How to not print new_lines in a while loop? [duplicate] - python

This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
How to print without a newline or space
(26 answers)
Closed 2 years ago.
I have a while loop. The purpose of this while loop is to trivially decide if a given integer N exists at a given index location of M.
I can achieve a better space complexity if I only used one line for each request of an input. Arbitrarily giving one element at a time instead of an entire list.
M = 2
N = 2
index = -1
while True:
print('take input: ', end = "")
a = str(input())
index = index + 1
if int(a) == N:
if index == M:
print('yes')
break
if index > M:
print('no')
break
if index < M:
if int(a) == N:
print('no')
break
Unintended result
================= RESTART: C:\Users\User\Desktop\logspace(m).py ================
take input: 1
take input: 2
no
>>>
I would like the console to only do one line at a time as shown below.
================= RESTART: C:\Users\User\Desktop\logspace(m).py ================
take input: (Do not echo previous inputs only one integer at a time... All on one line!)
no
>>>
Question
Is there any functions, modules, etc that could do this without tinkering with my console settings?

Related

Python composed Lists [duplicate]

This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
I would just like a tip on how to send even numbers to the left and odd numbers to the right, I've been trying for a long time and I can't, the subject is composed lists, I appreciate any help. Simplified code below without loop or conditional structure.
test = [[],[]]
num = int (input("Type it : "))
test.append()
print(test)
test = [[], []]
num = input("Enter a number or quit")
while num != "quit": # execute code as long as num is not quit
num = int(num) # convert num to a number (until here, it's a string !!!)
if num % 2 == 0: # num is even
test[0].append(num)
else: # num is odd
test[1].append(num)
print(test)

How to write in superscript in Python 3? [duplicate]

This question already has answers here:
How do you print superscript in Python?
(13 answers)
Closed 1 year ago.
I am writing a code which is supposed to print a series in the form:
x - (x^2)/2! + (x^3)/3! - (x^4)/4! ... (x^n)/n!
where x and n are input from the user end.
For now my code looks like this
x = int(input('Enter number: '))
n = int(input('Till which term? '))
#for series
for i in range(1,n+1,1):
if i == n:
print('('+str(x)+'^'+str(i)+')'+'/'+str(i)+'!')
elif i == 1:
print(str(x),end = ' - ')
else:
if i%2 != 0:
print('('+str(x)+'^'+str(i)+')'+'/'+str(i)+'!',end = ' - ')
else:
print('('+str(x)+'^'+str(i)+')'+'/'+str(i)+'!',end = ' + ')
but the output is:
================= RESTART: E:/Python/Files/special series 4.py =================
Enter number: 3
Till which term? 6
3 - (3^2)/2! + (3^3)/3! - (3^4)/4! + (3^5)/5! - (3^6)/6!
is there any function to write in superscript to avoid the arrow-head sign?
As the output of Python and pretty much any language is usually in unicode or ASCII, the answer is simply no.

Can't escape a recursive function in Python? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 2 years ago.
I'm having this extremely strange problem and I guess it's something simple but it just makes no sense to me.
CodeWars question states:
Define a function that takes a multi digit number and multiplies each digit until you get a single digit answer, so for example persistence(39) would compute 3*9 = 27, 2*7 = 14, 1*4 = 4, return 4
I wanted to try and solve this recursively, and I have the answer, but the program will never break out of the function. I've stepped through this program multiple times and it gets to the return statement and then jumps back up into the if statement and calls persistence again.
Code below:
def persistence(n):
arg_to_list = list(str(n))
# If the argument is > one digit
if len(arg_to_list) > 1:
total = int(arg_to_list[0])
for digit in arg_to_list[1:]:
# Don't want any muplication by 0
if digit != "0":
total *= int(digit)
# Call the function again on the total
persistence(total)
else:
return n
You are not returning anything unless the number is 1-digit already, so your recursion doesn't pass over the result up. Here is what your code should look like (note the return statement just before else: - it is the only change from the original code):
def persistence(n):
arg_to_list = list(str(n))
# If the argument is > one digit
if len(arg_to_list) > 1:
total = int(arg_to_list[0])
for digit in arg_to_list[1:]:
# Don't want any muplication by 0
if digit != "0":
total *= int(digit)
# Call the function again on the total
return persistence(total)
else:
return n

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

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.

Python IDLE less or more? [duplicate]

This question already has answers here:
Paging output from print statement
(3 answers)
Closed 5 years ago.
Getting a list of __builtins__ in IDLE how do I pause it after a certain number or bottom of the screen?
This gives me one at a time..
>>> for i in dir(__builtins__):
... print i
... raw_input("Press Enter...")
and I could slice it like ...
x=dir(__builtins__)
len(x)
for i in x[:10]:
print i
... and that give me first 10 but is there a way to get it to print 10, or bottom of screen until the user input ? Like a less or more in Unix?
Thanks!
Try something like:
print_every = 5
for i, f in enumerate(dir(__builtins__)):
print f
if i % print_every == 0 and i != 0:
raw_input("Press Enter...")
enumerate pairs each entry in the list with its index in the list
if i % print_every == 0: checks to see if i (the current index) is a multiple of print_every.
The above code should print the list in groups of print_every many entries.

Categories

Resources