sum the values of dictionary only if the keys is equal or greater than x - python-3.x

Given a dictionary which contains keys and values, and I want sum the values based on the keys value. For example, {1:10, 2:20, 3:30, 4:40, 5:50, 6:60}, and sum the values only if is equal or greater than 2 in keys, which output is 200.
x =2
count = 0
for key, value in dictionary.items():
while key == x:
count += 1[value]
And my output is none, and I don't know what I am missing on.

Try this. Your way of iterating over the dictionary items is correct, but inside the loop, you need to check if the current key is greater than or equal to your required key. Only then you should increment the count with the value corresponding to that key which can be retrieved in this way - dictionary[key] or you can simply add the value like count+=value
dictionary = {1:10, 2:20, 3:30, 4:40, 5:50, 6:60}
x=2
count = 0
for key,value in dictionary.items():
if key>=x:
count += dictionary[key]
print(count)

your code is incomplete and won't run as-is, so it's difficult to speculate why you're getting an output of None.
in your requirements you mention "equal or greater than 2" but your code has "key == x". This should be "key >= x".
inside your for loop you have a while. Fixing other issues this would result in an infinite loop. You want an if, not a while.
fixing those things and making an assumption or two, your code would be:
x = 2
count = 0
for key, value in dictionary.items():
if key >= x:
count += value
Alternately, you could write it in a single line of code:
sum ( v for k, v in dictionary.items() if k >= x )

I believe you just need to do as below:
count = 0
for key, value in dictionary.items():
if key >= n:
count += value

Related

Getting lowest non-zero value from a dictionary

I am trying to get the largest and smallest value / values from a dictionary.
Where the lowest value should not be zero, but the closest to it.
If there is a 0 present and the values are K:0 K:3 K:7 K:1 it should return 1 and not 0.
I've tried using the min / max functions, but haven't been able to get them to work properly. Want to get all values even when there are multiple.
Example Dictionary.
Dict = {"D1" : "0", "D2" : "2", "D3" : "7", "D4" : "7", "D5" : "4"}
Highest = max(Dict, key=Dict.get)
Lowest = min(Dict, key=Dict.get)
Only gets me D3 and D1 respectively. Also returns the 0.
Highest works in most cases, but Lowest returns the 0. Should there be a check after lowest has been assigned and iterate over the dictionary again?
Highest and Lowest can be a list or a single Value doesn't really matter.
My current code looks something like this.
Dict = {"D1" : "0", "D2" : "2", "D3" : "7", "D4" : "7", "D5" : "4"}
Highest = max(Dict, key=Dict.get)
Lowest = min(Dict, key=Dict.get)
for key, value in Dict.items():
if value == Dict[Highest]:
Do x
elif value == Dict[Lowest]:
Do y
else:
Do z
Which mostly works, except for the above mentioned 0 getting returned.
Edit
Was doing some more testing and the dictionaries received had a chance to be full of zero values or the same positive integer.
Which made the solution a bit wonky.
Decided to change it up a bit and iterate over the items instead by assigning a start value for both highest and lowest.
When iterating through the dictionary I assigned new values to highest and lowest if they were either > or < respectively.
Something like the code below. (Tried to comment with some code, but the formatting got messed up, so decided to edit the question a bit instead).
Highest = -1
Lowest = 1000000 # Highest Value the dictionary values may have
for key in dict:
if dict[key] > Highest and dict[key] != 0:
Highest = dict[key]
if dict[key] < Lowest and dict[key] != 0:
Lowest = dict[key]
# Then possible to iterate over the dictionary and get the highest and lowest values from the dictionary.
for key, value in dict.items():
if value == Highest and Highest != -1:
Do X
elif value != 0:
if value == Lowest and Lowest != 1000000:
Do Y
else:
Do z
else:
Do z
You need to filter first, then min/max the filtered data. Sticking to your design as closely as possible:
nozeroes = {k: v for k, v in Dict.items() if v > 0} # New dict with only positive values
# Only change to original version is replacing Dict with nozeroes
Highest = max(nozeroes, key=Dict.get)
Lowest = min(nozeroes, key=Dict.get)
Note: If you just want the values themselves, and don't care about the keys, this is even easier:
nonzero_values = [v for v in Dict.values() if v > 0]
Highest = max(nonzero_values)
Lowest = min(nonzero_values)
from math import inf
Dict = {"D1": "0", "D2": "2", "D3": "7", "D4": "7", "D5": "4"}
Highest = max(Dict, key=lambda x: Dict[x] or inf)
Lowest = min(Dict, key=lambda x: Dict[x] or inf)

