update value in python dictionary by adding a number - python

I want to make a program that adds a name in the dictionary if it doesn't exist already and count the times it is given as input. My code works, however, it doesn't add 1 when it iterates.
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] += 1
# else wasn't properly indented earlier
else:
namelist[word] = 1
print(namen())
print(namelist)

You can use the dict.get method instead to provide a default value to a new entry to the dict:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] = namelist.get(word, 0) + 1

Your check is incorrect, you need if rather than for to see if the key exists, then you can remove the inner if statement
if name in namelist:
namelist[word] += 1
else:
namelist[word] = 1

No one said anything about the has_key method of dictionaries, which is in my opinion the standard way to to this:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
if namelist.has_key(word):
namelist[word] += 1
else:
namelist[word] = 1
print(namen())
print(namelist)

try this
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
try:
namelist[word] += 1
except:
namelist[word] = 1
print(namen())
print(namelist)

Related

Can I fix the index out of range error when I try to get a different word out of the last place of a list with all the same words

For this exercise I can input words until i enter "stop". All the words that I have input will go in to a list. I use a for loop to loop over all the words in the list. If the word isnt the same as the next or previous I "mark" that word.If there are no marked words it wil print out that there are none.If there are 2 or more marked words it will print that it cant be known. This works well until the last word in the list is the "marked" one. I get the error list index out of range. Does anyone see a solution for this? Below I will paste the code.
Thank you!
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`
I tried to check if the index is at the last place that it would check the previous 2 words to see if they are the same. But this didnt have any effect
woorden = []
woord = str(input())
vreemdeEend = 0
vreemdWoord = ""
while woord != "stop":
woorden.append(woord)
woord = str(input())
if len(woorden)>0:
woorden.append(woorden[-1] + "DIFRENCE")
for index, elem in enumerate(woorden):
if (woorden[index] != woorden[index-1] and woorden[index] != woorden[index+1] and woorden[index-1] != 0):
vreemdeEend += 1
vreemdWoord = woorden[index]
if(vreemdeEend == 1):
print("De vreemde eend in de bijt is " + vreemdWoord)
elif(vreemdeEend >= 2):
print("vreemd eend is onbeduid")
else:
print("er is geen vreemd eend")`

Variable not defined even though it exists

