How to print a collection of characters next to each other [duplicate] - python

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 4 years ago.
I have this code where given an integer n, I want to print out all integers in the interval [1→n] that divide n, separated with spaces. I wrote this code:
n = int(input('Enter number:'))
for i in range(1, n+1):
if (n%i==0):
print (i)
I get this as the answer:
Enter number:8
1
2
4
8
But I want my answer next to each other, separated using spaces (so: 1 2 4 8). How do I do this?

Instead of:
print(i)
You should put:
print(i, end=" ")
This will change the end of line string from "\n" to " ". This will give you the desired output.
Another method would be to build a list of results and print it out at the end:
n = int(input('Enter number:'))
final_results = list()
for i in range(1, n+1):
if (n%i==0):
final_results.append(str(i))
print(" ".join(final_results))

I would suggest accumulating all intermediate results, and only when the computation is done, print it.
n = int(input('Enter number:'))
dividers = []
for i in range(1, n+1):
if (n%i==0):
dividers.append(i)
print(dividers)
If you want to print them with nice comma separation, you can do something like this:
print(', '.join(str(divider) for divider in dividers))
Benefits
First, this reduces the number of calls to wherever you are printing to (by default, this is stdout)
Second, the code becomes more readable and easier to adjust and expand later-on (for example, if you later decide that you want to pass those dividers onto another function)
Edit: adjusted the join operation per ritlew's comment

print(i),
(with the comma) Should do the job.

Related

Need Help Dealing with inputs [duplicate]

This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x
Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.
you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))
I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))

How can I write a string inside of an input?

I'm having a problem of printing a string inside an input. I made a for loop for automatic numbering based on how many elements that the user wants to input.
list = []
n = int(input("How many elements you want to input: "))
for i in range(0, n):
element = int(input(i+1))
if n == element:
print("hello")
break
list.append(element)
For example, I inputted 3 in the number of elements. I want to make my program output be like this:
input
input
input
(input is the user will type once the number is shown)
But my program looks like:
1input
2input
3input
I just want to work up with the design, but I don't know how to do it.
What you need is called string formatting, and you might use .format by replacing
element = int(input(i+1))
using
element = int(input("{}. ".format(i+1)))
or using so-called f-strings (this requires Python 3.6 or newer):
element = int(input(f"{i+1}. "))
If you want to know more, I suggest reading realpython's guide.
Try:
input(str(i+1)+'. ')
This should append a point and a space to your Text. It converts the number of the input to a String, at which you can append another String, e.g. '. '.
You have to edit the input in the loop to something like this:
element = int(input(str(i+1) + ". "))
You are close. Convert i+1 to a string and concatenate a . to it and accept input.
Note: Do not use list as a variable name. It is a Python reserved word.
lst = []
n = int(input("How many elements you want to input: \n"))
for i in range(n):
element = int((input(str(i+1) + '. ')))
if n == element:
print("hello")
break
lst.append(element)
How many elements you want to input:
5
1. 1
2. 6
3. 7
4. 4
5. 6
n = int(input("How many elements you want to input: "))
for i in range(0, n):
print(str(i+1) + ". " + str(n))
This should do.
I used the same code shape as yours, and that way it is easier for you to understand.

Python: Adding odd numbers together from an input

Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)

Creating a Number Pyramid

I first off would like to say this may be classified as a duplicate post, based on my current research:
How to do print formatting in Python with chunks of strings?
and
Number Pyramid Nested for Loop
and
pyramid of numbers in python
[Edit: The reason I cannot use the conclusions to these previous questions very similar to mine is that I cannot use anything except what we have covered in my class so far. I am not allowed to use solutions such as: len, map, join, etc. I am limited to basic formats and string conversion.]
I'm in the process of working on an assignment for my Python class (using 3.0+) and I've reached a point where I'm stuck. This program is meant to allow the user to input a number from 1 to 15 as a line count and output a number pyramid based on their choice, such as the following example where the user would input 5:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
So far I've gotten to the point where I can successfully print inputs 1 through 9, but have run into 2 issues.
Inputs from 10 to 15 the numbers become misaligned (which users in the above posts seemed to have as well).
I can't seem to correctly format the printed numbers to have spaces in between them like my example above
My current code for the program is:
print("This program creates a number pyramid with 1 to 15 lines")
lines = eval(input("Enter an integer from 1 to 15: "))
if lines < 16:
for i in range(1, lines + 1):
#Print leading space
for j in range(lines - i, 0, -1):
print(" ", end = '')
#Print left decreasing numbers
for j in range(i, 0, -1):
print(j, end = '')
#Print right increasing numbers
for j in range(2, i + 1):
print(j, end = '')
print("")
else:
print("The number you have entered is greater than 15.")
And my current output is:
Enter an integer from 1 to 15: 15
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
109876543212345678910
1110987654321234567891011
12111098765432123456789101112
131211109876543212345678910111213
1413121110987654321234567891011121314
15141312111098765432123456789101112131415
I am asking you guys out of a desire to learn, not for anyone to code for me. I want to understand what I'm doing wrong so I can fix it. Thank you all in advance!
You need to print one space more for the numbers from 10 to 15 because there is an extra character you have to take into consideration. If you change your max number to 100, you will need another space(total of 3), and so on. This means that instead if print(" ") you have to use print(" " * len(str(j))), where * duplicates the space len(str(j)) times and len(str(j)) counts the number of digits from j. Also, if you want the pyramid properly aligned, you have to print another space, the one between numbers.
To add a space between numbers, you have to print the space
print(j, end=' ')
input_number=int (raw_input ())
for i in range (1, input_number+1):
string=''
k=i
while (k>0):
string=string+str (k)
k=k-1
m=2
while (m<=i):
string=string+str (m)
m+=1
space=(2* input_number-1)
string=string.center (space)
print (string)
This code works well.

Python - Write a for loop to display a given number in reverse [duplicate]

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 8 years ago.
How would I have the user input a number and then have the computer spit their number out in reverse?
num = int(input("insert a number of your choice "))
for i in
That is all I have so far...
I am using 3.3.4
Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Why make it a number? 'In reverse' implies a string. So don't cast it to int but use it as string instead and just loop over it backwards.
You've got here a variety of different answers, many of which look similar.
for i in str(num)[::-1]:
print i
This concise variation does a few things worth saying in english, namely:
Cast num to a string
reverse it (with [::-1], an example of slicing, a pythonic idiom that I recommend you befriend)
finally, loop over the resultant string (since strings are iterable, you can loop over them)
and print each character.
Almost all the answers use [::-1] to reverse the list -- as you read more code, you will see it more places. I recommend reading more about it on S.O. here.
I hate to do your problem for you since you didn't really try to actually solve it or say what you're specifically having a problem with, but:
num = str(input("..."))
output = [num[-i] for i in range(len(num))]
print(output)
output = input("Insert number of your choice: ")[::-1]
print("Your output!: %s" % output)
In python 3.x+ input is automatically a string, doing [::-1] reverses the order of the string

Categories

Resources