What's the best way to search a text file for consecutive repetitions and return the text with highest number of them?

I'm extremely new to programming in general and have only been learning Python for 1 week.
For a class, I have to analyze a text DNA sequence, something like this:
CTAGATAGATAGATAGATAGATGACTA
for these specific keys: AGAT,AATG,TATC
I have to keep track of the largest number of consecutive repetitions for each, disregarding all but the highest number of repetitions.
I've been pouring over previous stackoverflow answers and I saw groupby() suggested as a way to do this. I'm not exactly sure how to use groupby for my specific implementation needs though.
It seems like I will have to read the text sequence from a file into a list. Can I import what is essentially a text string into a list? Do I have to separate all of the characters by commas? Will groupby work on a string?
It also looks like groupby would give me the highest incident of consecutive repetitions, but in the form of a list. How would I get the highest result from that list out of that list to them be stored somewhere else, without me the programmer having to look at the result? Will groupby return the highest number of consecutive repeats first in the list? Or will it be placed in order of when it occured in the list?
Is there a function I can use to isolate and return the sequence with the highest repetition incidence, so that I can compare that with the dictionary file I've been provided with?
Frankly, I really could use some help breaking down the groupby function in general.
My assignment recommended possibly using a slice to accomplish this, and that seemed somehow more daunting to try, but if that's the way to go, please let me know, and I wouldn't turn down a mudge in the direction on how in the heck to do that.
Thank you in advance for any and all wisdom on this.
Here's a similar solution to the previous post, but may have better readability.
# The DNA Sequence
DNA = "CTAGATAGATAGATAGATAGATGACTAGCTAGATAGATAGATAGATAGATGACTAGAGATAGATAGATCTAG"
# All Sequences of Interest
elements = {"AGAT", "AATG", "TATC"}
# Add Elements to A Dictionary
maxSeq = {}
for element in elements:
maxSeq[element] = 0
# Find Max Sequence for Each Element
for element in elements:
i = 0
curCount = 0
# Ensure DNA Length Not Reached
while i+4 <= len(DNA):
# Sequence Not Being Tracked
if curCount == 0:
# Sequence Found
if DNA[i: i + 4] == element:
curCount = 1
i += 4
# Sequence Not Found
else: i += 1
# Sequence Is Being Tracked
else:
# Sequence Found
if DNA[i: i + 4] == element:
curCount += 1
i += 4
# Sequence Not Found
else:
# Check If Previous Max Was Beat
if curCount > maxSeq[element]:
maxSeq[element] = curCount
# Reset Count
curCount = 0
i += 1
#Check If Sequence Was Being Tracked At End
if curCount > maxSeq[element]: maxSeq[element] = curCount
#Display
print(maxSeq)
Output:
{'AGAT': 5, 'TATC': 0, 'AATG': 0}
This doesn't seem like a groupby problem since you want multiple groups of the same key. It would easier to just scan the list for key counts.
# all keys (keys are four chars each)
seq = "CTAGATAGATAGATAGATAGATGACTAGCTAGATAGATAGATAGATAGATGACTAGAGATAGATAGATCTAG"
# split key string into list of keys: ["CTAG","ATAG","ATAG","ATAG", ....]
lst = [seq[i:i+4] for i in (range(0,len(seq),4))]
lst.append('X') # the while loop only tallies when next key found, so add fake end key
# these are the keys we care about and want to store the max consecutive counts
dicMax = { 'AGAT':0, 'AATG':0, 'TATC':0, 'ATAG':0 } #dictionary of keys and max consecutive key count
# the while loop starts at the 2nd entry, so set variables based on first entry
cnt = 1
key = lst[0] #first key in list
if (key in dicMax): dicMax[key] = 1 #store first key in case it's the max for this key
ctr = 1 # start at second entry in key list (we always compare to previous entry so can't start at 0)
while ctr < len(lst): #all keys in list
if (lst[ctr] != lst[ctr-1]): #if this key is different from previous key in list
if (key in dicMax and cnt > dicMax[key]): #if we care about this key and current count is larger than stored count
dicMax[key] = cnt #store current count as max count for this key
#set variables for next key in list
cnt = 0
key = lst[ctr]
ctr += 1 #list counter
cnt += 1 #counter for current key
print(dicMax) # max consecutive count for each key
Raiyan Chowdhury suggested that the sequences may overlap, so dividing the base sequence into four character strings may not work. In this case, we need to search for each string individually.
Note that this algorithm is not efficient, but readable to a new programmer.
seq = "CTAGATAGATAGATAGATAGATGACTAGCTAGATAGATAGATAGATAGATGACTAGAGATAGATAGATCTAG"
dicMax = { 'AGAT':0, 'AATG':0, 'TATC':0, 'ATAG':0 } #dictionary of keys and max consecutive key count
for key in dicMax: #each key, could divide and conquer here so all keys run at same time
for ctr in range(1,9999): #keep adding key to itself ABC > ABCABC > ABCABCABC
s = key * ctr #create string by repeating key "ABC" * 2 = "ABCABC"
if (s in seq): # if repeated key found in full sequence
dicMax[key]=ctr # set max (repeat) count for this key
else:
break; # exit inner for #done with this key
print(dicMax) #max consecutive key counts