This is a simple code I wrote for the flanker task:
import random
congruent = open('congruent.txt', 'r')
incongruent = open('incongruent.txt', 'r')
def createList(file):
lst = []
for row in file:
lst.append(row.strip('\n'))
return lst
file.close()
lstCongruent = createList(congruent)
lstIncongruent = createList(incongruent)
nr_trials = 20
def middleString(txt):
middle = txt[(len(txt)-1)//2]
return middle
def checkCongruency(item):
if item in lstCongruent:
correctCongruentAnswers = 0
correctCongruentAnswers += 1
return correctCongruentAnswers
elif item in lstIncongruent:
correctIncongruentAnswers = 0
correctIncongruentAnswers += 1
return correctIncongruentAnswers
for i in range(nr_trials):
rndItem = random.choice(lstCongruent + lstIncongruent)
print(rndItem)
answer = input('Please write your answer: ')
if answer == 'STOP':
exit()
while answer != 'F' and answer != 'J':
print('\33[91m Please type only F or J \33[0m')
break
if middleString(rndItem) == '<' and answer == 'F':
print('Correct answer!')
checkCongruency(rndItem)
elif middleString(rndItem) == '>' and answer == 'J':
print('Correct answer!')
checkCongruency(rndItem)
else:
print('Incorrect answer')
print('Correct congruent answers: ', correctCongruentAnswers)
print('Correct incongruent answers: ', correctIncongruentAnswers)
But when I run it, I get:
File "main.py", line 68, in <module>
print('Correct congruent answers: ', correctCongruentAnswers)
NameError: name 'correctCongruentAnswers' is not defined
is there any way to solve this without completely changing the code? I've tried different things, like defining the functions inside the for loop or some other stuff, but it won't work.
Since variable inside functions can only be use within the function, you can declare them as being global variables, albeit this is not good practice.
def checkCongruency(item):
global correctCongruentAnswers #here
global correctIncongruentAnswers #and here
if item in lstCongruent:
correctCongruentAnswers = 0
correctCongruentAnswers += 1
return correctCongruentAnswers
elif item in lstIncongruent:
correctIncongruentAnswers = 0
correctIncongruentAnswers += 1
return correctIncongruentAnswers

Python reverse each word in a sentence without inbuilt function python while preserve order

Not allowed to use "Split(),Reverse(),Join() or regexes" or any other
helping inbuilt python function
input something like this:
" my name is scheven "
output like this:
"ym eman si nevehcs"
you need to consider removing the starting,inbetween,ending spaces aswell in the input
I have tried 2 tries, both failed i will share my try to solve this and maby an idea to improve it
First try:
def reverseString(someString):
#lenOfString = len(someString)-1
emptyList = []
for i in range(len(someString)):
emptyList.append(someString[i])
lenOfString = len(emptyList)-1
counter = 0
while counter < lenOfString:
if emptyList[counter] == " ":
counter+=1
if emptyList[lenOfString] == " ":
lenOfString-=1
else:
swappedChar = emptyList[counter]
emptyList[counter] = emptyList[lenOfString]
emptyList[lenOfString] = swappedChar
counter+=1
lenOfString-=1
str_contactantion = ""
#emptyList = emptyList[::-1]
#count_spaces_after_letter=0
for letter in emptyList:
if letter != " ":
str_contactantion+=letter
#str_contactantion+=" "
str_contactantion+=" "
return str_contactantion
second try:
def reverse(array, i, j):
emptyList = []
if (j == i ):
return ""
for k in range(i,j):
emptyList.append(array[k])
start = 0
end = len(emptyList) -1
if start > end: # ensure i <= j
start, end =end, start
while start < end:
emptyList[start], emptyList[end] = emptyList[end], emptyList[start]
start += 1
end -= 1
strconcat=""
for selement in emptyList:
strconcat+=selement
return strconcat
def reverseStr(someStr):
start=0
end=0
help=0
strconcat = ""
empty_list = []
for i in range(len(someStr)):
if(someStr[i] == " "):
continue
else:
start = i
j = start
while someStr[j] != " ":
j+=1
end = j
#if(reverse(someStr,start,end) != ""):
empty_list.append(reverse(someStr,start,end))
empty_list.append(" ")
for selement in empty_list:
strconcat += selement
i = end + 1
return strconcat
print(reverseStr(" my name is scheven "))
The following works without managing indices:
def reverseString(someString):
result = crnt = ""
for c in someString:
if c != " ":
crnt = c + crnt # build the reversed current token
elif crnt: # you only want to do anything for the first space of many
if result:
result += " " # append a space first
result += crnt # append the current token
crnt = "" # and reset it
if crnt:
result += " " + crnt
return result
reverseString(" my name is scheven ")
# 'ym eman si nevehcs'
Try this:
def reverseString(someString):
result = ""
word = ""
for i in (someString + " "):
if i == " ":
if word:
result = result + (result and " ") + word
word = ""
else:
word = i + word
return result
You can then call it like this:
reverseString(" my name is scheven ")
# Output: 'ym eman si nevehcs'
Try this:
string = " my name is scheven "
def reverseString(someString):
result = ''
curr_word = ''
for i in someString:
if i == ' ':
if curr_word:
if result:
result = f'{result} {curr_word}'
else:
result = f'{result}{curr_word}'
curr_word = ''
else:
curr_word = f'{i}{curr_word}'
return result
print(repr(reverseString(string)))
Output:
'ym eman si nevehcs'
Note: if you're allowed to use list.append method, I'd suggest using a collections.deque as it's more performant than appending to a list. But of course, in the end you'll need to join the list together, and you mentioned that you're not allowed to use str.join, so that certainly poses an issue.

Write list to 2 different text files

Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.
Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers
This far everything works accept no text files written and no data written to text files at the end
Here is the Script so far
inputList = []
outputList = []
def FileOpen(myList):
#try:
count=0
INFILE=open("data.txt", "r")
for line in INFILE:
myList.append(line.rstrip())
count+=1
INFILE.close()
return count
#except:
# print("File could not be found")
# exit()
FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")
def AnalyseStudents(rawStudents,totalStudents):
for entry in rawStudents:
amountOfDigits = len(entry)
testOfDigits = entry.isdigit()
def inValid1(val1,val2):
answ = val1 != 8 and val2 != True
return answ
inValidResult1=(inValid1(amountOfDigits,testOfDigits))
def Valid1(val1,val2):
answ = val1 == 8 and val2 == True
return answ
validResult1=(Valid1(amountOfDigits,testOfDigits))
if inValidResult1:
print(entry, " is an INVALID student number")
elif validResult1:
a=entry[0]
b=entry[1]
c=entry[2]
d=entry[3]
e=entry[4]
f=entry[5]
g=entry[6]
h=entry[7]
sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
result = sum%11
def inValid2 (val):
answ = val != 0
return answ
inValidResult2=(inValid2(result))
def Valid2 (val):
answ = val == 0
return answ
validResult2=(Valid2(result))
if validResult2:
print(entry, " is an VALID student number")
elif inValidResult2:
print(entry, " is an INVALID student number")
totalStudents
AnalyseStudents(inputList,outputList)
def Write(outList):
if outList == (" is an VALID student number"):
OUTFILE1=open("ValidNumbers.txt","w")
for validResult in outList:
OUTFILE1.write(validResult+"\n")
OUTFILE1.close()
elif outList == (" is an INVALID student number"):
OUTFILE2=open("InvalidNumbers.txt","w")
for inValidResults in outList:
OUTFILE2.write(inValidResults+"\n")
OUTFILE2.close()
Write(outputList)
print("See output files for more details")
Your equality statements are wrong
if outList == (" is an VALID student number"):
...
elif outList == (" is an INVALID student number"):
The outList is a list but you are comparing it to strings. Put a debug breakpoint at those if statements and decide what you want.
I'm still working my way through this, but for the first function, you can use list comprehension and a couple of other Python functions. Commentary is included.
inputList = []
outputList = []
# Change parameter to the name of the file you want to open.
# Here, we can just make the parameter optional and pass your
# text file name by default.
def FileOpen(filename="data.txt"):
# Using with keeps the open file in context until it's finished
# it will then close automatically.
with open(filename, "r") as INFILE:
# Reach all the data at once and then try to decode it.
data = INFILE.read()
try:
data = data.decode("utf-8")
# If data can't be decoded, then it doesn't have that attribute.
# Catch that exception
except AttributeError:
pass
# Python 3 has a string method called .splitlines() that makes
# splitting lines a little simpler.
myList = [line for line in data.splitlines()]
# We'll return two values: The length (or count) of the list
# and the actual list.
return len(myList), myList
# We set up two variables for intake of our count and list results.
count, myList = FileOpen()
print("{} number of lines read from file".format(count))
EDIT: I don't know what the last part of your code is aiming to do. Maybe compare student count to valid entries? Here's the middle part. I moved the function outside and made it evaluate either valid or invalid in one fell swoop.
def is_valid(entry_value):
"""Validate current entry."""
if len(entry_value) != 8 and entry_value.isnumeric():
return False
return True
def AnalyseStudents(rawStudents, totalStudents):
for entry in rawStudents:
# Our new function will return True if the entry is valid
# So we can rework our function to run through the True condition
# first.
if is_valid(entry):
entry_sum = entry[0] * 8
entry_sum += entry[1] * 7
entry_sum += entry[2] * 6
entry_sum += entry[3] * 5
entry_sum += entry[4] * 4
entry_sum += entry[5] * 3
entry_sum += entry[6] * 2
entry_sum += entry[7] * 1
if entry_sum % 11 == 0:
print(entry, " is an VALID student number")
else:
print(entry, " is an INVALID student number")
else:
print(entry, " is an INVALID student number")
AnalyseStudents(inputList, outputList)

Can't print first and last character of code

Hey guys so I have my program working to a certain extent. My program is suppose to check if there is an "A" in the user input and if done so it will swap that "A" with the next letter.
Here are the examples:
"tan" = "TNA"
"abracadabra" = "BARCADABARA"
"whoa" = "WHOA"
"aardvark" = "ARADVRAK"
"eggs" = "EGGS"
"a" = "A"
In my case this is what works and doesn't work:
Works:
tan to TNA
Doesn't work:
abracadabra = BARCADABAR
whoa = WHO
aardvark = ARADVRA
eggs = EGG
a =
a just equals nothing.
What I'm getting at is that the last character isn't printing and I'm not sure how to do so.
def scrambleWord(userInput):
count = 0
Word_ = ""
firstLetter_ = ""
secondLetter_ = ""
while count < len(userInput):
if count+1 >=len(userInput):
break #copy last character
firstLetter_ = userInput[count] #assigning first letter
secondLetter_ = userInput[count+1] #assigning next letter
if firstLetter_ == 'A' and secondLetter_ != 'A':
Word_ += (secondLetter_ + firstLetter_) #Swap then add both letters
count+=1
else:
Word_+=firstLetter_
count+=1
return Word_
def main():
userInput = input("Enter a word: ")
finish = scrambleWord(userInput.upper())
print(finish)
main()
Probably because you are just breaking without writing the userinput[count] into the word.
if count+1 >=len(userInput):
Word_ += userInput[count]
break #copy last character
This should help

Categories