How does mentioned output get? please explain the code - python

arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
Answer is :2 3 4 5 6 6

This is your code:
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
arr is a list comprised of 6 integers.
In your first for loop, i will vary from 1 to 5 (inclusive).
Python lists are accessed using base-0 - i.e., the first element is at index zero, the second at 1 and so on.
Therefore your loop is moving every element to the position (index) that immediately precedes it. Nothing is moved into index 5

if you are refering to get the following result : 2 3 4 5 6 1
then you should rearrange the following way:
for i in range(0, 6):
arr[i-1] = arr[i]
that way, you start with arr[-1] = arr[0], so 6 will be replaced with 1 and so the code goes on

Related

how to fix this program to show output as 4 numbers per row in python

I have written a program where I need to input a length and it returns the digits in the Fibonacci number sequence.
Write a program that given an input n, outputs the first n Fibonacci numbers. The format of the output is that at most 4 numbers can be displayed in a row.
My problem is, when i run the program the output shows [0, 1, 1, 2, 3, 5, 8, 13, 21, 34].
I need the solution to show 4 numbers per row ie
0 1 1 2
3 5 8 13
21 34
Please find attached my code.
def number(n):
if n ==1:
print(0)
else:
li = [0, 1]
for i in range(2, n): # start the loop from second index as 'li' is assigned for 0th and 1st index
li.append(li[-1] + li[-2])
i += 1
print(li)
n = int(input('Enter a positive number:'))
number(n)
Can you please explain how I can achieve the desired result?
The trouble is this line of code:
print(li)
which only prints out a big list.
Instead, split the list into groups of 4:
li = [li[i:i+4] for i in range(0, len(li), 4)]
Now you can print each element in this list, with a newline so that they are on different lines:
print(*li, sep="\n")
This "unpacks" the list into its elements (which are themselves lists of at most length 4), then prints them out, separating each element with a newline.
Putting it all together:
def number(n):
if n ==1:
print(0)
else:
li = [0, 1]
for i in range(2, n): # start the loop from second index as 'li' is assigned for 0th and 1st index
li.append(li[-1] + li[-2])
i += 1
li = [li[i:i+4] for i in range(0, len(li), 4)]
print(*li, sep="\n")
>>> number(10)
[0, 1, 1, 2]
[3, 5, 8, 13]
[21, 34]

list index out of range in a merge and sort function

I tried writing a simple merge and sort function in python and got stuck after getting the following error-
List out of range.
I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below-
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 or j < len2:
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [1, 3, 7, 9, 0]
merge(lst1, lst2)
What I got:
IndexError Traceback (most recent call last)
<ipython-input-13-572aad47097b> in <module>()
22 lst1 = [2, 4, 5, 6, 8]
23 lst2 = [1, 3, 7, 9, 0]
---> 24 merge(lst1, lst2)
<ipython-input-13-572aad47097b> in merge(lst1, lst2)
7 len2 = len(lst2) - 1
8 while i < len1 or j < len2:
----> 9 if lst1[i] < lst2[j]:
10 merge_sorted.append(lst1[i])
11 i += 1
IndexError: list index out of range
Your problem is the while condition:
while i < len1 or j < len2:
it should be and - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done.
Your current code still enters the while-body and checks if lst1[i] < lst2[j]: if one of the i / j is bigger then the list you get the error you have.
The full fixed code:
def merge(lst1, lst2):
# Gets two sorted lists and returns one merged and sorted list
merge_sorted = []
i = 0
j = 0
len1 = len(lst1) - 1
len2 = len(lst2) - 1
while i < len1 and j < len2: # use and
if lst1[i] < lst2[j]:
merge_sorted.append(lst1[i])
i += 1
elif lst1[i] > lst2[j]:
merge_sorted.append(lst2[j])
j += 1
else:
merge_sorted.append(lst1[i])
merge_sorted.append(lst2[j])
i += 1
j += 1
# add remainder lists - the slices evaluate to [] if behind the list lengths
merge_sorted.extend(lst1[i:]) # if i is aready out of the list this is []
merge_sorted.extend(lst2[j:]) # if j is aready out of the list this is []
return merge_sorted
lst1 = [2, 4, 5, 6, 8]
lst2 = [0, 1, 3, 7, 9] # fixed input, needs to be sorted, yours was not
print(merge(lst1, lst2))
Output:
[0, 1, 2, 3, 4, 5, 6, 8, 7, 9]
As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines.
Just extend the list1 elements like
list1.extend(list2)
once the elements are into the list1
print(set(sorted(list1)))
First of all, Your logic is wrong! You are picking the lower numbers and putting them into the list. but what about the biggest number of all? You will be stuck there! Because you will never pick the last one!
I changed the logic. Instead of counting up the iterators, I removed the picked ones! and when one list got empty the rest of the other one will join the final list.
and secondly, don't use the "merge" name for your function! It's occupied!
def merger(l1, l2):
merge_sorted = []
t1, t2 = sorted(l1), sorted(l2)
while len(t1) != 0 and len(t2) != 0:
if t1[0] <= t2[0]:
merge_sorted.append(t1[0])
t1 = t1[1:]
else:
merge_sorted.append(t2[0])
t2 = t2[1:]
return merge_sorted + (t1 if len(t1) != 0 else t2)
lst2 = [2, 4, 5, 6, 8]
lst1 = [1, 3, 7, 9, 0, 10]
print(merger(lst1, lst2))
Here are the values for i, j just before that if condition-
0 0
0 1
1 1
1 2
2 2
3 2
4 2
4 3
5 3
When any of the lists is traversed till the end, it throws index out of range error.
Solution-
Instead of using or condition, use and condition and append the remaining list elements at the end of the sorted list.

