This question already has answers here:
How can I reverse a section of a list using a loop in Python?
(5 answers)
Closed 3 years ago.
I have this problem for homework and I have almost gotten it but not quite. I have to develop some code that takes a list and a number as parameters. The function returns a copy of the list with the first number of items reversed. I can not use in-built functions, slicing or reverse, I can only use append.() and range(). Would really appreciate someone's help with fixing my current code and maybe explaining how you fixed it? Thankyou!!!
str_list6 = ['e', 'd', 'u', 'd']
def length(my_list):
total = 0
for c in my_list:
total += 1
return total
def remove_value(my_list):
res = []
for i in range(length(my_list) -1, -1, -1):
res.append((my_list)[i])
return res
the example given:
numList = [1, 2, 3, 4, 5, 6, 7]
number = 4
The call to reverse(numList, number) should
return the new list
[4, 3, 2, 1, 5, 6, 7].
So my code currently simply reverses the list however (its hard to explain), it needs to reverse with the shift of the 'number'. Hopefully this make sense!
The problem here is that you are not taking into account the number to shift. In your example you are given two variables, the list and the number to shift (is this the position or the actual number you are looking for? - assuming position), yet your code only takes the list.
def remove_value(my_list, pos_to_reverse):
res = []
for i in range(pos_to_reverse-1, -1):
res.append(my_list[i])
for i in range(pos_to_reverse, length(my_list)-1):
res.append(my_list[i])
return res
You were getting close! I think the function below does what you want.
def reverse(numList,number):
# Make an empty list
reversedlist=[]
for i in range(number):
# i goes from 0 to number-1
reversedlist.append(numList[number-i-1])
# build a reversed list by adding each element
# of numList going in reverse order.
for i in range(number):
# i goes from 0 to number-1
numList[i]=reversedlist[i]
# change the first 'number' elements of the
# original list with the reversed list.
return numList
numList = [1, 2, 3, 4, 5, 6, 7]
number = 4
print(reverse(numList,number))
# prints: [4, 3, 2, 1, 5, 6, 7]
You can probably do like this.
l = [1, 2, 3, 4, 5, 6, 7]
n = 4
def solution(lst,n):
size = n
hiindex = size - 1
its = size//2
for i in range(0, its):
temp = lst[hiindex]
lst[hiindex] = lst[i]
lst[i] = temp
hiindex -= 1
return lst
print(solution(l,n))
You can use this tiny loop:
numList = [1, 2, 3, 4, 5, 6, 7]
number = 4
def reverse(l, n):
for i in range((n + 1) // 2):
l[i], l[n - i - 1] = l[n - i - 1], l[i]
return l
print(reverse(numList, number))
Output:
[4, 3, 2, 1, 5, 6, 7]
Related
def pairs(x):
for num in x:
if num == num :
return x
y = [2, 2, 2, 2, 2, 4, 3, 3]
pairs (y)
print (y)
this is returning [2, 2, 2, 2, 2, 4, 3, 3]
but I want to return [2,2,3]
I've tried 3 codes already other than this one
help me
Your code seems to be intended to find all the numbers that exist in pairs in the list. The best way would be (for a sorted list) to just cycle through the list and check successive elements.
Your code just matches if the current number is the same as the current numbers always returns true and returns all elements. A correct Code might be:
y = [2, 2, 2, 2, 2, 4, 3, 3]
y=sorted(y) # Sorts the given list
def pairs(arr):
i = 0 # Counter variable
res = [] #result list
while i < len(arr)-1:
if arr[i] == arr[i+1]:
res.append(arr[i]) # If the successive elements are the same, add
# it to the result array and since we have already
# checked the next element, increment the counter by
# two
i+=2
else:
i+=1 # If the elements are different we need to check the
# next element as well so increment by 1
return res
print(pairs(y))
You are comparing the element with itself which is always true. Here is the correct logic
y = [2, 2, 2, 2, 2, 4, 3, 3]
filt = []
i=0
while (i< (len(y)-1)):
if y[i] == y[i+1]:
filt.append(y[i])
i+=1
i+=1
print(filt)
I wrote this code to slice a list out of the center of another and it seems to work, but I feel like it may be possible to do this more neatly and efficiently (possibly with list comprehension)?
def get_middle(num, val_list):
idx_val = (int(num/2) , int(num/2 + num%2))
center_idx = int((len(val_list) - 1)/2)
idx_one, idx_two = center_idx-idx_val[0], center_idx+idx_val[1]
return val_list[idx_one:idx_two]
test_list = [1,2,3,4,5,6,7]
test_num = 3
new_list = get_middle(test_num , test_list )
print(new_list)
The output of the above code is: [3, 4, 5]
Code:
def get_middle(num, sequence):
m = (len(sequence) - 1)//2 - num//2
return sequence[m:m+num]
test_list = [1, 2, 3, 4, 5, 6, 7]
test_num = 3
print(get_middle(test_num, test_list))
Output:
[3, 4, 5]
Yes, you can do it in one line.
test_list[len(test_list)//2-test_num//3:len(test_list)//2+test_num//3+1]
Of course some adjustments have to be done depending on the parity of test_num and the parity of the length of the list.
What I try to do is to write a function sort_repeated(L) which returns a sorted list of the repeated elements in the list L.
For example,
>>sort_repeated([1,2,3,2,1])
[1,2]
However, my code does not work properly. What did I do wrong in my code?
def f5(nums):
count = dict()
if not nums:
for num in nums:
if count[num]:
count[num] += 1
else:
count[num] = 1
return sorted([num for num in count if count[num]>1])
return []
if count[num]: will fail if the dictionary doesn't have the key already. Take a look at the various counter recipes on this site and use one instead.
Also, not nums is true if nums is an empty sequence, which means that the loop body will never be executed. Invert the condition.
Use a counter and check for values greater than 1
from collections import Counter
def sort_repeated(_list):
cntr = Counter(_list)
print sorted([x for x in cntr.keys() if cntr[x] > 1])
sort_repeated([7, 7, 1, 2, 3, 2, 1, 4, 3, 4, 6, 5])
>> [1, 2, 3, 4, 7]
sorry to repost (I've just joined stack overflow 30 mins ago).
I don't think I explained in my previous post of my function.
def GetExtendedKeyword(message, newkeyword):
while True:
difference = len(message) - len(newkeyword)
if difference > 0:
newkeyword.extend(newkeyword[:difference]
return newkeyword
elif difference <= 0:
return newkeyword
What I have are two lists, a message and keyword list. The program calculates the difference between them and if the keyword is shorter than the message list, the program will repeat the keywordlist by that difference.
For example the original keywordlist is [0,1,5,2,5] and the difference is 3, the end result should be [0,1,5,2,5,0,1,5]. The program doesn't like my code when it comes to longer keyword or message lists. Please help!
If the amount can be larger than the list length, you can do this:
def extend(lst, n):
nfull = n / len(lst) + 1
nrem = n % len(lst)
return lst*nfull+lst[:nrem]
lst = [0,1,5,4,2,9]
print extend(lst, 3)
# [0, 1, 5, 4, 2, 9, 0, 1, 5]
print extend(lst, 7)
# [0, 1, 5, 4, 2, 9, 0, 1, 5, 4, 2, 9, 0]
list.extend(L) Extend the list by appending all the items in the
given list; equivalent to a[len(a):] = L.
It's sentence from Python Documentation. I think it is the best place where you should looking for a help. Acording to documentation, your code should look like this:
listOne = [0,1,5,4,2,9]
listOne.extend(listOne[:n])
I wonder to help you.
Try it like this
l = [0, 1, 5, 4, 2, 9]
l.extend(l[:n]) #extend l with the first n elements of l
This only works for n < len(l) ...
Use the function print_even_values with an input of an integer list and prints each even number on the list. Calling print_even_values([2, 8, 1, 9, 0, 19, 24]) would produce this output in the shell window:
2
8
0
24
My approach is:
def print_even_numbers(n:list) -> list:
'''Return a list of even numbers given a list of integers'''
for x in list:
if x % 2 == 0:
return(x)
assert print_even_numbers([2, 4, 2, 4, 5, 6]) == [2, 4, 2, 4, 6]
assert print_even_numbers([4, 1, 3, 2, 5, 9]) == [4, 2]
, but there is an error. Also, how do I make my output similar to the question? (i.e.
[2, 4, 2, 4, 6]
vs.(separate line)
2
4
2
4
6
I think the problem is you are returning a number when it is even, instead of returning the list of even numbers. You should store a number when it is even and then return the list:
def print_even_numbers(number_list):
even_numbers = [] # define the empty list of even numbers
for number in number_list:
if number % 2 == 0: # check if number is even
even_numbers.append(number) # if it is, store it
return even_numbers # Last step returns the list of even numbers
Well also you can use longer version that looks like this:
def generate_evens():
result = []
for x in range(1, 50):
if x % 2 == 0:
result.append(x)
return result
print(generate_evens())
And you have a short one using this:
def generate_evens1():
return [x for x in range(1, 50) if x % 2 == 0]
print(generate_evens1())