100 Days of Python - Lesson 37 - Question - python

I started taking the Dr Angela Yu Python class on Udemy few days ago and I've got a question regarding her "Love Calculator" code :
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = name1 + name2
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e
score = int(str(first_digit) + str(second_digit))
print(score)
The consol prints out the result below :
Welcome to the Love Calculator!
What is your name?
True Love
What is their name?
True Love
1010
I'd like to understand why the result of print(score) is 1010 and not 88 as there are only 4 characters in each words.
Thank you very much for your help :)

It is because of the letter e which is counted twice for each of the "True Love" inputs because there is an e in true and in love.
So instead of each character being counted once, you have 3 of them counted once and 1 counted twice, which gives 5 count for each word. Since the phrase is repeated, it then becomes 10 counts per word, and the string "10" added to "10" is "1010" and converting that to an integer we get 1010
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n") # True Love
name2 = input("What is their name? \n") # True Love
combined_names = name1 + name2 # True LoveTrue Love
lower_names = combined_names.lower() #true lovetrue love
t = lower_names.count("t") # 2
r = lower_names.count("r") # 2
u = lower_names.count("u") # 2
e = lower_names.count("e") # 4
first_digit = t + r + u + e # 10
l = lower_names.count("l") # 2
o = lower_names.count("o") # 2
v = lower_names.count("v") # 2
e = lower_names.count("e") # 4
second_digit = l + o + v + e # 10
score = int(str(first_digit) + str(second_digit)) # "10" + "10"
print(score) # 1010

I took your code and added in some additional print statements to illustrate why the value comes out as "1010".
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
combined_names = name1 + name2
print("Combined Names:", combined_names)
lower_names = combined_names.lower()
t = lower_names.count("t")
r = lower_names.count("r")
u = lower_names.count("u")
e = lower_names.count("e")
first_digit = t + r + u + e
print("First Digit:", first_digit)
l = lower_names.count("l")
o = lower_names.count("o")
v = lower_names.count("v")
e = lower_names.count("e")
second_digit = l + o + v + e
print("Second Digit:", second_digit)
score = int(str(first_digit) + str(second_digit))
print(score)
When I run that program and enter in "True Love" for both names, this is the resulting output on the terminal.
#Una:~/Python_Programs/Love$ python3 Love.py
Welcome to the Love Calculator!
What is your name?
True Love
What is their name?
True Love
Combined Names: True LoveTrue Love
First Digit: 10
Second Digit: 10
1010
First off, the entered names are concatenated into a string, "True LoveTrue Love". That string is sampled and the counts are built for the first digit and the second digit. For the first digit, two "t's", two "r's", two "u's" and four "e's" are found in that concatenated string. Therefore the first digit field will contain a value of "10" (2 + 2 + 2 + 4). Likewise, for the second digit calculation, two "l's", two "o's", two "v's", and four "e's" are found in the concatenated string. So again, the sum of those counts is "10". Finally, the two digits are converted to strings and then concatenated. This results in the string value "1010".
So if this calculator program is supposed to derive a different answer, you need to circle back and reevaluate your code.

Related

How to join list elements into strings?

I have a list here where I only need to input 10 letters or strings. I am having a problem separating the list.
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = ' '.join([str(item) for item in num_string])
print (string)
In my code, for example, I inputted a b c d e f g h i j since it is only 10 inputs. Instead of having an output like a b c d e f g h i j because I used the join method, I want to have a NewLine for every list. So I want it to be like
a
b
c
d
e
f
g
h
i
j
You are almost there just instead of joining a whitespace, join a newline, also you don't need to convert each element to string because each element is a string already because input always returns a string (in Python3) (so this is redundant: str(input()), it is the exact same as: input()):
string = '\n'.join(num_string)
Complete example (removed the redundant str):
print("Please input letter: \n")
num_string = []
num = 10
# the 0 isn't necessary either but
# I guess for clarification it can stay
for i in range(0, num):
element = input(str(i + 1) + ". ")
num_string.append(element)
string = '\n'.join(num_string)
print(string)
Alternatively you can use this (instead of the last two lines in the above code example):
print(*num_string, sep='\n')
And if you really want to shorten the code (it can be as short as 3 lines):
print("Please input letter: \n")
num = 10
print('\n'.join(input(f'{i + 1}. ') for i in range(num)))
print ("Please input letter: \n")
num_string = []
num = 10
for i in range (0,num):
element = str(input(str(i + 1) + ". "))
num_string.append(element)
string = '\n' .join([str(item) for item in num_string])
print (string)
Use '\n' , it is like a breakline in your output

