'Check and add based of the first 4 digits of each element in a list in Python
I've been struggling with this for the last 3 hours. I need to make a code that, using only lists:
Takes the input of various IDs and turns them into lists. To do that I made this code:
def getID(): id = input("Enter the IDs separated by a space: ") idlist = id.split() print (get2015(idlist)) return ""
After getting the input, check from what year they are. The Ids have the following format (20(15-22)xxxxxx, for example, 2015123456, where the first four digits indicate on what year the person was born. Then, add how many people was born in that year. This is what I tried for the year 2015 but isn't working.
def get(id): sum= 0 for x in id[:3]: if x == "2015": sum+= 1 return sum
An example of the output I need would be:
Input:
2015000000, 2016000000, 2015000011
Output:
Born in 2015: 2
Born in 2016 : 1
How could I solve this? Thanks in advance.
Solution 1:[1]
The ideal solution would be to use a dictionary.
def getID():
id = input("Enter the IDs separated by a space: ")
idlist = id.split(", ") #In your input example you separate them by comma
for id in idlist:
addBirth(id[:4])
print(birthData)
birthData = {} #Create an empty dictionary
def addBirth(year):
#Check if key exists
if year in birthData:
birthData[year] += 1
else:
#If the key wasn't present create a new key and initialise it to 1
birthData[year] = 1
getID()
with the input 2015000000, 2016000000, 2015000011
outputs the following:
{'2015': 2, '2016': 1}
However, because you can't use dictionaries, you can use list indices.
startYear = 2015
endYear = 2022
yearCount = endYear - startYear
#Create a list with as many items as years, all initialised to 0
birthData = [0]*yearCount
def addBirth(year):
birthData[int(year) - startYear] += 1
With the same input, it outputs:
[2, 1, 0, 0, 0, 0, 0]
In order to print the data like you suggested (only for the list version):
def printBirthData(birthData):
#For each year in the year range (2015 - 2022)
for year in range(yearCount):
#Only if there has been at least 1 birth that year
if birthData[year] != 0:
#Using f strings format the year and the year's data
print(f"Born in {startYear + year}: {birthData[year]}")
Outputs:
Born in 2015: 2
Born in 2016: 1
Solution 2:[2]
Use Counter
here:
from collections import Counter
inp = ["2015000000", "2016000000", "2015000011"]
print(Counter([x[:4] for x in inp])) # Counter({'2015': 2, '2016': 1})
Solution 3:[3]
I'd set up a separate dictionary of years, loop over the entries in your list of IDs, and check if the first four digits in it correspond to a year in the dictionary. If yes, increase its value in the dictionary by one. If not, add it as a new key to the dictionary with value one:
years = dict()
for id in idlist:
year = id[:4]
if year in years.keys():
years[year] += 1
else:
years[year] = 1
Solution 4:[4]
Try this : the list years will store from 2015 to 2022 count.
example: years[0] is for 2015
fun getSum(idList):
years = [0,0,0,0,0,0,0,0]
for id in idList :
year = int(id[:4])
years[year-2015] += 1
return years
idList = ['201567899','202267868']
years = getSum(idList)
for i in range(len(years)):
print('Born in {} : {}'.format(i+2015,years[i]))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Tim Biegeleisen |
Solution 3 | Schnitte |
Solution 4 |