Printing given pattern using for loop

I have written the following code and it runs but I am using 4 for loops and I would like to know if there is more effective way to write this code.
n = int(input('Please Enter the highest number \n'))
col = 2*n-1
for i in range(1, n+1):
for j in range(1, col+1):
if j >= i and j <= col-i+1:
print(n-i+1, end=' ')
elif j < i:
print(n+1-j, end=' ')
else:
print(j+1-n, end=' ')
print()
for i in range(n-1, 0, -1):
for j in range(1, col+1):
if j >= i and j <= col - i + 1:
print(n-i+1, end=' ')
elif j < i:
print(n + 1 - j, end=' ')
else:
print(j + 1 - n, end=' ')
print()
You could find the position relative to the center (di, dj), and then use its largest component as the label for that cell:
n = int(input('Please Enter the highest number \n'))
col = 2 * n
for i in range(1, col):
row = []
for j in range(1, col):
di, dj = abs(n-i), abs(n-j)
row.append(max(di,dj) + 1)
print(' '.join(str(x) for x in row))
Problem Definition
Breaking this down into a few logical obsevations.
We have a grid of numbers that appears symmetrical.
However, the middle row / middle column are only repeated once, this is
important.
Therefore it is more similar to looking down on a pyramid
from above, where 1 represents the highest point, and 4 / n the
lowest.
So we know that to follow DRY principle, we only need to generate one corner of the pyramid, and then we simply copy it to the other 3 corners.
Solution
(assuming use of pure python 3.x only, without libraries such as numpy)
def print_pyramid(n=4):
"""Print a symmetrical pyramid of numbers descending from n"""
# Calculate bottom half of grid
bottom = []
for j in range(n):
row = [max(i, j + 1) for i in range(1, n + 1)]
row = row[::-1][:-1] + row
bottom.append(row)
# Invert bottom to get top
rows = bottom[::-1][:-1] + bottom
# Print formatted
for row in rows:
row_str = [str(i) for i in row]
print(f"{' '.join(row_str)}")
print_pyramid(4)
This is definitely not the most efficient method (see recursive functions), but it is fairly quick and pythonic.
Explanation
Bottom Right corner
First we generate an array of numbers, 1 => n:
[i for i in range(1, n + 1)]
[1, 2, 3, 4]
Then we loop n times to generate this for each row (j), but replace any values lower than j using max:
for j in range(n):
row = [max(i, j+1) for i in range(1,n+1)]
[1, 2, 3, 4]
[2, 2, 3, 4]
[3, 3, 3, 4]
[4, 4, 4, 4]
Bottom Left Corner (~mirror image)
First we select the row elements in reverse with slice notation [::-1]
Then we remove the last element [:-1]
row = [max(i, j+1) for i in range(1,n+1)]
row[::-1][:-1]
[4, 3, 2]
[4, 3, 2]
[4, 3, 3]
[4, 4, 4]
Top Half
Now we create the top half using the same slicing technique to reverse and select from our existing nested array.
bottom[::-1][:-1]
[4, 4, 4, 4, 4, 4, 4]
[4, 3, 3, 3, 3, 3, 4]
[4, 3, 2, 2, 2, 3, 4]
Finally, we print our full array with string formatting
for row in rows:
row_str = [str(i) for i in row]
print(f"{' '.join(row_str)}")
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
P.S. Please don't cheat on your homework assignments ;)
Since the inner loops are identical, you could join the two outer loops into one, e.g. by chaining the two ranges:
from itertools import chain
...
for i in chain(range(1, n + 1), range(n - 1, 0, -1)):
...
The condition can be simplified like this:
i <= j <= col - i + 1

