how to split the output of the Python code? - python

I have following code, which should print an output of k numbers around n number, and instead the n number the code should replace by *:
def numbers_around(n, k):
for cislo in range(n-k, n+k+1):
if cislo == n:
print("*", end=" ")
else:
print(cislo, end=" ")
numbers_around(8, 3)
numbers_around(10, 2)
The output should be:
5 6 7 * 9 10 11
8 9 * 11 12
But my output is all in one line:
5 6 7 * 9 10 11 8 9 * 11 12

You are using the parameter end = " " in the print function, which replaces the default end used by python which is starting new line; if you want to start new line after each printing, just add print() at the end.
the full function should be
def numbers_around(n, k):
for cislo in range(n-k, n+k+1):
if cislo == n:
print("*", end=" ")
else:
print(cislo, end=" ")
print()

Using end=" " tells the print function to output a space at the end, instead of the line break that it would normally output.
Therefore the output of the second function call starts on the same line as the output of the first function call ends.
You need to output an additional line break at the end of the numbers_around function.
To do that, just add an empty print() after the for loop:
def numbers_around(n, k):
for ...:
# ...
print()

The problem is that you're telling print() to put a space at the end instead of the newline character '\n' it normally uses. You could fix this by just adding another call to print() at the end, but actually, if you redesign the function a little bit, you can make it a lot simpler. By using the splat operator, you can print everything at once.
Option 1: Use a generator expression or list comprehension instead of a for-loop.
def numbers_around(n, k):
r = range(n-k, n+k+1)
out = ('*' if i==n else i for i in r)
print(*out)
Option 2: Instead of replacing n, get the two ranges around n and put a '*' in the middle.
def numbers_around(n, k):
r1 = range(n-k, n)
r2 = range(n+1, n+k+1)
print(*r1, '*', *r2)

Related

Alternating lines with Nested Loops

