So I'm trying to do this
You will be given a positive integer n > 0 and you will construct a pattern that is made up of n rows:
• Row 0 contains 1 number—the number 1
• Each row is one longer than the one before and follows the pattern that ensues
So if variable n:int = 4, the output would be
[1]
[1,2]
[2,3,5]
[5,7,10,15]
The number in the current array is added to the number immediately above it in the previous array and appended at the end of the current array. Also when starting a new array the last element of the previous array is considered as the first element of the current array.
I apologize if my question is unclear, but I hope after the example and explanation I provided, the question is clearer now.
Here is my code:
def append(n: int):
for x in range(1,n+1):
return(x,x+1)
print(append(n))
When I put n = 4, it doesnt seem to work, what's the problem here?
This will do it:
def func(n):
mylist = []
for i in range(n):
if i == 0:
mylist.append([1])
else:
mylist.append(createnewlist(mylist[i-1]))
return mylist
def createnewlist(a):
newlist = []
for i in range(len(a)+1):
if i == 0:
newlist.append(a[len(a)-1])
else:
value = a[len(a)-1]
for m in range(i):
value += a[m]
newlist.append(value)
return newlist
print(func(6))
I don't think your code will return the pattern you want to show. Here's a little code I wrote to print that pattern but there are two loops running, if you could optimize that you could do it or else use the code just as it is.
n=4
arr=[1]
brr = [1]
print(brr)
for i in range(0,n-1):
brr = arr[i:]
for k in range(0,len(arr)):
brr.append(arr[k]+brr[k])
arr = brr
print(brr)
Related
I've written a code which works pretty well, no errors, no problems. But no matter how hard I try to print the list values each in a new line, it still wouldn't work. I've tried sep='\n', and even tried to put the list in a loop to print each value one by one. I still get the result printed all in a row, in one line. This sounds too annoying and I can't figure out why my code is having this strange behavior. Here's my code:
length = int(input())
input_string = [int(y) for y in input().split()]
def lowest(string):
return(min(x for x in string if x is not None))
def none_set(string):
for k in range(length):
if string[k] != None:
if string[k] <=0:
string[k] = None
def counter(string):
nums = 0
for h in range(length):
if string[h] != None:
nums += 1
return nums
cnt = []
for i in range(length):
minimum = lowest(input_string)
none_set(input_string)
cnt.append(counter(input_string))
for j in range(length):
if input_string[j] != None:
input_string[j] -= minimum
result = list(set(cnt))[::-1]
print(result, sep='\n') #Doesn't print the values in new line :/
Sample Input:
6
5 4 4 2 2 8
Expected Output:
6
4
2
1
The Output I Get:
[6, 4, 2, 1]
In case you want to know what exactly my code does, check this link here (No login/signup needed), however, the issue is not really relative to what the goal of my code is, I'd say.
I appreciate in advance, for any tip, solution, or help.
It's because you're printing the whole list.
lst = ['a','b','c']
If I print this list I get ['a','b','c']. To print each item you can use a for loop like so:
lst = ['a','b','c']
for item in lst:
print(item)
#output:
a
b
c
Try this.
for i in result:
print(i)
Try to print like that:
for i in result:
print(i)
Use join() instead of multiple calls to print(). Some will consider it more difficult to read, but it's definitely more efficient even for small lists, and orders of magnitude faster for lists greater than 100 elements.
print("\n".join(map(str, result)))
def back_interleave(first, second):
if first == [] and second == []:
return []
elif first == []:
return second[::-1]
elif second == []:
return first[::-1]
else:
newlist = []
for i in range(len(first)-1, 0,-1):
newlist.append(first[i])
newlist.append(second[i])
for j in range(len(second)-len(first)-1,0,-1):
newlist.append(second[i])
return newlist
can anybody tells me what's wrong with my code towards this question.
I'm not exactly sure what's wrong with your code, but the second and third if-statements appear to use built-in list reversing functionality which the original problem forbids.
What I would do is determine the length of the longer list, then iterate through both lists backwards.
def back_interleave(first, second):
newlist = []
# You want to iterate through the length of the longer list
length = max(len(first), len(second))
for x in range(length):
# start appending elements from the back of the list
index = -1*(x+1)
if x < len(first):
newlist.append(first[index])
if x < len(second):
newlist.append(second[index])
return newlist
The problem in your code is when you use the range function, the stop value is exclusive i.e., the index 0 is becoming exclusive in your case. And also in the j loop the values at index i are being stored instead of the values at index j.
#CyanideTesla has given the code that works pretty well for your problem
I am trying to solve problem 189 on leetcode
The question is:
Given an array, rotate the array to the right by k steps, where k is non-negative.
According to the solution, I have tried out to implement the idea given in approach 2: by using an "extra" array. Still, I am unable to get the desired result. What's the issue with this code?
I tried brute force approach as well but it's not accepted there, so trying this!! Any help would be appreciated!
i = 0
l = len(nums)
arr = [0]*l
while i < len(nums):
split = l-k
if i >=0 and i < split:
arr[i+k] = nums[i]
if i >= k+1 and i < l:
arr[i-k-1] = nums[i]
i+=1
nums = [0]*l
for a in range(0,l):
nums[a] = arr[a]
print(arr)
print(nums)
After getting some help, I tried with the slicing approach(as suggested in the comments) and this is the code I could come up with:
l = len(nums)
a = nums[:l-k] # appending part
nums = nums[l-k:] # real array
for i in a:
nums.append(i)
print(nums)
Still, this is not running on that website. I am getting the correct output array but not exactly what's the requirement.
Check the below out. I came up with the correction needed.
from typing import List
def rotate(nums: List[int], k: int) -> None:
l = len(nums)
a = nums[:l-k] # appending part
# nums = nums[l-k:] # real array # -> How you have written
nums[:] = nums[l-k:] # real array # -> How it should be
for i in a:
nums.append(i)
# print(nums) # Not needed
nums = [1,2,3,4,5]
rotate(nums, 3)
print(nums)
Problem with you code is that, the task expects you to modify the list that is being passed into the function. However when you assign it like nums = nums[l-k:], that will be visible only to within the function. That's why when you print it you saw the expected result. But that assignment will not modify the list referred to by that variable. Instead, you should do the assignment like nums[:] = nums[l-k:], in order to modify the list, which is in the global scope.
I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.
This is the code I have so far in Python:
i = 0
j = 0
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
count.append(k)
print(count)
Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?
Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.
Any and all help is appreciated.
For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.
You can try this if you want nothing but zero elements.
print [element for element in count if element == 0]
If I understand your question right the answer for your question is like this.
i = 0
j = 0
for i in range (1,10):
# Resetting so that count will not have previous values
count = []
for j in range(1,11):
k = i%j
count.append(k)
# printing all the indexes where the value is '0'
print([index for index, item in enumerate(count) if item == 0])
You know your range of extern loop so you can just write your code in this way :
count = []
for i in range (1,10):
for j in range(1,11):
k = i%j
if(i == 9):
count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])
i have homework in which i must use recursion to find all occurances of a number/letter/word in a list and return their index in the original list.. I have searched this site for previously answered question but I couldn't find any answer regarding recursion with the option to continue checking the list even after the first occurances has been found..
should look like this pretty much:
>>> find_value( [4,7,5,3,2,5,3,7,8,6,5,6], 5)
[2,5,10]
my code so far goes like this:
def find_all(x,y):
if len(x) == 1 and x[0] == y:
return [i for i, y in enumerate(x)]
return find_all(x[1:],y)
Though it only minimize the list and gives me the same [0] as the index.. which is true, for the divided list.. this way I will never get the original index..
Thanks
- if this already exist, I am sorry for i have searched and couldn't find.
Here is a simple non-recursive solution:
def find_value(l, lookfor):
return [i for i, v in enumerate(l) if v == lookfor]
As a piece of advice for your homework -- just pass the progress through the list as an optional third argument to find_all:
def find_value(list, lookfor, position=0)
... and add one to position each time you recurse.
The point of assigning a homework is usually so that you can explore the problem and learn from it. In this case, it is recursion which is usually hard for beginners.
The point of recursion is to construct an answer for a larger problem from a solution of a smaller ones. So it is best to start off with the smallest one possible:
def find_all(haystack, needle):
if not haystack:
# no occurrences can happen
return []
If the list is not empty, we can check if the first element is what we are looking for:
if haystack[0] == needle:
occurrences = [0] # the index of the first element is always 0
else:
occurrences = []
We will also need the solution to the smaller problem:
recursive_occurences = find_all(haystack[1:], needle)
Now the problem you have noticed is that the indices that are returned are always 0. That's because they are indices in the smaller list. If an item has index 0 in a smaller list, it means its index in the largest list is actually 1 (this is the main part your program was missing), thus:
for x in recursive_occurences:
occurrences.append(x+1)
And return the complete answer:
return occurrences
I hope this helps you a bit, so you can do your next homework on your own.
Here are several solution:
in one go, ugly, but working:
def find_value(lst, elt):
return [x + 1
for x in ([] if not lst else
(([-1] if lst[0] == elt else []) +
find_value(lst[1:], elt)))]
prettier, but with hidden index param:
def find_value(lst, elt, idx=0):
return [] if not lst else \
(([idx] if lst[0] == elt else []) +
find_value(lst[1:], elt, idx + 1))
pretty?, long with inner recursive function... more maintainable ?
def find_value(lst, elt):
def _rec(lst, elt, idx):
if not lst:
return []
res = [idx] if lst[0] == elt else []
return res + _rec(lst[1:], elt, idx + 1)
return _rec(lst, elt, idx=0)
There is a very simple solution to this problem, even if you are using recursion to solve the assignment:
>>> def find_value(array, value):
*head, tail = array
array = find_value(head, value) if head else []
return array + [len(head)] if tail == value else array
>>> find_value([4, 7, 5, 3, 2, 5, 3, 7, 8, 6, 5, 6], 5)
[2, 5, 10]
>>>