putting str and int together 4 times not working [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
I get this error:
TypeError: cannot concatenate 'str' and 'int' objects
How can I add strings to integers?
There are two ways to fix the problem which is caused by the last print statement.
You can assign the result of the str(c) call to c as correctly shown by #jamylak and then concatenate all of the strings, or you can replace the last print simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
str(c) returns a new string representation of c, and does not mutate c itself.
c = str(c)
is probably what you are looking for
If you want to concatenate int or floats to a string you must use this:
i = 123
a = "foobar"
s = a + str(i)
c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.
Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.
You can convert int into str using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")
The easiest and least confusing solution:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c
I found this on http://freecodeszone.blogspot.com/
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():
rolling = True; import random
while rolling:
roll = input("ENTER = roll; Q = quit ")
if roll.lower() != 'q':
num = (random.randint(1,6))
print("----------------------"); print("you rolled " + str(num))
else:
rolling = False
main()
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
This is what i have done to get rid of this error separating variable with "," helped me.
# Applying BODMAS
arg3 = int((2 + 3) * 45 / - 2)
arg4 = "Value "
print arg4, "is", arg3
Here is the output
Value is -113
(program exited with code: 0)

How to display A B C D E if a input 5 numbers 1 2 3 4 5

import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)
What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.
random.randrange(1,26)
This is wrong. Random's second parameter is non-inclusive, meaning you'll get numbers from 1 to 25.
You should use:
random.randrange(1, len(ltr))
Then your result letter is just accessing the correct index in your ltr string - simply doing ltr(var1)
As for user input, you need to invert it to integer values like this:
a = int(input(''))
strip() your ltr and find element at (entered_position-1) , repeat for five times ,and join the list separated by a space
ltr = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(' '.join([ltr.strip()[int(input('number 1-26: '))-1] for _ in range(5)]))
print(' '.join([ltr.strip()[random.randrange(1,27)-1] for _ in range(5)]))
What you want to do is to print the letter in the alphabet which is at the position the user entered. In other words, the user enters the index of that letter inside the alphabet. Since you can access a character inside a string using its index in python using letter = string[index] you can do this:
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
print(ltr[a], ltr[b], ltr[c], ltr[d], ltr[e])
Note that due to the space at the start of ltr, A will be output when entering 1.
Edit: Update according to question in comments.
You can sort the inputs if you put them in a list and sort() them. Then you can get the characters at the positions from the input list:
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
inputs = []
for _ in range(5):
inputs.append(int(input("Enter a number:")))
inputs.sort()
print(', '.join(map(str, inputs)))
print(', '.join(ltr[i] for i in inputs))

How to repeat string message without use asterisk, loop, array, import

I get a quiz about programming python.
Input: 3 lines of any string. (only 3 lines)
Output: 3 * 5 = 15 lines of string which repeat 3 lines of input 5 rounds
** But this quiz has restricted word: import for while * . sep if else elif list set tuple dict [] {} lambda map filter
I already try it by use asterisk character to repeat string but this is restricted word. It cannot submit.
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C + "\n"
print(STRING_RESULT * 5)
Example
Input:
man
in
middle
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle
Thanks for your helping.
Given your restrictions, recursion sounds like a good approach. Give this a shot!
def repeater(a,n):
n <= 0 and exit(0)
n == 1 and print(a)
print(a)
return(repeater(a,n-1))
STRING_A = input()
STRING_B = input()
STRING_C = input()
STRING_RESULT = STRING_A + "\n" + STRING_B + "\n" + STRING_C
repeater(STRING_RESULT, 5)
Output:
man
in
middle
man
in
middle
man
in
middle
man
in
middle
man
in
middle