This is the exercise I need to complete:
Using nested loops, write some code that outputs the following:
##########
**********
##########
**********
##########
Following is all the code I have so far. I assume I need to combine these two loop functions to one but I'm struggling with it. I'm early on in my first class and any help with this would be appreciated!
for a in range (0, 5, 2):
for b in range(10):
print("#", end = "")
print("")
for a in range (1, 5, 2):
for b in range(10):
print("*", end = "")
print("")
Since no input is specified, only a fixed output:
for _ in '_':
for _ in '_':
print('''##########
**********
##########
**********
##########''')
And yes, if that was my homework exercise, I'd absolutely submit this.
There are several ways to do it. First you should check how many lines you need to output. 5, so you need a loop doing something 5 times.
for i in range(5):
Now you need 2 loops to paste print the 2 line patterns (you already have them in your code)
for b in range(10):
print("#", end = "")
print("")
and
for b in range(10):
print("*", end = "")
print("")
If you need to alternate between 2 values it's mostly the best to use the Modulo Operator.
So you can just switch between the 2 loops by % 2.
for i in range(5):
if i % 2 == 0:
for b in range(10):
print("#", end = "")
print("")
else:
for b in range(10):
print("*", end = "")
print("")
I would suggest to simply base the symbol on the row index, even or odd
nb_lines = 5
line_size = 10
for i in range(nb_lines):
for _ in range(line_size):
if i % 2 == 0:
print("#", end="")
else:
print("*", end="")
print()
But no need of nested loops
nb_lines = 5
line_size = 10
for i in range(nb_lines):
if i % 2 == 0:
print("#" * line_size)
else:
print("*" * line_size)
def printStripes(row_length, number_of_rows):
for _ in '_':
print( "".join(
[ "\n" if n%(row_length+1)==row_length else
"#" if (n//(row_length+1))%2==0 else
"*"
for n in range(number_of_rows*(row_length+1))
]
),end="")
printStripes(row_length=5,number_of_rows=8)
But don't tell your teacher that you got if from stackoverflow. (Thanks Kelly, for how to deal with the nested loop constraint.)
You can use this to get the result that you want
for i in range(0,5):
print("*"*10)
print("#"*10)

How to make function loop on its own separate line?

I have written for a coding problem assigned to me essentially there is a scratch and win ticket and I have to figure out what prizes I could win. I will be given 10 inputs and each output after running through should be on its own line. However Every time I run the code with 10 inputs all of the inputs just appear on one line.
How do I make sure that each output appears on its own line?
Although to be noted my code does output the correct answer its just the formatting that is troubling I want each answer to be on its own line instead of just being on one line.
from collections import Counter
def Winner(L):
zz = Counter(L)
if zz["63"] == 9:
print("No Prizes Possible")
elif zz["63"] == 0:
for T in zz:
if zz[T] >= 3:
print("$" + T, end=" ")
else:
for V in zz:
KK = zz[V] + zz["63"]
if KK >= 3:
if V != "63":
print("$" + V, end=" ")
for d in range(10):
z = [input() for i in range(9)]
yy = []
for g in z:
if g == "?":
yy.append(ord(g))
else:
yy.append(g.replace("$", ""))
yy = [int(i) for i in yy]
yy.sort()
yy = [str(i) for i in yy]
Winner(yy)
Here is a sample input of what I mean:
$10
$100
?
$10
$1
$50
$50
$1000
$1
essentially having 10 inputs like these.
If you add \n (the newline character) at the end of your string, you will add a newline after each time your program prints. For example, you could have this loop which would print "hello world" 10 times, each on its own separate line.
for i in range (10):
print('hello world', '\n')
Or more conveniently, you can get rid of the end = " ", and Python will automatically add a new line.
You are using end=" " in your print function.
Just leave it as print("$" + T) and print("$" + V) so it appends newline by default.

How to convert user input into a list and remove all occurrences of a particular digit or character?

I assume I am tackling this problem from the wrong angles or lack the proper understanding of built-in functions and syntax to resolve my issues despite my trying. I also discovered using:
input("Enter input: ")
is dangerous and should use raw_input instead, but can't seem to get this functioning correctly.
I want to write a script that can take user input, convert it into a list, multiply each individual element by 3, scan the solution to that problem for any "3" and remove all occurences of "3" while maintaining all other figures in their respective elements in the list, to then print or return the final result.
ex. entering 1 2 3 would output 6 9 as 1 * 3 = 3 which would be omitted.
ex. entering 2 6 11 would output 6 18 as 11 * 3 = 33 and both 3's would be omitted.
If for instance, user was to input x where x * 3 = 2381193 - I want for this to be converted to 28119.
I believe the simplest way to do this would be to convert to a string?
I started with something like this:
userInput = input("list element seperated by space: ")
nums = userInput.split()
x = int(nums[0]) * 3
y = int(nums[1]) * 3
z = int(nums[2]) * 3
output = x, y, z
negate = list(output)
if "3" in str(x):
del negate[0]
if "3" in str(y):
del negate[1]
if "3" in str(z):
del negate[2]
print(negate)
and now I've re-thought it to:
userInput = raw_input("list element seperated by space: ")
nums = userInput.split()
for x in list(nums):
numsList = int(x) * 3
output = list(numsList)
y = "3"
while y in str(output): output.remove(y)
print(output)
But overall, I am unable to achieve the desired result.
Could you please provide feedback?
It would be greatly appreciated :)
In your case, your first snippet was close to making a solution to your problem. The only thing you would want to do, is to change the conditional statement into an interative statement, like so:
nums = str(input("list element seperated by space: ")).split(" ")
num_list = []
if len(nums) != 1:
num_list = [*(int(num.replace("3", "")) * 3 for num in nums)]
else:
num_list = [nums[0]]
for x in num_list:
if x != 3:
print(str(x).replace("3", "") + " ", end="")
else:
print("0 ", end="")
If you input 11 you would receive 0 and if for instance you had 133 - you would want to remove the 3 but keep the 1.
This part of your question is not clear/elaborated enough hence i did not include this logic in my snippet above. So anyone is free to edit my answer and include it once the point above is clear.
[EDIT]: So i made changes to my snippet above. I have not tested this so there is a chance for it to be wrong. If that is the case, then inform me of any specific patterns/tests that would end as unwanted.

Square Every Digit of a Number in Python? [duplicate]

