Python Looping Random numbers - python

What I've got to do is get to print out as 5 4 3 2 1
then 4 3 2 1 under that then 3 2 1 and so on, right now all I have is the first line so i'll get 5 4 3 2 1 or 6 5 4 3 2 1 but I can't seem to get it right when trying to get it to continue until it reaches 1
from random import choice
i=choice([5,6,7,8,9,10])
while i:
print(i, end=" ")
i -= 1
if(i <1):
break

A compact approach:
import random as rnd
length = rnd.choice([5, 6, 7, 8, 9, 10])
lst = [str(x) for x in range(length, 0, -1)]
while lst:
print(" ".join(lst))
lst.pop(0)
Replace range with xrange if you are using Python 2.7.

You need two loops, one to do the initial countdown (5, 4, 3, 2, 1), the other to loop through each of the lists you need to produce. For example:
from random import choice
i=choice([5,6,7,8,9,10])
for j in [*range(i,0,-1)]:
for k in [*range(j,0,-1)]:
print(k, end=" ")
print('')

You can try this.
from random import choice
x = choice([5,6,7,8,9,10])
while x > 0:
y = x
while y > 0:
print y,
y = y-1
print "\n"
x = x-1

Related

Multiple if statements in list comprehension with one iterator

I was studying list comprehension and came across the possibility of adding several conditions. I do not know what behavior I expected, but I cannot explain what I am getting. Why does 1 turn into 3, 2 remains a 2, and 3 turns into 6?
a = [x if x % 2 == 0 else x * 2 if x % 3 == 0 else x * 3 for x in range(1, 11)]
output:
[3, 2, 6, 4, 15, 6, 21, 8, 18, 10]
Re-writing as a loop and converting the conditional expressions to full if/elif/else statements might help explain it:
a = []
for x in range(1, 11):
if x % 2 == 0:
temp = x
elif x % 3 == 0:
temp = x * 2
else:
temp = x * 3
a.append(temp)
For 1 it goes like this:
1 % 2 = 1, so it goes to else clause,
1 % 3 = 1, so it also goes to else clause
and it gets into x*3 which is 1*3 = 3
When you write x if condition else y, you get x only if condition is true. So since the condition is false, you go to the else clause. You can look at it like this:
x if x % 2 == 0 else (x * 2 if x % 3 == 0 else x * 3) for x in range(1, 11)

I wonder why range slice is not working properly in python

