Nested Loops to create a pattern - python

How could I use Nested Loops to create the following pattern?
111111
11111
1111
111
11
1
So far i have this and i seem to be stuck.
def main():
stars = "******"
for x in range (1,7):
print(stars)
for y in range (1,1):
stars = stars.replace("*"," ")
main()

You need to replace just 1 star in the inner loop:
stars = "******"
for x in range(6):
stars = stars.replace("*","1")
print(stars)
for y in range(1): # need range(1) to loop exactly once
stars = stars.replace("1","",1)
Output:
111111
11111
1111
111
11
1
If you actually want stars:
stars = "******"
for x in range(6):
print(stars)
for y in range(1):
stars = stars.replace("*","",1)
Output:
******
*****
****
***
**
*
The last arg to str.replace is count where only the first count occurrences are replaced. So each time we only replace a single character.
If you have to uses the stars variable and replace then the code above will work, if you just need nested loops and to create the pattern, you can loop down from 5 and use end="" printing once in the inner loop:
for x in range(5, -1, -1):
print("1" * x, end="")
for y in range(1):
print("1")
Again the same output:
111111
11111
1111
111
11
1

def main(symbol, number):
for x in reversed(range(number)):
s = ""
for y in range(x+1):
s += symbol
print s
main("1", 6)
You can give arguments one symbol (Example - '1','*') and number (Example - '5 for *****' to start with)

You are replacing all the stars in the string with the replace method, meaning you would online print one line of start. You could use the substring method for a better result.

Check answer of Padraic Cunningham with Nested Loop.
Without Nested Loop:
Create Count list by range method and reverse method of list.
Iterate list and print 1 multiple of count.
code:
counters = range(1, 7)
counters.reverse()
for i in counters:
print "1"*i
Output:
111111
11111
1111
111
11
1

Since you're requesting a nested loop, I guess this is just a training exercise and it is not important how efficient it is.
Therefore let me propose a solution with a 'proper' inner loop and without reversed ranges:
def triangle(x, c='1'):
for i in range(x):
line = ''
for _ in range(i, x):
line += c
print(line)

You can get the same output using a simple approach, as Python supports * operator on Strings which returns a string with repeated occurrences.
character = "1" #You can change it to "*"
for i in range(6, 0, -1):
print character*i
Output:
111111
11111
1111
111
11
1

Related

Python program which prints out line number and length of list: Error

Now I'm using while loops to try and do this because I'm not too good at using for loops. As the title reads, I'm trying to print out a table which has the line number next to the length of each line.
Error: When I hit run all I get is the above print out (line and number of words with dashes below). I do not get a series of printouts of y and z
Note: I'm probably making this way harder than it needs to be
Code:
list1 = ['Lets go outside','pizza time','show me the money']
list2 = []
print('line number of words')
print('---- ---------------')
x = 0
len_l1 = len(list1)
while len_l1 > 0:
split_lis1 = list1[0+x].split(' ')
list2.append(split_lis1)
len_l1 -= 1
x += 1
while len_l1 > 0:
q = 1
y = len(list1) - len(list1) + q(x)
z = len(list2[0+x])
print(y, z)
len_l1 -= 1
x += 1
what I want the print out to look like:
line number of words
---- ---------------
0 3
1 2
2 4
Thanks.
Yes, you might have overcomplicated the solution as there are out of the box Python methods that help you easily solve problems like this. For iteration with indexes, use enumerate, in the example below we set the index to start at 1. We can also use some simple string formatting defined in fmt to ensure consistent spacings.
li = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
fmt = ('{} {}')
for idx, sentence in enumerate(li,1):
no_of_words = len(sentence.split())
print(fmt.format(idx, no_of_words))
Then simple use split to split the whitespaces and get the total number of words and let enumerate manage the whole thing for you.
>>
line number of words
---- ---------------
1 3
2 2
3 4
list1 = ['Lets go outside','pizza time','show me the money']
print('line number of words')
print('---- ---------------')
for i in range(0, len(list1)):
length = len(list1[i].split(" "))
print(i + 1, " ", length)
Check out python docs for range and for details.

How does str.replace() method work?

I have this input:
'0472/91.39.17'
I want to replace my input with '1234567890' one by one like this:
'1234/56.78.90'
But my outcome is
0472/91.09.17
Here's my code
phone = '0472/91.39.17'
repl = 1234567890
for i in phone:
if i.isdigit():
for j in str(repl):
x = phone.replace(i, j)
print(x)
What is the proper way to do this?
You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. Re-combine that together with ''.join to get a string as a result, and Bob's your uncle.
repliter = iter(str(repl))
result = ''.join(next(repliter) if c.isdigit() else c for c in phone)
# the ternary expression here evaluates to:
# if c.isdigit():
# next(repliter)
# else:
# c
Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead.
import itertools
repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...
I was thinking you could use itertools count with modulus for numbers higher than 10.
from itertools import count
c = count(0) # start number
phone = '0472/91.39.17'
''.join(str(next(c) % 10) if item.isdigit() else item for item in phone)

changing a for loop to a while loop

