How to Find The Top 3 Maximum Values in a Swift Dictionary

How do you find a maximum value in a Swift dictionary?

let maximum = data.reduce(0.0) { max($0, $1.1) }

Just a quick way using reduce.

or:

data.values.max()

Output:

print(maximum) // 5.828

How do you find the top 3 maximum values in a Swift dictionary?

The max method can only return a single value. If you need to get the top 3 you would need to sort them in descending order and get the first 3 elements using prefix method



let greatestChampion = champions.sorted { $0.value > $1.value }.prefix(3)

print(greatestChampion)

This will print

[(key: "Neeko", value: 25), (key: "Ekko", value: 20), (key: "Ahri", value: 10)]

How can I get the largest value from an integer array in a dictionary of arrays

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
var largest_kind : String? =nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largest_kind = kind
}
}
}

find the largest three Numbers on the array of int swift

You are appending to result inside the loop, every time you find a new maximum for first, second or thrid. This can happen more than 3 times. But the required array contains exactly 3 elements. Clearly, you shouldn't do add the result inside the loop.

You should only append to result at the end of the loop, the values first, second and thrid. You might as well just return the array literal [first, second, thrid] directly:

func largestThreeNumbers(_ array: [Int]) -> [Int] {
var first = 0
var second = 0
var third = 0
if array.count < 3 {
print("Invalid Input")
return []
}

for element in array {
if element > first{
third = second
second = first
first = element

}
else if element > second {
third = second
second = element


}
else if element > third {
thrid = element

}
}
return [first, second, third]
}

Highest frequency element in the dictionary

You have correctly constructed num1Dict, which will be something like this for the input [3,2,3]:

[2:1, 3:2]

values.max() will return 2, because out of all the values in the dictionary (1 and 2), 2 is the highest.

See your error now?

You need to return the key associated with the highest value, not the highest value.

One very straightforward way is to do this:

func majorityElement(_ nums1: [Int]) -> Int? { // you should probably return an optional here in case nums1 is empty

let num1Dict = Dictionary(nums1.map{ ($0, 1) }, uniquingKeysWith : +)
var currentHigh = Int.min
var mostOccurence: Int?
for kvp in num1Dict {
if kvp.value > currentHigh {
mostOccurence = kvp.key
currentHigh = kvp.value
}
}
return mostOccurence

}

How can I sort or filter a dictionary using the highest Int values?

You could obtain this by sorting and then filtering your list. For this, you'll use some of Swift's standard high-level functions:

//define basics
let basics = ["harry": 89, "chris": 33, "jane": 98, "hans": 90, "finn": 98 ]
//sort basics by the age value from highest to lowest
let sortedBasics = basics.sorted { $0.value > $1.value }
//filter the list to remove any elements with a value lower than our recorded high
let filteredBasics = sortedBasics.filter { $1 == sortedBasics.first?.value }
print(filteredBasics) //[("jane", 98), ("finn", 98)]

For reference: The $0 and $1 are considered "shorthand" names for the inferred parameters of the filter and sorted functions. Also note that these two functions are not mutating, so basics still remains in the same state.

How to get the 3 items with the highest value from dictionary?

You can simply use sorted() to get the keys of dict as:

my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}

my_keys = sorted(my_dict, key=my_dict.get, reverse=True)[:3]
# where `my_keys` holds the value:
# ['K', 'B', 'A']

OR, you may use collections.Counter() if you need value as well:

from collections import Counter
my_dict = {"A":3,"B":4,"H":1,"K":8,"T":0}

c = Counter(my_dict)

most_common = c.most_common(3) # returns top 3 pairs
# where `most_common` holds the value:
# [('K', 8), ('B', 4), ('A', 3)]

# For getting the keys from `most_common`:
my_keys = [key for key, val in most_common]

# where `my_keys` holds the value:
# ['K', 'B', 'A']


Related Topics



Leave a reply



Submit