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
Related
I tried to make just add print(a+b) and I only got what it equals I don't know what to do I can't find it or look for it online.
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world') will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a+b), it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a + '+' + b + '=' + (a+b))
Notice the difference between + without quotes and '+' with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5 and b = 3. First, we evaluate all the expressions:
print(5 + '+' + 3 + '=' + 8)
Now, we have to add a combination of numbers with strings. The + operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' + '+' + '3' + '=' + '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5+3=8')
which prints the literal 5+3=8
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} + {b}) = {a + b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 + 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!
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.
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
I'm looking for a code that runs, i.e:
int(input) = 2565
Printed Output should be like:
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
I wrote the code that gives final answer "9". But I couldn't managed to write it with every digit separated "+" sign. Assuming that I need to use while loop but how can I write the code so it will be like the output above?
You can use something like this:
def sum_of_digits(s):
if s < 10:
return s
return sum_of_digits(sum(int(c) for c in str(s)))
> sum_of_digits(2565)
9
It recursively checks if the numerical value is less than 10. If it does, it returns this value. If not, it adds the digits, then recursively calls itself on the result.
Edit
To print out the steps as it goes along, you could do something like this:
def sum_of_digits(s):
if s < 10:
print(s)
return s
print(' + '.join(c for c in str(s)) + ' = ')
return sum_of_digits(sum(int(c) for c in str(s)))
First, initiate an empty string output_str.
With a while loop which contniues when our integer is > 9:
[s for s in str(x)] would create a list of the digits (as strings) of our integer. It's called a list comprehension, is very useful, and my advice is to read a bit about it.
With " + ".join() we create a string with " + " between the
digits. Add this string at the end of output_str.
Add " = " to the end of output_str.
Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum()). Store the sum into x.
Add the new x + " = " to output_string.
At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars (=) from it.
x = 2565
output_str = ""
while x > 9:
lst_of_digits = [s for s in str(x)]
output_str += " + ".join(lst_of_digits)
output_str += " = "
x = sum([int(s) for s in lst_of_digits])
output_str += f"{x} = "
output_str = output_str[:-3]
outputs:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'
You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\n" but it can be change to your desire.
And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:
>>> " + ".join("123")
'1 + 2 + 3'
>>>
Mixing it all together:
def sum_digit(n):
s = sum(map(int,str(n)))
print(" + ".join(str(n)),"=",s, end="")
if s<10:
print()
return s
else:
print(" = ",end="")
return sum_digit(s)
Here we first get the sum of the digit on s, and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step
>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>>
This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)
I am a noob but this should do what you want.
Cheers,
Guglielmo
import math
import sys
def sumdigits(number):
digits = []
for i in range( int(math.log10(number)) + 1):
digits.append(int(number%10))
number = number/10
digits.reverse()
string = ''
thesum = 0
for i,x in enumerate(digits):
string += str(x)
thesum += x
if i != len(digits)-1: string += ' + '
else: string += ' = '
if thesum > 10:
return string,thesum,int(math.log10(number))+1
else:
return string,thesum,0
def main():
number = float(sys.argv[1])
finalstring = ''
string,thesum,order = sumdigits(number)
finalstring += string
finalstring += str(thesum)
while order > 0:
finalstring += ' = '
string,thesum,order = sumdigits(thesum)
finalstring += string
finalstring += str(thesum)
print 'myinput = ',int(number)
print 'Output = ',finalstring
if __name__ == "__main__":
main()
Heres my code
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * n
def remove(x):
return x.replace(" ","-")
print remove(x)
Basically its like this
s = abc
n = 2
I want to print abc-abc
but I end up getting abc-abc-
don't know how to do this.
n = input()
x = (s + " ") * n
Assuming you enter 'abc' and '2', the string becomes 'abc abc ' (Note the space at the end). When you replace with -, it replaces the trailing space with a -. A very quick solution would be to use
x.replace(" ", "-", n-1)
The third parameter is the count, so it will replace all but the trailing space.
This code will do the job
'-'.join([s]*n)
for your data it will be abc-abc
How about this solution:
#!/usr/bin/env python
s = raw_input()
n = input()
x = (s + " ") * (n-1)
x += s
def remove(x):
return x.replace(" ","-")
print remove(x)
So the last 's' would not add any space to x and therefor there is no space at the end to turn into a hyphen.