Problem with multiidimentional input to loop and list - python-3.x

First time asking in the forum.
I have a problem.
I have to loop thru a vertical list like this.
1
2
3
4
5
6
7
8
9
10
11
Each separated by enter key, not by space. And then reorganize each item/number descending.
For the descending organization i already know it can be sorted or sorted reverse. But for all I have tried I cannot loop thru all the items in the vertical list.
It only reads 1 and ends the cycle which I understand it is only reading the first list but I just do not know how to loop thru vertical lists be it 1 single value or a matrix.
This is my code
from pip._vendor.distlib.compat import raw_input
numbers = raw_input()
line = []
for row in numbers:
line.append(row)
print(line)
line.sort(reverse=True)
for value in line:
print(value)
input:
1
2
3
4
5
6
7
8
9
10
11
Once again each separated by enter key, not by space
output:
['1']
Thanks in advance for your support.

Related

Csv file split comma separated values into separate rows and dividing the corresponding dollar amount by the number of comma separated values in panda

beginner here!
I have a csv file with comma separated values. I want to split each comma separated value in different rows in pandas. However, the corresponding dollar amounts should be divided by the number of comma separated values in each cell and export the result in a different csv file.
the csv table and the desired output table
I have used df.explode(IDs) but couldn’t figure out how to divide the Dollar_Amount by the number of IDs in the corresponding cells.
import pandas as pd
in_csv = pd.read_csv(‘inputCSV.csv’)
new_csv = df.explode(‘IDs’)
new_csv.to_csv(‘outputCSV.csv’)
You can divide the dollar amount by the number of ids in each row before using explode. This can be done as follows:
# Preprocessing
df['Dollar_Amount'] = df['Dollar_Amount'].str[1:].str.replace(',', '').astype(float)
df['IDs'] = df['IDs'].str.split(",")
# Compute the new dollar amount and explode
df['Dollar_Amount'] = df['Dollar_Amount'] / df['IDs'].str.len()
df = df.explode('IDs')
# Postprocessing
df['Dollar_Amount'] = df['Dollar_Amount'].round(2).apply(lambda x: '${0:,.2f}'.format(x))
With an example input:
IDs Dollar_Amount A
0 1,2,3,4 $100,000.00 4
1 5,6,7 $50,000.00 3
2 9 $20,000.00 1
3 10,11 $20,000.00 2
The result is as follows:
IDs Dollar_Amount A
0 1 $25,000.00 4
0 2 $25,000.00 4
0 3 $25,000.00 4
0 4 $25,000.00 4
1 5 $16,666.67 3
1 6 $16,666.67 3
1 7 $16,666.67 3
2 9 $20,000.00 1
3 10 $10,000.00 2
3 11 $10,000.00 2
There will be a one line way to do this with a lambda function (if you are new, read up on lambda functions!) but as a slightly less new beginner, I think its easier to think about this as two separate operations.
Operation 1 - get the count of ids, Operation 2 - do the division
If you take a look here https://towardsdatascience.com/count-occurrences-of-a-value-pandas-e5dad02303e9 you'll get a good lesson on how to do the group by you need to get the count of ids and join it back to your data frame. I'd read that because its a much more detailed explainer, but if you want a simple line of code consider this Pandas, how to count the occurance within grouped dataframe and create new column?
Once you have it, the divison is as simple as df['new_col'] = df['col1']/df['col2']

Alternative to Unique(Filter)

I have a dataset (single column) with repeating numbers. One number can repeat consecutively for 10 rows then switch to another number that repeats for 26 rows and may even go back to a previous number and repeat for another 30 rows. I used the cell code =UNIQUE(FILTER(L:L, L:L<>"")) but this does not capture non-unique repetition. I want to get the sequence of numbers that captures the number every time the repetition changes.
Dataset
10
10
10
10
4
4
4
4
9
9
9
4
4
4
Desired
10
4
9
4
use:
=LET(rng,A1:A14,rang2,A2:A15,FILTER(rang2,rang2<>rng))
or, if you do not mind the volatile function OFFSET:
=LET(rang2,A2:A15,rng,OFFSET(rang2,-1,0),FILTER(rang2,rang2<>rng))

Excel Sequential Numbering Based On Cell Value

