python how to swap some numbers in a list - python

for example, I have a list[8,9,27,4,5,28,15,13,11,12]
I want to change the position between the numbers after 28 and the numbers before 27.
The output should be [15,13,11,12,27,4,5,28,8,9].
I tried to change it, use a,b=b,a , but it doesn't work, there always lost some numbers in the output.
if I only change the position between two numbers, a,b=b,a is working, but if I want to change two or more numbers, it is not working.
could anyone give me some hints plz?

x = [8,9,27,4,5,28,15,13,11,12]
y = x[6:] + x[2:6] + x[0:2]
>>> y
[15, 13, 11, 12, 27, 4, 5, 28, 8, 9]

You can use slicing:
lis = [8,9,27,4,5,28,15,13,11,12]
ind1 = lis.index(27)
ind2 = lis.index(28)
if ind1 < ind2:
lis = lis[ind2+1:] + lis[ind1:ind2+1] + lis[:ind1]
else:
#do something else
print lis
#[15, 13, 11, 12, 27, 4, 5, 28, 8, 9]

Related

Inserting a value to list according to a threshold value

I have list a = [1,2,3,6,8,12,13,18,33,23] and list b=[] that is empty. I need each value in list a compare with all the values in the list b by taking the difference of the new value from list a with all the contents of the list b. If the difference is grater than to the value of the threshold, it must insert to list b rather than skip to the next value in a, how can do that?
a =[1,2,3,6,8,12,13,18,33,23]
b=[]
b.append(a[0])
for index in range(len(a)):
for i in range(len(b)):
x = a[index] - b[i]
if x > 1:
b.append(a[index])
print("\nOutput list is")
for v in range(len(b)):
print(b[v])
The desired output is:
output = [1,6,8,12,18,33,23]
To further clarify, in first time the list b have the first item from list a. I need to check if the a[0]-b[0]>1, then insert the value of a[0] in b list, and next if a[1] - b[0]>1 then insert the a[1] in b list , and if [[a[2] -b[0] >1] and [a[2]-b[1] > 1]] then insert a[2] in b list and so on
Here is the probable solution to the stated problem though the output is not matching with your desired outcome. But sharing on the basis of how I understood the problem.
a = [1, 2, 3, 6, 8, 12, 13, 18, 33, 23]
b = []
b.append(a[0])
threshold = 1 # Set Threshold value
for index in range(len(a)):
difference = 0
for i in range(len(b)):
difference = abs(a[index] - b[i])
if difference > threshold:
continue # Keep comparing other values in list b
else:
break # No need for further comparison
if difference > threshold:
b.append(a[index])
print("\nOutput list is")
print(b)
Output is:
Output list is
[1, 3, 6, 8, 12, 18, 33]
Also, I notice that after swapping the last two elements (33 <-> 23 ) of the list a as below:
a = [1, 2, 3, 6, 8, 12, 13, 18, 23, 33]
and running the same code. the output was near to your desired output:
Output list is
[1, 3, 6, 8, 12, 18, 23, 33]
This problem is very interesting now as I put myself into more investigation. And I found it a very interesting. Let me explain. First consider the list a as a list of integer numbers starting from 1 to N. For example:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
and set the threshold to 1
threshold = 1 # Set Threshold value
Now, run the programme with threshold = 1 and you will get the output:
Output list is
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
and if you rerun with threshold = 2, you will get the following output:
threshold = 2
Output list is
[1, 4, 7, 10, 13, 16, 19]
Basically, this programme is basically generating a hopping series of integer numbers where hopping is set to the threshold value.
Interesting!!! Isn't it???

How to calculate median from 2 different lists in Python

I have two lists note = [6,8,10,13,14,17] Effective = [3,5,6,7,5,1] ,the first one represents grades, the second one the students in the class that got that grade. so 3 kids got a 6 and 1 got a 17. I want to calculate the mean and the median. for the mean I got:
note = [6,8,10,13,14,17]
Effective = [3,5,6,7,5,1]
products = [] for num1, num2 in zip(note, Effective):
products.append(num1 * num2)
print(sum(products)/(sum(Effective)))
My first question is, how do I turn both lists into a 3rd list:
(6,6,6,8,8,8,8,8,10,10,10,10,10,10,13,13,13,13,13,13,13,14,14,14,14,14,17)
in order to get the median.
Thanks,
Donka
Here's one approach iterating over Effective on an inner level to replicate each number as many times as specified in Effective, and taking the median using statistics.median:
from statistics import median
out = []
for i in range(len(note)):
for _ in range(Effective[i]):
out.append(note[i])
print(median(out))
# 10
To get your list you could do something like
total = []
for grade, freq in zip(note, Effective):
total += freq*[grade]
You can use np.repeat to get a list with the new values.
note = [6,8,10,13,14,17]
Effective = [3,5,6,7,5,1]
import numpy as np
new_list = np.repeat(note,Effective)
np.median(new_list),np.mean(new_list)
To achieve output like the third list that you expect you have to do something like that:
from statistics import median
note = [6,8,10,13,14,17]
Effective = [3,5,6,7,5,1]
newList = []
for index,value in enumerate(Effective):
for j in range(value):
newList.append(note[index])
print(newList)
print("Median is {}".format(median(newList)))
Output:
[6, 6, 6, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 17]
Median is 10
For computing the median I suggest you use statistics.median:
from statistics import median
note = [6, 8, 10, 13, 14, 17]
effective = [3, 5, 6, 7, 5, 1]
total = [n for n, e in zip(note, effective) for _ in range(e)]
result = median(total)
print(result)
Output
10
If you look at total (in the code above), you have:
[6, 6, 6, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 17]
A functional alternative, using repeat:
from statistics import median
from itertools import repeat
note = [6, 8, 10, 13, 14, 17]
effective = [3, 5, 6, 7, 5, 1]
total = [v for vs in map(repeat, note, effective) for v in vs]
result = median(total)
print(result)
note = [6,8,10,13,14,17]
effective = [3,5,6,7,5,1]
newlist=[]
for i in range(0,len(note)):
for j in range(effective[i]):
newlist.append(note[i])
print(newlist)