Python losing track of index location in for loop when my list has duplicate values

I'm trying to iterate over pairs of integers in a list. I'd like to return pairs where the sum equals some variable value.
This seems to be working just fine when the list of integers doesn't have repeat numbers. However, once I add repeat numbers to the list the loop seems to be getting confused about where it is. I'm guessing this based on my statements:
print(list.index(item))
print(list.index(item2))
Here is my code:
working_list = [1,2,3,4,5]
broken_list = [1,3,3,4,5]
def find_pairs(list, k):
pairs_list = []
for item in list:
for item2 in list:
print(list.index(item))
print(list.index(item2))
if list.index(item) < list.index(item2):
sum = item + item2;
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
### First parameter is the name is the list to check.
### Second parameter is the integer you're looking for each pair to sum to.
find_pairs(broken_list, 6)
working_list is fine. When I run broken_list looking for pairs which sum to 6, I'm getting back (1,5) but I should also get back (3,3) and I'm not.
You are trying to use list.index(item) < list.index(item2) to ensure that you do not double count the pairs. However, broken_list.index(3) returns 1 for both the first and second 3 in the list. I.e. the return value is not the actual index you want (unless the list only contains unique elements, like working_list). To get the actual index, use enumerate. The simplest implementation would be
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for j, item2 in enumerate(list):
if i < j:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
For small lists this is fine, but we could be more efficient by only looping over the elements we want using slicing, hence eliminating the if statement:
def find_pairs(list, k):
pairs_list = []
for i, item in enumerate(list):
for item2 in list[i+1:]:
sum = item + item2
if sum == k:
pair = (item, item2)
pairs_list.append(pair)
return pairs_list
Note on variable names
Finally, I have to comment on your choice of variable names: list and sum are already defined by Python, and so it's bad style to use these as variable names. Furthermore, 'items' are commonly used to refer to a key-value pair of objects, and so I would refrain from using this name for a single value as well (I guess something like 'element' is more suitable).

Why am I getting the wrong values?