I need to generate a sequential number in col C based on the value in col B. The number needs to follow the text System and each time the sequence number in col B resets, I need the numbering to reset but start at the next nearest base number, as shown below
Example data...
A ¦ B ¦ C
1 1 End Item
2 2 System10
3 3 System11
4 3 System12
5 2 System20
6 3 System21
7 3 System22
8 2 System30
9 3 System31
I have tried the following formula =IF(B1=B2, "System" & C1+1, "System" & 1)
However this doesn't give me the numbers starting at 10.
Any help would be greatly appreciated.
As a first cut at this, you could try:
=IF(C1="End Item","System10",IF(B2>=B1,"System"&RIGHT(C1,LEN(C1)-6)+1,"System"&ROUNDUP(RIGHT(C1,LEN(C1)-6),-1)))
This does allow for numbers of more than two digits, but doesn't increase to the next multiple of ten if the current number is an exact multiple of ten.
One way of getting round this would be to add a small increment:
=IF(C1="End Item","System10",IF(B2>=B1,"System"&RIGHT(C1,LEN(C1)-6)+1,"System"&ROUNDUP(RIGHT(C1,LEN(C1)-6)+0.1,-1)))

Alternate between printing two series of numbers

Input format: The first line of input consists of the number of test cases, T
Next T lines consist of the value of N.
Constraints: 1<= T <=100, 1<= N <= 250
Output format: For each test case, print the space-separated N terms of the series in a separate line.
Sample test case 1
Input:
1
7
Output:
1 1 2 2 4 2 6
The series is a combination of 2 series, the 1st series: 1,2,4,6,... and the 2nd series: 1,2,2,.... I have made the code for the first series but cannot find how to code the 2nd one.
Code for the first series appended into list depending on the no of elements
def firstS:
l=[1]
i=1
x=math.ceil(7/2)
while(x!=0):
l.append(i+i)
i+=1
x-=1
return l
The problem is the no of elements, for 7 elements the 1st series has 4 and 2nd series has 3 elements, for 8 elements 1st has 4 and 2nd has 4 elements and for 9 elements 1st has 5 and 2nd has 4 elements so the no of elements will be for series 1 math.ceil(n/2) and for series 2 math.floor(n/2) where n is total elements of the combined series.
For iteration, one way do something every N iterations is to use the modulus operator (%). Modulus is basically a remainder operator, so the result periodically repeats as numbers are iterated one-by-one.
Also, in Python, the standard method for doing a for-loop (iterating a certain number of times) is using range.
Here's an example demonstrating both, where every third number has the same number of exclamation marks:
# List the numbers 0-9 (repeat ten times)
for i in range(0, 10):
if i % 3 == 0:
print(i, "!")
elif i % 3 == 1:
print(i, "!!")
else:
print(i, "!!!")
Result:
0 !
1 !!
2 !!!
3 !
4 !!
5 !!!
6 !
7 !!
8 !!!
9 !
I'll leave it as an exercise for the asker to determine how to apply this to their use-case of switching between printing two different sequences.

Dictionary that has lists in keys, how to print so that the KEY with the least values in the list gets printed first?

So I have tried to do this extensively but to no avail.. I'm writting a program that takes a dictionary of names that have a list to them, and a numerical value of the amount of things in the list. I want to print each name in the list so that the first name that gets printed is the one with the least amount of values in the list, and the last name printed is the one with the most amount of values in the list.. here is my code. IT ONLY prints the name which is the key and then the whole list of values. and then it prints e which is the end. so
"anna"
3
4
5
6
e
"dan"
3
4
6
e
"cilla"
3
4
e
"billy"
6
e
...and so on
for GPS in GNR:
print('"'+GPS+'"')
for s in GNR[GPS]:
print(s)
print("e")
and here is the dictionary with its values.
GNR = {"anna":[3,4,5,6],"billy":[6],"cilla":[3,4],"dan":[3,4,6]}
So the result I would like is not the above but this:
"billy"
6
e
"cilla"
3
4
e
"dan"
3
4
6
e
"anna"
3
4
5
6
e
as you see it prints the name with the least values in its list first followed by the rest.
I'm clueless how to do this :( I know i need to compare each value to the rest and then save it somewhere but I dont know where. Any help will be appriciated :)
To get the keys ordered by number of elements in the corresponding list, you could do:
ascending = sorted(GNR, key=lambda x: len(GNR[x]))
# ascending is ['billy', 'cilla', 'dan', 'anna']
for key in ascending:
li = GNR[key]
# print them etc.

Resources