I was wondering how I could change the following lines of codes to use a while loop instead of a for loop.
for num in range(10):
print(num+1)
It currently prints out the following:
1
2
3
4
5
6
7
8
9
10
Thanks!
start = 0
while start != 10:
start = start + 1
print(start)
hope this hepls
number = 1
while (number <=10):
print 'The number is:', number
number = number + 1
The for loop runs over an iterable, while a while loop runs while a condition is true, so you just need to think of the right condition.
Here, something counting up to 10 will work:
>>> number = 0
>>> while number < 10:
... print(number + 1)
... number += 1
...
1
2
3
4
5
6
7
8
9
10
Writing code that has the same output is not the same as rewriting code to do the same thing. Other answers simply do the former, so this solves the latter:
numbers = range(10)
while numbers:
numbers.pop(0) + 1
The original code iterates over a list that does not exist outside of the loop - it could work with a list of something other than range(10), but it's not necessarily just a '+ 1' operation.
The conditional statement for a while loop, however, needs to be true for the loop to begin so the list should already exist. To keep true to the spirit of the original code, we use range() to create the list, and use pop() to iteratively remove the first element from it.
The differences here are that a variable (numbers) gets used, but is empty after the loop, and we don't rely on list comprehension to iterate, but explicitly remove the first element until 'numbers', being empty, results in a false condition.
well..... a while statement operates UNTIL a certain condition is met, as the for operates for a set of given iterations.
in your case you want to print stuff until num reaches 10, so
while num <= 10 :
print num
num = num + 1
would do

Taking user input of 2-D array in a given format

I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.
There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)
Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]

Python - replay values in list

Please help for task with the list in Python my logic is bad works:( .
This is full text of task: Write a program that takes a list of
numbers on one line and displays the values in a single row, are
repeated in it more than once.
To solve the problem can be useful sort method list.
The procedure for withdrawal of repetitive elements may be arbitrary.
My beginning code is :
st = (int(i) for i in input().split())
ls = []
for k in st:
if k == k + 1 and k > 1:
Task is : if we have replay value in list we must print it. We only can use sort() method and without any modules importing.
Results Examples:
Sample Input 1:
4 8 0 3 4 2 0 3
Sample Output 1:
0 3 4
Sample Input 2:
10
Sample Output 2:
Sample Input 3:
1 1 2 2 3 3
Sample Output 3:
1 2 3
This code isn't run( sort() function doesn't want sort my_list. But I must input values like my_list = (int(k) for k in input().split())
st = list(int(k) for k in input())
st.sort()
for i in range(0,len(st)-1):
if st[i] == st[i+1]:
print(str(st[i]), end=" ")
my_list = (int(k) for k in input().split())
After running this line, my_list is a generator, something that will create a sequence - but hasn't yet done so. You can't sort a generator. You either need to use []:
my_list = [int(k) for k in input().split()]
my_list.sort()
which makes my_list into a list from the start, instead of a generator, or:
my_list = list(int(k) for k in input().split()))
my_list.sort()
gather up the results from the generator using list() and then store it in my_list.
Edit: for single digits all together, e.g. 48304, try [int(k) for k in input()]. You can't usefully do this with split().
Edit: for printing the results too many times: make the top of the loop look backwards a number, like this, so if it gets to the second or third number of a repeating number, it skips over and continues on around the loop and doesn't print anything.
for i in range(0,len(st)-1):
if st[i] == st[i-1]:
continue
if st[i] == st[i+1]:
print...
st = (int(i) for i in input().split())
used = []
ls = []
for k in st:
if k in used: # If the number has shown up before:
if k not in used: ls.append(k) # Add the number to the repeats list if it isn't already there
else:
used.append(k) # Add the number to our used list
print ' '.join(ls)
In summary, this method uses two lists at once. One keeps track of numbers that have already shown up, and one keeps track of second-timers. At the end the program prints out the second-timers.
I'd probably make a set to keep track of what you've seen, and start appending to a list to keep track of the repeats.
lst = [num for num in input("prompt ").split()]
s = set()
repeats = []
for num in lst:
if num in s and num not in repeats:
repeats.append(num)
s.add(num)
print ' '.join(map(str,repeats))
Note that if you don't need to maintain order in your output, this is faster:
lst = [num for num in input("prompt ").split()]
s = set()
repeats = set()
for num in lst:
if num in s:
repeats.add(num)
s.add(num)
print ' '.join(map(str, repeats))
Although if you can use imports, there's a couple cool ways to do it.
# Canonically...
from collections import Counter
' '.join([num for num,count in Counter(input().split()).items() if count>1])
# or...
from itertools import groupby
' '.join([num for num,group in groupby(sorted(input().split())) if len(list(group))>1])
# or even...
from itertools import tee
lst = sorted(input('prompt ').split())
cur, nxt = tee(lst)
next(nxt) # consumes the first element, putting it one ahead.
' '.join({cur for (cur,nxt) in zip(cur,nxt) if cur==nxt})
this gives the answers you're looking for, not sure if it's exactly the intended algorithm:
st = (int(i) for i in input().split())
st = [i for i in st]
st.sort()
previous = None
for current in st:
if ((previous is None and current <= 1)
or (previous is not None and current == previous + 1)):
print(current, end=' ')
previous = current
>>> "4 8 0 3 4 2 0 3"
0 3 4
>>> "10"
>>> "1 1 2 2 3 3"
1 2 3
updated to:
start with st = (int(i) for i in input().split())
use only sort method, no other functions or methods... except print (Python3 syntax)
does that fit the rules?

Categories

Resources