This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
How to print without a newline or space
(26 answers)
Closed 5 days ago.
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.
def sq(num):
words = num.split() # split the text
for word in words: # for each word in the line:
print(word**2) # print the word
num = 9119
sq(num)
We can use list to split every character of a string, also we can use "end" in "print" to indicate the deliminter in the print out.
def sq(num):
words = list(str(num)) # split the text
for word in words: # for each word in the line:
print(int(word)**2, end="") # print the word
num = 9119
sq(num)
Alternatively
return ''.join(str(int(i)**2) for i in str(num))
def sq(num):
z = ''.join(str(int(i)**2) for i in str(num))
return int(z)
number=str(input("Enter the number :"))
def pc(number):
digits = list(number)
for j in digits:
print(int(j)**2,end="")
pc(number)
We can also support input of negative numbers and zeros. Uses arithmetic operators (% and //) for fun.
def sq(num):
num = abs(num) #Handle negative numbers
output = str((num % 10)**2) #Process rightmost digit
while(num > 0):
num //= 10 #Remove rightmost digit
output = str((num % 10)**2) + output #Add squared digit to output
print(output)
You can try this variant:
def square_digits(num):
return int(''.join(str(int(i)**2) for i in str(num)))
def square_digits(num):
num = str(num)
result = ''
for i in num:
result += str(int(i)**2)
return int(result)
var = square_digits(123)
print(var)

Using print() inside recursive functions in Python3

I am following the book Introduction to Computing Using Python, by Ljubomir Perkovic, and I am having trouble with one of the examples in recursion section of the book. The code is as follows:
def pattern(n):
'prints the nth pattern'
if n == 0: # base case
print(0, end=' ')
else: #recursive step: n > 0
pattern(n-1) # print n-1st pattern
print(n, end=' ') # print n
pattern(n-1) # print n-1st pattern
For, say, pattern(1), the output should be 0 1 0, and it should be displayed horizontally. When calling the function pattern(1), nothing prints out, however. But if this is followed by a print statement without arguments, then the results are displayed.
>>>pattern(1)
>>>print()
0 1 0
If I remove the end argument of the print() functions inside the recursive function, I get correct output (albeit it displays it vertically):
>>> pattern(1)
0
1
0
This makes me think that the recursive code itself is correct (plus I confirmed it was with the source provided by the book's website, and with the errata sheet). I am not sure, however, why the print statement isn't printing the output as the functions run, if the end parameter is included. Any help would be greatly appreciated.
The print function doesn't always flush the output. You should flush it explicitly:
import sys
def pattern(n):
'prints the nth pattern'
if n == 0: # base case
print(0, end=' ')
else: #recursive step: n > 0
pattern(n-1) # print n-1st pattern
print(n, end=' ') # print n
pattern(n-1) # print n-1st pattern
sys.stdout.flush()
Note that on python3.3 print has a new keyword argument flush that you can use to forcibly flush the output(and thus avoid using sys.stdout.flush).
On a general note I'd decouple the output from the pattern, doing, for example:
def gen_pattern(n):
if n == 0:
yield 0
else:
for elem in gen_pattern(n-1):
yield elem
yield n
for elem in gen_pattern(n-1):
yield elem
def print_pattern(n):
for elem in gen_pattern(n):
print(elem, end=' ')
sys.stdout.flush()
This makes the code more flexible and reusable, and has the advantage of calling flush only once, or you could also call it once every x elements(actually I believe print already does this. It flushes if trying to write many characters on the screen).
In python3.3 the code could be simplified a little:
def gen_pattern(n):
if n == 0:
yield 0
else:
yield from gen_pattern(n-1)
yield n
yield from gen_pattern(n-1)
The reason is that when end is used with some value other than a "\n" then the print function accumulates the whole value and prints the output only when a newline is to be printed or the loop is over.
See the difference in these two programs:
In [17]: for x in range(5):
print(x,end=" ")
if x==3:
print(end="\n")
sleep(2)
....:
0 1 2 3 #first this is printed
4 #and then after a while this line is printed
In [18]: for x in range(5):
print(x,end=" ")
if x==3:
print(end="\t")
sleep(2)
....:
0 1 2 3 4 #whole line is printed at once

Categories