I was attempting to create a program that would take a user input which would be a string of numbers and print out how many times each number occurred. However, I receive a TypeError stating that the int object is not iterable? How would I fix this and why is it happening? Thank you.
def main():
count = {}
user_input = input("Enter numbers separated by spaces: ")
for number in user_input.split():
if number in count:
count[number] = count[number] + 1
else:
count[number] = 1
print(count)
for k,v in count.values():
if v == 1:
print(k,"occurs one time")
else:
print(k,"occurs",v,"times")
main()
Replace:
for k,v in count.values():
With:
for k,v in count.items():
For your loop, you need both the key, k, and the value, v. count.values() will return only the values. count.items(), by contrast, will return both.
For every key check its value like this:
for key in count:
if count[key] == 1:
print(key,"occurs one time")
else:
print(key,"occurs",count[key],"times")
count.values() method returns only values in dictionary not keys. count.items() will return you key value pairs.
Related
n = int(input())
MyDict = {}
key = []
value = []
check_key = []
for i in range(0,n):
inp = input().split()
key.append(inp[0])
value.append(inp[1])
MyDict = dict(zip(key,value))
for j in range(0,n):
check_inp = input()
check_key.append(check_inp)
for k in check_key:
if k in MyDict:
print("{}={}".format(k,MyDict[k]))
else:
print("Not found")
This is all I have written
Please help me to do it more efficiently
I can't find the error in test case
can anyone please help me to figure out error
I'm stuck here for 3-Days
problem Image
Test Case Results
It seems what youre asking is that you want to query keys in your dict and if there are no results corresponding to that key it should yield the proper message otherwise return its value. if so:
a = {'sam' : 99999999,
'tom' : 11111111,
'har' : 22222222,}
a.get('sam')
a.get('edw')
a.get('har')
returns:
99999999
None
22222222
I think the reason that your tests fail is because you're not giving back a response when they are polling for phoneNumbers. Also Your script will also gather n amounts of names to check against the phoneBook which according to the specifications in the question it should not.
I've simplified your code a little and removed unnecessary variables:
# the number of entries on the phoneBook
n = int(input())
phoneBook = {}
for i in range(n):
k, v = input().split()
phoneBook[k] = v
while True:
# the name to lookup in the phonebook
name = input()
# Exit condition if we don't get any input.
if name == "":
break
# Tries to get the phoneNumber via the given name in the phoneBook
try:
print("{}={}".format(name,phoneBook[name]))
# If 'name' is not inside of the dictionary, it raises an KeyError
# which we catch here to instead just print out "Not found"
except KeyError:
print("Not found")
Output from one of my tests:
3
asdasd 123123123
jkdjkjkfd 129020990201
jkasjkldlk 1991991991
kalsdkl
Not found
asdasd
asdasd=123123123
Try this and see if that solves the problem for you.
I am trying to update dictionary by taking input from the user, pls help me in doing that.
Below is the code i am trying to implement.
n = int(input("enter a n value:"))
d = {}
for i in range(n):
keys = input() # here i have taken keys as strings
values = int(input()) # here i have taken values as integers
d[keys] = values
print(d)
c = {}
key = input()
valu = int(input())
c[key] = valu
d.update({c})
There's a bug in the last line of your code. {c} tries to create a set using c as its element which is not allowed as dict object is not hashable. Change you last line to: d.update(c) and it should work.
I am trying to build a function which returns the most occurred character in a given string and it's working pretty nicely, but how do I return None if the characters have same frequency?
Like for input: 'abac'
Expected output is: 'a'
and for input: 'abab'
Expected output is: None
I have tried using a dictionary to store character frequency and then returning the element with largest value.
def most_occuring_char(str1):
count = {}
max = 0
c = ''
for char in str1:
if char in count.keys():
count[char]+=1
else:
count[char] = 1
for char in str1:
if max < count[char]:
max = count[char]
c = char
return c
I don't know how to check whether the count dictionary elements have same frequency.
You can do that counting with the dict using collections.Counter.
You basically only have to add a check to see if the maximum count is unique (if so, return the char with maximum number of occurrences) or not (if so, return None):
from collections import Counter
def most_occurring_char(string):
counter = Counter(string)
max_char_count = max(counter.values())
is_unique = len([char_count for char_count in counter.values() if char_count == max_char_count]) == 1
if is_unique:
char = [char for char, count in counter.items() if count == max_char_count][0]
return char
return None
# Tests
assert most_occurring_char('abac') == 'a'
assert most_occurring_char('abab') is None
Once you have a dictionary containing the counts of every character (after your first for loop), you can inspect this to determine whether certain counts are the same or not.
If you wish to return None only when all the character counts are the same, you could extract the values (i.e. the character counts) from your dictionary, sort them so they are in numerical order, and compare the first and last values. Since they are sorted, if the first and last values are the same, so are all the intervening values. This can be done using the following code:
count_values = sorted(count.values())
if count_values[0] == count_values[-1]: return None
If you wish to return None whenever there is no single most frequent character, you could instead compare the last value of the sorted list to the second last. If these are equal, there are two or more characters that occur most frequently. The code for this is very similar to the code above.
count_values = sorted(count.values())
if count_values[-1] == count_values[-2]: return None
Another possibility:
def most_occuring_char(s):
from collections import Counter
d = Counter(s)
k = sorted(d, key=lambda x:d[x], reverse=True)
if len(k) == 1: return k[0]
return None if len(k) == 0 or d[k[0]] == d[k[1]] else k[0]
#Test
print(most_occuring_char('abac')) #a
print(most_occuring_char('abab')) #None (same frequencies)
print(most_occuring_char('x')) #x
print(most_occuring_char('abcccba')) #c
print(most_occuring_char('')) #None (empty string)
I have a simple for loop iterating through a user input string. If the it encounters a certain value, I want to be able to look ahead at the next value in order to determine what to do next. What is the best way to accomplish this? For example in my code below, if it encounters a "1" in the string, it should look at the next character in the string. If it is also a 1, print 1. Otherwise do nothing.
UserInput = input("Enter calculator expression:")
for x in UserInput:
...
...
if x == 1:
# if the next value in the string is 1:
# print 1
# else:
# do nothing
Use range and len in the loop to get position address
UserInput = input("Enter calculator expression")
for i in range(len(UserInput)-1):
if x[i]=='1':
if x[i+1]=='1':
print "something"
else:
pass
You can zip a string with itself, but offset with a slice.
>>> from itertools import zip_longest
>>> the_input = 'foobar' # example
>>> the_input[1:] # slice off the first character
'oobar'
>>> for c, lookahead in zip_longest(the_input, the_input[1:]):
... print(c, lookahead)
...
f o
o o
o b
b a
a r
r None
This is more Pythonic than using an index like you would in a language like C.
Zipping pairs things elementwise, like the teeth of a zipper.
You can user enumerate() function.
something like this,
#!/user/bin/python3
for i,x in enumerate(UserInput):
if x=='1':
if UserInput[i+1] == '1':
print('1')
Firstly, python convention is snake-case (user_input instead)
code below is my solution
from itertools import islice
def window(seq, n=2):
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
pair = list(window(user_input))
comparison_list = ["1"]
result = [x for x,y in pair if x in comparison_list and x == y]
You don't need to look ahead. At least it is not what we usually do when we tackle this kind of problem. Instead, you should look backward - by storing the information. The following example stores the information in a variable state and you can decide the next action in the subsequent iteration.
UserInput = input("Enter calculator expression:")
state = '0'
for x in UserInput:
if x == '1':
if state == '1':
print('1')
else:
state = '1'
else:
state = '0'
A different (probably more pythonic) way of doing this with the zip function:
for char, next_char in zip(UserInput, UserInput[1:]):
if char == "1" and char == next_char:
print(1)
prev_char = None
for char in input("Enter calculator expression:"):
pass # Here you can check the current character and the previous character
if 1 == prev_char and 1 == char:
print(1)
prev_char = char
I have a program where by a teahcer can view the her student's squiz results and sort them in a avruiety way:
if role == 2:
class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
filename = (str(class_number) + "txt")
sort_or_not = prompt_int_small("Would youlike to sort these scores in any way? Press 1 if the answer is no or 2 if the answer is yes")
if sort_or_not == 1:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
lines.sort()
for line in lines:
print (line)
if sort_or_not == 2:
type_of_sort = prompt_int_big("How would you like to sort these scores? Press 1 for scores in alphabetical order with each student's highest score for the tests, 2 if you would like to see the students' highest scores sorted from highest to lowest and 3 if you like to see these student's average scores sorted from highest to lowest")
if type_of_sort == 1:
with open(filename , 'r') as r:
for line in sorted(r):
print(line, end='')
if type_of_sort == 2:
with open (filename,'r') as r:
def score(line):
return int(line.split(':')[1])
for line in sorted(r, key=score, reverse = True):
print(line)
if type_of_sort == 3:
with open (filename,'r') as r:
def score(line):
returnint(line.split(':')[1])
average = sum(map(int, score))/len(score)
print(name,"--",average)
However when the third option is selected an error comes up:
average = sum(map(int, score))/len(score)
TypeError-'function' object is not iterable
map() in Python-3.x returns an iterator (unlike Python-2.x where it returns a list of the result). Hence, you need to generate the list from the iterator and then pass it to the sum() function.
average = sum(list(map(int, score)))/len(score)
In the above, example score should be iterable like a list or a tuple.
EDIT: Well, map takes an iterable as an argument (like list, tuple) but in this case the argument passed, score, is a function. And you are passing the function name and not calling the function. Hence, a function gets passed to the map() function. So, you need to call the function. Eg:
score_list = score(r.readline())
average = sum(list(map(int, score_list)))/len(score_list)