Please help
Below is the code
start = 3
end = 5
for x in range(start, end + 1):
print x
#and
#print iterate from 0
I am looking here, x will print 3 4 5
and I also need to print 0 1 2 that first time enter to loop print 0 and second time enter to loop print 1 and so on.
Please help
python has enumerate for just this:
start = 3
end = 5
for i, x in enumerate(range(start, end + 1)):
print(i, x)
which prints:
0 3
1 4
2 5
start = 3
end = 5
counter = 0
for x in range(start, end + 1):
print x
#and
#print iterate from 0
print counter
counter += 1
Related
I've to write a function that takes the limit as an argument of the Fibonacci series and prints till that limit. Here, if the limit is fibonacci(10) then the output should be 0 1 1 2 3 5 8
I tried:
def fibonacci(number):
a = 0
b = 1
print(a,end = ' ')
print(b, end = ' ')
for num in range( 2 , number):
c = a + b
a = b
b = c
print(c, end = " ")
fibonacci(10)
The output came:
0 1 1 2 3 5 8 13 21 34
What should I do?
You can simply just add a check to see if the number resulting from a+b is going to be larger than the limit.
for num in range( 2 , number):
if a+b > number: return
c = a + b
a = b
b = c
print(c, end = " ")
Output:
0 1 1 2 3 5 8
The break statement exits the for loop so that no numbers over the limit will be printed. You can also use return instead of break. However, if you end up adding logic after the for loop, it will not be reached because return will exit the entire function.
SUGGESTION (courtesy of #OneCricketeer)
You may also use a while loop here instead of a range. This achieves the same output with cleaner, easier to understand code.
while (a+b < number):
c = a + b
a = b
b = c
print(c, end = " ")
def fibonacci(limit):
a=0
b=1
print(a,end=" ")
print(b,end=" ")
for i in range(limit):
c=a+b
if c<=limit:
print(c,end=" ")
a=b
b=c
x=int(input())
fibonacci(x)
Input:
10
Output:
0 1 1 2 3 5 8
Please help me print the pattern below as it is, if the input entered is 7:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
I figured out to find the middle element of the pattern with any input:
rows=int(input("Enter the number of rows:"))
l=[]
for x in range(1,rows+1):
if x%2!=0:
l.append(x)
mid_value=len(l)
Please help me complete the above pattern......
Thanks in advance!
If you use a list-of-lists to store the values, the value for any specific cell can be determined by doing some basic math involving the cell indexes and the number of rows.
An illustration:
def cell_value(i, j, n_rows):
# The value of any cell is the minimum distance
# from its own coordinates (i, j) to the "outside" (ie,
# an i or j less than 0 or equal to n_rows). Imagine an
# ant in the grid. How many steps would it have to take
# to escape the grid, using the shortest route?
return min(
abs(i - -1),
abs(i - n_rows),
abs(j - -1),
abs(j - n_rows),
)
N_ROWS = 7
rows = [
[
cell_value(i, j, N_ROWS)
for j in range(N_ROWS)
]
for i in range(N_ROWS)
]
for r in rows:
print(*r)
Output:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
This looks like a homework question, so I'm going to try and explain how to approach it rather than just provide code.
A few things worth noting to start:
- The pattern's symmetrical in both directions, so we can save some effort and logic by only solving the top-left quarter, and copying it to the rest.
- Each row is similar the the one before, with one added at the point where the row and column indices (i and j) are equal - rather than recalculate every row from scratch, we can take the one before as a base.
So, for the first row, make a list of 1s the length of your input (7, in this case).
Copy this for the seventh row (note: row6 = row0 won't create a copy; you'll need row6 = list(row0) )
For the second and sixth rows, take a copy of the first row. If i is equal to or greater than j and is in the first half of the row, add 1 to it. You'll need to copy that in reverse for the back half of the row. (Alternative - set the value to j+1 rather than just adding 1)
Repeat until the fourth row, and you should be done.
EDIT: code included, because it was an interesting problem
numberOfRows = int(input("Enter the number of rows:"))
listOut = [[1]*numberOfRows] * numberOfRows #grid of 1s of appropriate size
for j in range(int((numberOfRows+1)/2)): #symmetrical, so only look to the middle
if j > 0:
listOut[j] = list(listOut[j-1]) #copy previous row
for i in range(int((numberOfRows+1)/2)):
if i>=j:
listOut[j][i] = j+1
listOut[j][numberOfRows-(i+1)] = j+1
#copy current row to appropriate distance from the end
listOut[numberOfRows-(j+1)] = list(listOut[j])
for row in listOut:
# * for sequence unpacking, printing lists as strings w/o commas
print(*row)
It might not be the most elegant solution but something like this should work:
n = int(input('Enter the number of rows:'))
table = [[1 for _ in range(n)] for _ in range(n)]
start = 0
end = n
while start < end:
start += 1
end -= 1
for i in range(start, end):
for j in range(start, end):
table[i][j] += 1
for row in table:
print(' '.join(str(ele) for ele in row))
Simple implementation without using any list
n = int(input())
x = n
for i in range((n // 2 + 1) if n % 2 and n > 1 else n //2):
for l in range(1, i + 1):
print(l, end=' ')
print((str(i + 1) + ' ') * x, end='')
for r in range(i, 0, -1):
print(r, end=' ')
print()
x -= 2
y = 1
for j in range(n // 2, 0, -1):
for l in range(1, j):
print(l, end=' ')
print((str(j) + ' ') * (2 * y + 1 if n % 2 else 2 * y), end='')
for r in range(j-1, 0, -1):
print(r, end=' ')
print()
y += 1
Basically, I need a code that takes an integer and then prints out the string of numbers with the certain range.
For example:
n = 11
1 2 2 3 3 3 4 4 4 4
n = 7
1 2 2 3 3 3 4
a = []
n = int(input())
if n == 0:
print(n)
for i in range(int(n) + 1):
a += [i] * i
a = ' '.join(map(str, a))
print(a[:n])
This does the job but it counts spaces as characters, so I tried to convert it to an int
n = int(n)
print(' '.join(a[:n]))
But when the n >= 47, it starts to print out 10 as 1 0 which is incorrect
I also tried this code
n = int(input())
for i in range(n):
b = (str(i) * i)
print(b, end = ' ')
But I don't understand how to separate the b with spaces without converting the string to a list and printing it in one line either.
I am not sure if it is even possible.
Maybe something like this?
# initialize variables:
number = 11
counter = 0
for i in range(number):
for j in range(i):
# print number:
print('%d ' %i, end='')
# increment counter (tracks how many numbres to print):
counter += 1
# exit inner loop if counter reaches number:
if counter >= number-1: break
# exit outer loop if counter reaches number:
if counter >= number-1: break
Output:
1 2 2 3 3 3 4 4 4 4
Here's a solution using itertools. Generators, chain, repeat and islice are all lazily evaluated, so this uses O(1) space.
>>> n = 7
>>> from itertools import chain, repeat, islice
>>> gen = chain.from_iterable(repeat(i, i) for i in range(1, n+1))
>>> for i in islice(gen, n):
... print(i, end=' ')
...
1 2 2 3 3 3 4
This seems simple. But this does solve the problem?
>>> for i in t:
... if i!=" ": print i
...
1
2
2
3
3
3
4
4
4
4
or even string replace like,
print t.replace(" ","\n")
1
2
2
3
3
3
4
4
4
4
So what I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign
for eg: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers.
Simillarly for 1 1 -3 2 would get me 1 3 2 1
Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.
j=0
count=0
length=(raw_input())
st=map(int,raw_input().split())
while j+1 < len(st):
k=j+1
count=0
temp=j
while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)):
count+=1
k+=1
j+=1
print count+1,
j=temp+1
print 1
Try using for loops instead of while loops as that avoids you some variable assignments:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
if (st[j]<0 and st[j+1]>0) or (st[j+1]<0 and st[j]>0):
count += 1
else:
break
print(count)
print(1)
This will give:
<< 1 -2 3 4
>> 4
>> 3
>> 2
>> 1
<< 1 1 -3 2
>> 1
>> 3
>> 2
>> 1
It may also be a bit faster if you extract the numbers from the list once instead of twice:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
first, second = st[j:j+2]
if (first<0 and second>0) or (first>0 and second<0):
count += 1
else:
break
print(count)
print(1)
The last thing I would try is checking that they sigs are different with a single comparisson but I do not really expect this to be faster:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
product = st[j] * st[j+1]
if product != abs(product):
count += 1
else:
break
print(count)
print(1)
for i in range(7,0,-1):
for i in range(i-1):
print i,
print
The above code prints:
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
I want to get rid of the zeroes in the first 4 lines.
Start your range at 1 instead of the default 0:
for i in range(1, i-1):
print i,
Instead of ranging to i - 1, adjust your outer loop to produce the right values but increase the end-point; there is little point in producing a range from 1 to 1 or from 1 to 0.
for i in range(6, 1, -1):
for i in range(1, i):
print i,
print
This saves you from printing too many empty newlines at the end:
>>> for i in range(6, 1, -1):
... for i in range(1, i):
... print i,
... print
...
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
You could also use print i + 1 instead of starting at 1; decrement the values in the outer loop in that case:
for i in range(5, 0, -1):
for i in range(i):
print i + 1,
print