List issue in python : how to except one value before product of remaining all - list-comprehension

I have a list of items. I want to replace first item with product of remaining items of list except first. Do the same for remaining all. How can i do that?
lst = [2,3,5,4,7]
Output should be :
New_lst = [420,280,168,210,120]

First get the product:
>>> import math
>>> p = math.prod([2,3,5,4,7])
>>> p
840
Then divide all numbers by the product:
>>> lst = [2,3,5,4,7]
>>> New_lst = [p//i for i in lst]
>>> New_lst
[420, 280, 168, 210, 120]

Related

I have a double nested list. I would like to remove the second element inside of the nested list. i.e. [[[x,1],[x,2],[x,3]],[[x,1],[x,2],[x,3]]]

for x in y:
[z.pop(0) for z in x]
IndexError: pop index out of range.
The function seems to keep looping after it has gone through all the values of x. I would like to move on the next value of x after it has done it has completed its work. I understand that the error is occurring due to the changing of my data shape, but how do I avoid this?
First solution:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
for lst in nested_list:
for j in lst:
j.pop(1)
print(nested_list)
The above solution will give you the following output:
[[[11], [20], [300]], [[100], [202], [303]]]
Second Solution
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
result = []
for lst in nested_list:
for j in lst:
result.append(j[0])
print(result)
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]
If you are familiar with python then you can also go with the following:
nested_list = [[[11,1],[20,2],[300,3]],[[100,1],[202,2],[303,3]]]
def return_first(lst):
return [j[0] for i in lst for j in i]
print(return_first(nested_list))
del nested_list
The above solution will give you the following output:
[11, 20, 300, 100, 202, 303]

Task : Find unique elements in an array. Count their occurrences. Find the numbers that occur less than 10 times in an array of 5000 elements

I tried a few solutions :
1.)
uniqueValues, indexList,occurCount = np.unique(desired_array,
return_index=True, return_counts=True)
print(uniqueValues,indexList,occurCount)
However the indexList only gives first occurrence of a number. For example : if num 33 occurred at 20,56,3000, indexList would only show that it occurred at 20. Since 33 occurs less than 10 times, i.e 3 times, I need all the locations.
2.) I decided to use dictionary to find all the index locations. But this is not working.
for i in range(5000):
...: if not d.get(i):
...: d[desired_array[i]]=[i]
...: else:
...: indices = d[desired_array[i]]
...: indices.append(i)
This jobs screams for collections.Counter:
from collections import Counter
desired_array = [1, 2, 3, 1, 3, 5, 3]
result = Counter(desired_array)
print(result)
This will print out the unique elements and the count of occurrences:
Counter({3: 3, 1: 2, 2: 1, 5: 1})
You can replace
for i in range(1250):
var = desired_array[i]
if not d.get(var):
d[var] = []
# print(var)
s = d[var]
s.append(i)
with
for i in range(1250):
var = desired_array[i]
d.setdefault(var, []).append(i)
According to the documentation dict.setdefault(key, default):
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
To write a csv file it's best to use the standard csv.Writer class:
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
If you want to write the key/value pairs of your dict to the csv file you need to write something like:
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
for k, v in desired_array.items():
writer.writerow((k, v))

Reading input as dictionary in python

Im trying to read input spread across multiline in form of dictionary and apply simple math operations on the value of dictionary . My code reads
d ={}
bal=0
text = input().split(",") #split the input text based on line'text'
print(text)
for i in range(5):
text1 = text[i].split(" ") #split the input text based on space & store in the list 'text1'
d[text1[0]] = int(text1[1]) #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
for key in d:
if key=='D':
bal=bal+int(d[key])
#print(d[key])
elif key=='W':
bal=bal-int(d[key])
print(bal)
Input : W 300,W 200,D 100,D 400,D 600
output :{'D': 600, 'W': 200}
400
Expected Output: {'W':300,'W':200,'D':100,'D':400,'D':600}
600
ISSUE: The issue here is the code always reads 2 and last values only . For example in the above case output is
{'D': 600, 'W': 200}
400
Can someone let me know the issue with for loop .
Thanks in advance
You can try like this in a simpler way using your own approach. #Rakesh and #Sabesh suggested good. Dictionary is an unordered collection with unique and immutable keys. You can easily check this on your Python interactive console by executing help(dict).
You can check https://docs.python.org/2/library/collections.html#collections.defaultdict . Here you'll find number of examples on how to efficiently using dictionary.
>>> d = {}
>>> text = 'W 300,W 200,D 100,D 400,D 600'
>>>
>>> for item in text.split(","):
... arr = item.split()
... d.setdefault(arr[0], []).append(arr[1])
...
>>> d
{'W': ['300', '200'], 'D': ['100', '400', '600']}
>>>
>>> w = [int(n) for n in d['W']]
>>> d = [int(n) for n in d['D']]
>>>
>>> bal = sum(d) - sum(w)
>>> bal
600
>>>

Python: Use a for loop to get Nth number out of a list

I need to get every 3rd value out of a list and add it to a new list.
This is what I have so far.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(count)
return skipped_list
skip is equal to 3
I get the indexes and not the value of the numbers in the list.
It gives me [0,3,6]. Which are the indexes in the list and not the value of the indexes.
The example I am given is:
In this list [12,87,234,34,98,11,9,72], you should get [12,34,9].
I cannot use skipped_list = original_samples[::3] in any way.
You need to append the value of the original_samples array at the index. Not the index (count) itself.
def make_reduced_samples(original_samples, skip):
skipped_list = []
for count in range(0, len(original_samples), skip):
skipped_list.append(original_samples[count])
return skipped_list
The correct, most pythonic, and most efficient way to do that is to use slicing.
lst = [12, 87, 234, 34, 98, 11, 9, 72]
skipped_list = lst[::3]
print(skipped_list) # [12, 34, 9]
If the step does not obey a linear relation (which it does here), then you could use a list-comprehension with enumerate to filter on the index.
skipped_list = [x for i, x in enumerate(lst) if i % 3 == 0]
print(skipped_list) # [12, 34, 9]
One liner:
skipped_list = [j for (i,j) in enumerate(original_samples, start=1) if i % 3 == 0]

How to insert a String as Integer to a List in Python

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]
Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.
Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful
You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Resources