player_list= {'peter':0, 'karel':0}
naam = input("Welke speler moet een score + 1 krijgen?")
for key, value in player_list.items():
player_list[naam] = value + 1
print(player_list)
Can someone explain me I why get the correct value whenever I enter "peter" but not when I enter "karel"?
I assume, that you'd like to increment dict value of the key which is same as the string that user provides via input. Ask yourself, do you really need to iterate over dict items to do such thing? Dict is key-value structure, and you can access value of the key whenever you provide this key directly.
>>> player_list = {'peter':0, 'karel':0}
>>> player_list['peter']
0
Setting value to the existing dict key is easy. All you need to do is:
>>> player_list['peter'] = 3
>>> player_list['peter']
3
If you'd like to increment value for 'peter' you need to take whatever is stored under 'peter' and add one, but there is no need to iterate over dict items to do that. Like with any other variable, dict element is kind of placeholder for some space of memory that you can access via that placeholder. So in case of any variable you'd do something as:
>>> x = 1
>>> x = x + 1 # or x += 1 for short
...and in case of dict element, you can do the same:
>>> player_list['peter'] = player_list['peter'] + 1 # or:
>>> player_list['peter'] += 1
If you're curious why your current code doesn't work as you expected, run your code using debugger or just add print function:
for key, value in player_list.items():
print("Current key: {}, current value: {}".format(key, value))
player_list[naam] = value + 1
In fact, it's always good to use some debugging tools whenever you don't know why your code execution is different than your expected result.

How to retrieve the max key and max value from a dictionary?

a = ['also', 'akin', 'akee','ague', 'aero', 'anes','here','beer','bute', 'byre', 'came', 'case', 'doze', 'down', 'drek', 'drew', 'dyes', 'fret', 'freo']
i = 'e'#i is user guess input
dic = {}
for item in a:
key = ''
for chr in item:
if chr == i:
key += i
else:
key += '-'
if key not in dic:
dic[key] = []
dic[key].append(item)
print(dic)
c = max(k for k, v in dic.items())
d = max(v for k, v in dic.items())
print('\nmax key:',c)
print('\nmax value:',d)
Output:
{'---e': ['ague', 'bute', 'byre', 'came', 'case', 'doze'], '--ee': ['akee'], '----': ['also', 'akin', 'down'], '-e-e': ['here'], '-ee-': ['beer'], '--e-': ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo'], '-e--': ['aero']}
max key: -ee-
max value: ['here']
In the above example, a is a list of words. When the user guess a letter, for example 'e', the program iterates through each word in the list. Replace any letter that is not 'e' to a dash '-'.
I tried to map that result into a dictionary to keep track of the each group of words that where letter 'e' occurs in the same position.
Now, i want to retrieve the group of words(or key) with the largest number of words. Judging by the output, i'm not doing that because key'-e--' has the largest number of words.
I've also tried
max(dic.keys())
max(dic)
dic.get(max(dic.keys()))
Am i not fully understand the concept of max key and values for a dictionary?
Please suggest how i can fix this.
Thanks
In your question, the notion of max means being associated with the largest list., or being the largest list
max(dic.keys(), key=lambda x: len(dic[x]))
Will give you the maximum of dic's keys
Also,
sorted(dic.items(), key=lambda x:len(x[1]), reverse=True)
(in this example, lambda (x, y): len(y) works in python 2, not sure about python 3)
Will output a list of key, value tuples sorted by number of matches:
[('---e', ['ague', 'bute', 'byre', 'came', 'case', 'doze']), ('--e-', ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo']), ('----', ['also', 'akin', 'down']), ('-e-e', ['here']), ('--ee', ['akee']), ('-e--', ['aero']), ('-ee-', ['beer'])]
Edit, no lambda
Without using a lambda, you'd be using a regular function:
def myMax(value_tuple):
key, value = value_tuple
return len(value)
and using it like so:
max(dic.items(), key=myMax)
Retrieve max key:
max(MyDictionary.keys(), key=type).
Retrieve max value:
max(MyDictionary.values(), key=type)
Replace type with the key type in both cases. i.e int
Hope it helps.

Resources