For homework I have been set the following:
Build a dictionary with the names from myEmployees list as
keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary
and increase the salary of employees which names have more than four
letters with 1000 * length of their name. Print the dictionary contents before
and after the increase.
I can't figure out how to do it.
This is what I've come up with so far.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
First, change the values to integers/floats.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
After doing this, as you know, you need to loop over the items in the dict.
for x in employeeDict:
x = len(employeeDict)
if x > 5:
print employeeDict[x]
In the code above, your "x" will be the employee name. And as you know, to asign a value to a key in dict, you have to use dict[key] = value, so try to do it in the if x > 5: block statement. Im not trying to give you the full answer, but to push you in to the right direction.
You have some indentation problems, clearly, but the main problems are that you are taking the length of the dictionary (getting the number of keys) not taking the length of the key. You also have some bad logic.
employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", "Adren":"10,000"}
say = 'Before increase'
print say
print employeeDict
say1 = 'After increase'
print say1
for x in employeeDict:
length = len(employeeDict) # <---- indent this
if length >= 5: # <--- greater than 4
# convert string to number, add money, convert back to string
employeeDict[x] = str(int(employeeDict[x]) + 1000 * (length))
print employeeDict[x]
This should give you what your looking for.
employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000}
print "Before increase"
print employeeDict
for name, salary in employeeDict.items():
if len(name) > 4:
employeeDict[name] = salary + len(name) * 1000
print "After increase"
print employeeDict
You had a few problems in your version.
Your idention for your for-loop was not correct
You were getting the length of the dictionary and not the length of the keys in the dictionary.
You should make the values in your dictionary floats/integers.
Also note, I believe your homework said if the name was longer than four characters. So i used 4 instead of five.
Give this a try and analyse it :
employees = {"John":10000, "Daren":10000, "Graham":10000}
for name in employees:
if len(name) > 5:
employees[name] += 1000 * len(name)
If you have to stick with the string values you can do this :
employees = {"John":"10000", "Daren":"10000", "Graham":"10000"}
for name in employees:
if len(name) > 5:
employees[name] = str(int(employees[name]) + 1000 * len(name))
Related
Write a Python program that will take N names from the user. Create a dictionary from the N names that will hold First_name, Middle_name, and Last_name in separate keys. The inputs will take N at first and then take N names. You can assume that the names will contain less than or equal to 3 words.
Sample Input:
4
Zubayer Ahmed
Sadia Nur Amin
Mehedi Hasan Shawon
Nafis
Sample Output:
{ "Fname" : [“Zubayer”, “Sadia”, “Mehedi”, “Nafis”] , "Mname" : [“Nur”, “Hasan”], "Lname" : [“Ahmed”, “Amin”, “Shawon”] }
This problem requires you to first find the number of names needed, this can be done using a simple input() call.
numNames = int(input("> "))
we can also prepare the dictionary like so
nameDict = {"Fname":[],"Mname":[],"Lname":[]}
Then we need to iterate depending on the number the user has entered
for i in range(numNames):
During each iteration of the above for loop, you need to ask the user for a name, then split it into a list of each names names = input("name {i+1} > ").split(" ")
You can then add them to the dictionary as the problem requires using basic selection
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
This solution could be made more efficient if you can find a better way to sort the names into the dictionary.
Although StackOverflow isn't for your entire problems, more so questions about specific areas. Next time have a go at the problem and post if you get suck with details about your attempt.
But anyway, here is my full solution
numNames = int(input('names >'))
nameDict = {'Fname':[],'Mname':[],'Lname':[]}
for i in range(numNames):
names = input(f'name {i+1} > ').split(' ')
if len(names) >= 1:
nameDict["Fname"].append(names[0])
if len(names) == 2:
nameDict["Lname"].append(names[1])
elif len(names) == 3:
nameDict["Mname"].append(names[1])
nameDict["Lname"].append(names[2])
print(nameDict)
Here's my solution:
number_of_entries = int(input("How many entries would you like? "))
first_names = []
middle_names = []
last_names = []
i = 0
while i < number_of_entries:
full_name = input(": ")
names_array = full_name.split(' ')
if len(names_array) >= 1:
first_names.append(names_array[0])
if len(names_array) >= 2:
middle_names.append(names_array[1])
if len(names_array) >= 3:
last_names.append(names_array[2])
i += 1
names_dictionary = { "Fname" : first_names, "Mname" : middle_names, "Lname" : last_names}
print(names_dictionary)
It works by storing every category of name into an array first then adding that to the dictionary in the end.
In this homework, you must handle the initial 4 and read correctly the following input lines.
After that you will have a list of names, I think the best approach is the following
from itertools import zip_longest
names = ["Zubayer Ahmed","Sadia Nur Amin","Mehedi Hasan Shawon","Nafis"]
# split into single words
names = [x.split() for x in names]
# do a zip of the triads and remove None values
filtered = [ list(filter(None,_)) for _ in zip_longest(*names)]
#do the dict:
dict(zip( ("Fname","Mname", "Lname"), filtered))
the output:
{'Fname': ['Zubayer', 'Sadia', 'Mehedi', 'Nafis'],
'Mname': ['Ahmed', 'Nur', 'Hasan'],
'Lname': ['Amin', 'Shawon']}
I'm new to python. I am trying to make a generator that requires 3 letters from an input. I need it to only accept 3 letters no more no less. The if len i put does not work
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else (names):
print("Error! Must Be 3 Characters")
else requires no condition
import random
usernames = int(input("How Many Usernames Are To Be Generated?"))
names = []
for item in range(0,usernames):
names.append(input("What Is The First Three Letters of The Pupils Name?"))
if len(names) == 3:
suffixes = ["ing", "end", "axe", "gex", "goh"]
for name in names:
final = name + random.choice(suffixes)
print(final)
else :
print("Error! Must Be 3 Characters")
Why is names a list?
You have an empty list, name = [] .
Then you add one item to it .
names.append(input("What ..
This is why it fails, because the len of names is 1.
Either get rid of the list or check the len of the first item .
if len(names[0]) == 3
Im and MSc student who has been lumped with doing python code this year but have no prior experience. I was wondering if someone could help me with this question, i have some parts done.
Q6)
Assignment 6
Grades are classified according to % (ranging from 0 to 100 inclusive), if greater than or equal to the following:-
70 First ; 60 Second Upper ; 50 Second Lower ; 45 Third ; 40 Pass; 0 Fail.
Create a dictionary from the data above, and use it as part of a program to grade marks, from 2 sources:-
1. during development, grade marks in sequence from a hardcoded list of marks = [-1,0,1,49,60,71,100,101],
2. after development, include code to repeatedly request marks for testing, until terminated by entering q or Q.
Marks will be awarded for concise coding, which should run efficiently with minimal use of comparisons tests.
Retain features to take input from both sources above in the final code, i.e. don't delete item '1' after development.
My solution so far looks something like this :
hardcoded_lst = [-1,0,1,49,60,71,100,101]
grade_input=int(input('What grade?')
input_lst= []
while grade_input !=
input_lst.append(grade_input)
grade_input=int(input('What grade?')
print(input_lst)
i need to create a dictionary for the values but currently that isnt working either.
Id appreciate any help, in basic code as i am not very advanced.
Thanks
creating dictionary isn't that tough, its as simple as creating list, which you have already done
For list
mylist = []
#for dictionary
mydictionary = {}
Adding item into dictionary
mylist.append(value)
mydictionary["fail"] = 50
Iterating the list
for item in mylist:
print item
Iterating in dictionary
for key,value in mydictionary.iteritem():
print key,value
I hope this helps you, there might be mistake in iteritem spelling etc you could google it but thats how its done normally
here is updated thing
mydictionary = {}
marks = 0
mydictionary[(0,45)] = "Fail"
mydictionary[(46,59)] = "Lower"
mydictionary[(60,69)] = "Second Lower"
mydictionary[(70,100)] = "First"
marks = 63
for key,value in mydictionary.iteritems():
if marks >= key[0] and marks <= key[1]:
print value
The given code works you could also do it in this way though
The following program should do as you asked. There are several lines that are commented out with the # character. You may uncomment those lines if you wish to see the value of the variable referenced in the call to the debug function. Please take time to study the code so that you understand how and why it works.
import pprint
import sys
RANGE = range(0, 101)
GRADE = {70: 'First', 60: 'Second Upper',
50: 'Second Lower', 45: 'Third',
40: 'Pass', 0: 'Fail'}
MARKS = -1, 0, 1, 49, 60, 71, 100, 101
def main():
"""Grade hardcoded marks and grade marks entered by the user."""
# debug('MARKS')
grade_all(MARKS)
grade_all(get_marks())
print('Goodbye!')
def grade_all(marks):
"""Take an iterable of marks and grade each one individually."""
for mark in marks:
# debug('mark')
if mark in RANGE:
print(mark, 'gets a grade of', grade_one(mark))
else:
print(mark, 'is not a valid mark')
def grade_one(mark):
"""Find the correct grade for a mark while checking for errors."""
# debug('RANGE')
if mark in RANGE:
for score, grade in sorted(GRADE.items(), reverse=True):
if mark >= score:
return grade
raise ValueError(mark)
def get_marks():
"""Create a generator yielding marks until the user is finished."""
while True:
try:
text = input('Mark: ')
except EOFError:
sys.exit()
else:
# debug('text')
if text.upper() == 'Q':
break
try:
mark = round(float(text))
except ValueError:
print('Please enter a mark')
else:
# debug('mark')
if mark in RANGE:
yield mark
else:
print('Marks must be in', RANGE)
def debug(name):
"""Take the name of a variable and report its current status."""
frame, (head, *tail) = sys._getframe(1), name.split('.')
for scope, space in ('local', frame.f_locals), ('global', frame.f_globals):
if head in space:
value = space[head]
break
else:
raise NameError('name {!r} is not defined'.format(head))
for attr in tail:
value = getattr(value, attr)
print('{} {} {} = {}'.format(
scope, type(value).__name__, name, pprint.pformat(value)), flush=True)
if __name__ == '__main__':
main()
You need to create a dictionary using the grade values as keys, and depending on the input populate the key with the input, or reject it as invalid. Maybe something like this:
if input>=70:
grade[first]=input
elif input>=60 and input<70:
grade[secondupper]=input
elif input<0 or input>100:
print 'invalid grade!'
If you have more than one value for each grade then consider using a list to read the values into, and then setting the corresonding dictionarty value to the list as you fill it.
I have a nested dictionary that I'm using to pull values. I'm using letters as keys with values dependent on the letter location within the string.
I'm trying to code it so that as the letter is found within the string, it pulls the value that is accurate for its position within the string. I have 3 locations - "starter" and "finisher" are the first and last 4 characters respectively. Anything else is "mid".
I've tried getting the character's position within the string to be taken as an integer that I can easily input into a conditional sequence.
def Calc(letterstring, data_table):
Places= len(string)
Score = 0.0
for i in range(Places):
letter= string[i]
if [i] >= int(3) and [i] <= ((Places)-4):
position_in_string = "Starter"
elseif [i] >= ((Places)-4):
position_in_string = "Finisher"
else:
position_in_string = "Mid"
position = (position_in_string)
Score += data_table[letter][position]
return Score
string = input("Insert your line here: ") # Something like ABCDEFGHIJKLMNOP
total_score= (Calc((string), (data_table)))
print (total_score)
And I would expect an output of an integer.
But if I try to do it this way, I end up with:
TypeError: unorderable types: list() >= int()
Any advice or observations would be welcome!
Some changes I'd recommend:
Python has an enumerate builtin that will take a sequence (including a string) and return both the index and the value for each element in the sequence
Use letterstring consistently in your function, and in general, using "string" as a variable name is frowned upon
I'm assuming data_table is a dict of dictionaries, such that the outer dictionary has keys = to 'A-Z' (note the .upper() to ensure that 'a' gets converted to 'A' etc. You should probably also add some error checking in case a user puts in ABC1), and the inner dictionary has the 3 strings you set (Starter, Finisher, and Mid)
no idea why this is getting dorked up formatting
def Calc(letterstring, data_table):
Score = 0.0
ls = len(letterstring)
for i,letter in enumerate(letterstring):
if i < 4:
position_in_string = "Starter"
elif i >= (ls-4):
position_in_string = "Finisher"
else:
position_in_string = "Mid"
Score += data_table[letter][position_in_string]
return Score
instring = input("Insert your line here: ") # Something like ABCDEFGHIJKLMNOP
total_score= Calc(instring.upper(), data_table)
print (total_score)
I am on a step of a question that I cannot answer. The first part is:
full_name = input('Enter your full name ')
The second part is to use a while loop to print the name out backwards like from 'John Finger' to 'regniF nhoJ'.
It has to be done using a while loop, which is kind of weird to me since nothing I have read demonstrates anything like that with a while loop.
This is the usual way to do this:
print(full_name[::-1])
But this is probably what is meant:
full_name = input('Enter your full name ')
pos = len(full_name) - 1
while pos >= 0:
print(full_name[pos], end="")
pos -= 1
print()
There are several different way to do this, and it is a standard programming exercise which would work (in principle) in many languages. It is not Pythonic though. The problem is that a new string object is created for each character, which is inefficient.
reverse_name =""
i = len(full_name)
while i > 0:
reverse_name += full_name[i-1]
i -=1
Length: Get Length of string by len in-build function.
Decrement count by 1 because string index start from the 0
Apply while loop with condition count greater then -1.
String Concatenation: Add two string variables.
Print result.
Demo:
>>> full_name = "John Finger"
>>> result = ""
>>> count = len(full_name)
>>> print "lenght:", count
lenght: 11
>>> count -= 1
>>> while count>-1:
... result +=full_name[count]
... count -= 1
...
>>> result
'regniF nhoJ'
import sys
name = 'John Finger'
index = len(name) - 1
while index >= 0:
sys.stdout.write(name[index])
index -= 1