how to get list of numbers by adding or subtracting given 4 numbers in python

I am trying to get possible numbers from 1 to n, given 4 numbers. by adding or subbtracting 2 or more of the 4 numbers.
e.g. it goes into loop for numlist(1,2,3,16). Below is the code:
def numlist(a,b,c,d):
#user input of 4 numbers a,b,c,d
# assigning variables value of -1. This will be used to provide -1 or +1 or 0
p=-1
q=-1
r=-1
s=-1
count=0
myarray=[]
mysum=a+b+c+d #sum of given 4 numbers
for x in range(mysum):
while count<mysum:
if p<=1:
if q<=1:
if r <=1:
if s<=1:
n1=p*a+q*b+r*c+s*d #number to be generated by adding/subtracting
s=s+1
#print(n1)
if n1>0 and (n1 in myarray)==False:
#print(n1)
myarray.append(n1) #add to myarray if number is positive and not already present
myarray.sort() #sort myarray
count=count+1
if count==mysum:
break
else:
s=-1
r=r+1
else:
r=-1
q=q+1
else:
q=-1
p=p+1
else:
p=-1
print(len(myarray),'total')
print(myarray)
numlist(1,3,4,14)
outputs
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
but if numlist(1,3,4,19)
it keeps running without ending in output of array. only shows total.
where am I going wrong ?
I think you should rethink your algorithm. Consider this:
from itertools import combinations
def numlist(lst):
lst = lst + [-i for i in lst]
result = set()
for i in range(2, 5):
result.update(sum(k) for k in combinations(lst, i))
return sorted(i for i in result if i > 0)
numlist([1, 3, 4, 19])
# [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
I did a little patch-up work, and found the high-level problem with your logic.
Your code goes into an infinite loop when the current value of count cannot be formed with the input values. Your logic fails to increment count until it finds a way to create that value. You spin through one combination after another of coefficients.
for x in range(mysum):
print ("top of loop; x =", x)
while count<mysum:
print("count", count, "\tmysum", mysum, "\tcoeffs", p, q, r, s)
if p<=1:
...

How do you enter numbers into a list without any being repeated?

I am trying to make a list with the numbers 1-24 all in it in a random order, why doesn't this work?
full_list = []
x = 0
while x < 25 :
n = randint (1,24)
while n in full_list:
n = randint (1,24)
full_list.append(n)
x = x + 1
random has a shuffle function that would make more sense for this task:
ar = list(range(1,25))
random.shuffle(ar)
ar
> [20, 14, 2, 11, 15, 10, 3, 4, 16, 23, 13, 19, 5, 21, 8, 7, 17, 9, 6, 12, 22, 18, 1, 24]
Also, your solution doesn't work because while x < 25 needs to be while x < 24. It is in an infinite loop when x = 24 (since randint(1,24) will never generate a new number not in the list).

Python: How to range() multiple values from list or dictionary?

Im new to programming. Trying to range numbers - For example if i want to range more than one range, 1..10 20...30 50...100. Where i need to store them(list or dictionary) and how to use them one by one?
example = range(1,10)
exaple2 = range(20,30)
for b in example:
print b
or you can use yield from (python 3.5)
def ranger():
yield from range(1, 10)
yield from range(20, 30)
yield from range(50, 100)
for x in ranger():
print(x)
The range function returns a list. If you want a list of multiple ranges, you need to concatenate these lists. For example:
range(1, 5) + range(11, 15)
returns [1, 2, 3, 4, 11, 12, 13, 14]
Range module helps you to get numbers between the given input.
Syntax:
range(x) - returns list starting from 0 to x-1
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
range(x,y) - returns list starting from x to y-1
>>> range(10,20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
range(x,y,stepsize) - returns list starting from x to y-1 with stepsize
>>> range(10,20,2)
[10, 12, 14, 16, 18]
>>>
In Python3.x you can do:
output = [*range(1, 10), *range(20, 30)]
or using itertools.chain function:
from itertools import chain
data = [range(1, 10), range(20, 30)]
output = [*chain(*data)]
or using chain.from_iterable function
from itertools import chain
data = [range(1, 10), range(20, 30)]
output = [*chain.from_iterable(data)]
output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

Categories