I made code as follows to execute binary search in sorted list for my study.
Code to find which number of values 'x' are in the list 'ss'.
Problem is, it should execute as reducing range of list, but it doesn't work.
def bin_search(ss, x):
return bin_search_range( ss, x, range(len(ss)) )
def bin_search_range(ss, x, r):
print(r)
print("len(r)", len(r))
if len(r) > 0:
mid = ((r.start) + (r.stop)) // 2
print("start", r.start)
print("stop", r.stop)
print("mid", mid)
print("x", x," ss[mid]", ss[mid])
if x == ss[mid]:
print("----[x = ss[mid]----")
return print("answer", mid)
elif x < ss[mid]:
print("----[x < ss[mid]]----")
return bin_search_range(ss, x, r[:mid])
else:
print("----[x > ss[mid]]----")
return bin_search_range(ss, x, r[mid+1:])
else: # len(r) == 0
return None
#Except "return print("answer", mid)", I just wrote down the rest of the output to know the progress.
In the manner of recursion, I repeated slicing the list through mid(which is median of list).
Until the median and 'x' match.
Below median, in other words left of median. There was no problem finding the value in.
There was a problem when finding the value on the right side of the median.
Below are the results of the execution of bin_search ([1, 2, 3, 4, 5, 6, 7], 5).
[Execution Result]
bin_search ([1, 2, 3, 4, 5, 6, 7], 5)
range(0, 7)
len(r) 7
start 0
stop 7
mid 3
x 5 ss[mid] 4
----[x > ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
----[x < ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
.
.
.
#RecursionError: maximum recursion depth exceeded while calling a Python object
Since x = 5, ss[mid] = 6, shouldn't the range of range be reduced to (4,5)?
Just like my prediction below
[Expected Result]
range(0, 7)
len(r) 7
start 0
stop 7
mid 3
x 5 ss[mid] 4
----[x > ss[mid]]----
range(4, 7)
len(r) 3
start 4
stop 7
mid 5
x 5 ss[mid] 6
----[x < ss[mid]]----
range(4, 5)
len(r) 3
start 4
stop 5
mid 4
x 5 ss[mid] 5
----[x = ss[mid]----
answer 4
Besides, when len(r) becomes 0, I thought I would print None, but I can't get any output.
Doesn't None print out when all the runs are over? I thought None would be printed because there was no range to search anymore, but I don't know why it couldn't be printed.
No matter how hard I think about it, I don't know if there's a problem with the code. If you know anything about it, I'd appreciate it if you could help me.

Python: How to make numeric triangle with recursion

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx
You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)
Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

Recursive Pascals Triangle Layout

So i've managed to get Pascals Triangle to print successfully in terms of what numbers are printed, however, i can't get the formatting correct using:
n = int(input("Enter value of n: "))
def printPascal(n):
if n <= 0: #must be positive int
return "N must be greater than 0"
elif n == 1: #first row is 1, so if only 1 line is wanted, output always 1
return [[1]]
else:
next_row = [1] #each line begins with 1
outcome = printPascal(n-1)
prev_row = outcome[-1]
for i in range(len(prev_row)-1): #-1 from length as using index
next_row.append(prev_row[i] + prev_row[i+1])
next_row += [1]
outcome.append(next_row) #add result of next row to outcome to print
return outcome
print(printPascal(n))
this prints as:
Enter value of n: 6
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]
which is correct, however i want it to be formatted as a right angle triangle such as:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
my issue is, i'm new to this language and cannot work out where to put the splits and such in my code to be able to get it to print as this.
Any help or nudge in the right direction would be very much appreciated.
Thanks.
You want to use the str.join() function, which prints out all elements in a list separated by a string:
>>> L = printPascal(6)
>>> for row in L:
... print ' '.join(map(str, row))
...
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
' '.join(list) means you're printing out every element in a list separated by a space (' ').
However, every element in the list needs to be a string in order for the join function to work. Yours are integers. To fix this, I've changed all the integers to strings by doing map(str, row). This is equivalent to:
new_list = []
for item in row:
new_list.append(str(item))
Or as a list comprehension:
[str(item) for item in row]

Python: print without overwriting printed lines

I have
for i in range(0, 11): print i, "\n", i
I'd like my python program to print this way for each for loop
1st loop:
1
1
2nd loop:
1
2
2
1
3rd loop:
1
2
3
3
2
1
I've tried using \r\n or \033[1A but they just overwrite the previous line. Is there a way I can "push" the outputted line down so I don't overwrite it?
One way to do this,
def foo(x, limit):
if x < limit :
print x
foo(x + 1, limit)
print x
foo(1, 11)
It's not possible to do it in 1 for loop as you're currently trying.
As I suggested, you can do it like this by using lists
>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
... l1.append(i)
... l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
... print i
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
Concatenation of two list generators.
>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
... print x
...
0
1
2
3
4
5
4
3
2
1
0
>>>
one of ways to solve this
def two_side_print(start, end):
text = [str(i) for i in range(start,end)]
print '\n'.join(text), '\n', '\n'.join(reversed(text))
two_side_print(1, 11)
Another option is to save the printed values in a list and print that list in reverse order in each loop iteration.
My suggestion:
l = []
for i in range(1, 5):
print 'Loop '+str(i) # This is to ease seeing the printing results
for val in l:
print val
print i
l.insert(len(l),i)
for val in reversed(l):
print val
The output for a loop iterating from 0 to 5:
Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1
I hope this is what you are looking for.
You can use a recursive function to help here:
def print_both_ways(start, end):
print(start)
if start != end:
print_both_ways(start+1, end)
print(start)
Usage:
print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines

Categories

Resources