Create averages from a list from .txt file?

classs = input("Class [1, 2 or 3] - ")
if clas
data = f.readlines()
for le:
print(line)
found = True
if found == False:
print("False")
Here is a typical printed output:
John = 10
John = 6
John = 4
I need to be able to create an average just by using the 10, 4, 6 as I need to know a way to isolate the rest and allow the numbers to proceed inorder to create the average score.
If the format of each line is the same, you can use string.split and cast to int:
classs = input("Class [1, 2 or 3] - ")
l = []
if classs =='1':
name = input("What is your name? - ")
datafile = '1.txt'
found = False
with open(datafile, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print(line)
l.append(int(line.split()[2]))
found = True
if found == False:
print("False")
Then go through the list of numbers and get the average, something like:
total = 0
num = 0
for x in l:
total = total + x
num = num + 1
print(total/num)
one way would be to extract the last 3 numbers for each player from your list (i'm assuming you only need 3, if not this code can be altered for more)
Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
count = 0
record = line
studentList = record.split(': ')
score = studentList[1].strip('\n')
studentList = [studentList[0], score]
if len(dataList) == 0:
dataList.append(studentList)
else:
while count < len(dataList):
if studentList[0] == dataList[count][0]:
if len(dataList[count]) == 4:
dataList[count][3] = dataList[count][2]
dataList[count][2] = dataList[count][1]
dataList[count][1] = score
break
dataList[count].append(score)
break
elif count == len(dataList) - 1:
dataList.append(studentList)
break
count = count + 1
this will give you a 2D array. each smaller array within will conatin the persons name at index 0 and there three numbers at indecies 1,2 and 3. now that you have these, you can simply work out the average.
AverageScore = []
# this is the array where the student' record (name and highest score) is saved
# in a list
count = 0
while count < len(dataList):
entry = []
# this is whre each student name and score will be temporarily held
entry.append(dataList[count][0])
# this makes it so the array 'entry' contains the name of every student
Sum = 0
frequency = len(dataList[count])
incount = 1
while incount < frequency:
Sum = Sum + int(dataList[count][incount])
incount = incount + 1
average = Sum / (frequency-1)
entry.append(average)
AverageScore.append(entry)
# this appends the name and average score of the student to the larger array
# 'AverageScore'
count= count + 1
# the count is increased so the process is repeated for the next student
AverageSorted = sorted(AverageScore,key=lambda l:l[1], reverse=True)
# http://stackoverflow.com/questions/18563680/sorting-2d-list-python
# this is code i obtained through someone else's post which arranges the array in descending
# order of scores
count2 = 0
while count2 < len(AverageSorted):
print(AverageSorted[count2][0], ':', AverageSorted[count2][1])
count2 = count2 + 1
# this formats the array so it prints the elements in a list of each student's
# name and score
Long winded and inefficient, but its the best i can do with my small knowledge of python :)
If this is the content of 1.txt:
John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13
Replace your "with" statement with this:
name = "John"
_class = 1
with open("%s.txt" % _class, "r") as out:
lines = out.readlines()
scores = []
for line in lines:
if name in line:
# "strip" without arguments strips out all beginning
# and trailing white-space (i.e. " ", "\n", "\r").
line = line.strip()
score = int(line.split(" = ")[1])
scores.append(score)
# If there isn't any scores in this list, then there was no user
# data.
if scores:
# Use python built-in sum to sum the list of scores and
# divide the result by the number of scores gives you the average.
average = sum(scores) / len(scores)
print "%s's average score is %.1f out of %d game(s)." % (
name, average, len(scores))
else:
print "User %s not found." % name

Categories