How to ignore numbers after specific number in the list/array in Python?

I'm stuck on this problem:
I was trying to return sum of list of numbers in the array ignoring sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
Here are my test cases:
number_69([1, 3, 5]) --> 9
number_69([4, 5, 6, 7, 8, 9]) --> 24
number_69([2, 1, 6, 9, 11]) --> 14
I came up with something like:
def number_69(arr):
for num in arr:
if 6 not in arr and 9 not in arr:
return sum(arr)
return 0
i guess we stop adding when we see 6 and we start again when we see 9
def number_69(arr):
sum = 0
stop = False
for num in arr:
if num == 6:
stop = True
elif num == 9:
stop = False
elif stop is False:
sum = sum + num
return sum
print(number_69([2, 1, 6, 9, 11]))
Great name for a function BTW
def summer_69(arr):
toSum = True
sum = 0
for x in arr:
if toSum :
if(x == 6):
toSum = False
else :
sum += x
else :
if(x == 9):
toSum = True
return sum
Hope it is useful
Another attempt, using list.pop:
lst = [4, 5, 6, 7, 8, 9]
def summer_69(lst):
s = 0
while lst:
i = lst.pop()
if i == 9:
while i!=6:
i = lst.pop()
else:
s += i
return s
print(summer_69(lst))
Prints:
9
You can iteratively slice out the parts between the 6 and the 9 until there are no more pairs, then call sum on the remainder.
For 'slicing' we use the Python's index slicing, which works by giving a start index and an end index (which will not be included).
>>> [0, 1, 2, 3][1:3] == [1, 2]
True
>>> [0, 1, 2, 3][1:]
[1, 2, 3]
>>> [0, 1, 2, 3][:2]
[0, 1]
We find the locations of the first 6 and the first following 9 with list.index. We do have to make sure to only start looking for a 9 after the 6. This gives
def number_69(arr):
while 6 in arr:
index = arr.index(6)
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
return sum(arr)
Since we know that every 6 will be followed by a 9, there is no need to check whether there is a 9 in the list. Thus, this function will remove all 6-9 blocks and only then return the sum of the entire list.
If there is a 6 without an accompanying 9 this function will raise a ValueError. This can be solved by checking for a 9 anyways, but this has to be done after the index of the first 6. If no 9 is found, we also have to break out of the loop, since the 6 will not be removed.
def number_69(arr):
while 6 in arr:
index = arr.index(6)
if 9 in arr[index:]:
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
else:
break
return sum(arr)
def summer_69(arr):
pop = []
for i in arr:
if i <=9 and i>=6:
continue
else:
pop.append(i)
return pop

creating sum of odd indexes python

I'm trying to create a function equal to the sum of every other digit in a list. For example, if the list is [0,1,2,3,4,5], the function should equal 5+3+1. How could I do this? My knowledge of Python does not extend much farther than while and for loops. Thanks.
Here is a simple one-liner:
In [37]: L
Out[37]: [0, 1, 2, 3, 4, 5]
In [38]: sum(L[1::2])
Out[38]: 9
In the above code, L[1::2] says "get ever second element in L, starting at index 1"
Here is a way to do all the heavy lifting yourself:
L = [0, 1, 2, 3, 4, 5]
total = 0
for i in range(len(L)):
if i%2: # if this is an odd index
total += L[i]
Here's another way, using enumerate:
L = [0, 1, 2, 3, 4, 5]
total = 0
for i,num in enumerate(L):
if i%2:
total += num
>>> arr = [0,1,2,3,4,5]
>>> sum([x for idx, x in enumerate(arr) if idx%2 != 0])
9
This is just a list comprehension that only includes elements in arr that have an odd index.
To illustrate in a traditional for loop:
>>> my_sum = 0
>>> for idx, x in enumerate(arr):
... if idx % 2 != 0:
... my_sum += x
... print("%d was odd, so %d was added. Current sum is %d" % (idx, x, my_sum))
... else:
... print("%d was even, so %d was not added. Current sum is %d" % (idx, x, my_sum))
...
0 was even, so 0 was not added. Current sum is 0
1 was odd, so 1 was added. Current sum is 1
2 was even, so 2 was not added. Current sum is 1
3 was odd, so 3 was added. Current sum is 4
4 was even, so 4 was not added. Current sum is 4
5 was odd, so 5 was added. Current sum is 9
let's take this list as an example:
l = [1,2,3,4,5]
for even indexes sum:
even_index_eles = l[1::2] # [2, 4]
sum(even_index_eles) # 6
for odd indexes sum:
odd_index_eles = l[::2] # [1, 3, 5]
sum(odd_index_eles) # 9
it's worked with odd or even length of list

Categories