Python float print in real time - python

Is there any way to print the numbers in real times instead of printing them one by one? I have 6 different countries
china = 1399746872
india = 1368138206
USA = 327826334
Japan = 12649000
Russia = 146804372
Sweden = 10379295
I change this numbers in the script but how do I print them so I see them change?
!EDITED!
I want to kind of overwrite this list everytime it prints so I see the numbers go up
Countries = []
china = 1399746872
india = 1368138206
USA = 327826334
Japan = 12649000
Russia = 146804372
Sweden = 10379295
Countries.append(china)
Countries.append(india)
Countries.append(USA)
Countries.append(Japan)
Countries.append(Russia)
Countries.append(Sweden)
print(Countries)

you could use os.system("cls") to clear the console.
I made a little demo:
import time, sys, json, os
from random import randint
vals = {
"china": 1399746872,
"india": 1368138206,
"USA": 327826334,
"Japan": 12649000,
"Russia": 146804372,
"Sweden": 10379295
}
for _ in range(100):
# clear console
os.system("cls")
# print values
[print(f"{k}: {v}") for k, v in vals.items()]
# renew values with random generated integers
vals = {k:randint(0, 1000000) for k in vals}
# sleep 5s
time.sleep(5)

Related

Define a function to a dataframe

Consider this code in Python
filter_2020 = hdb_million[hdb_million["year"]==2020]
town_2020 = filter_2020["town"].unique()
results_2020 = len(town_2020)
print(town_2020)
print("in 2020 the number of towns are:", results_2020)
print("\n")
filter_2021 = hdb_million[hdb_million["year"]==2021]
town_2021 = filter_2021["town"].unique()
results_2021 = len(town_2021)
print(town_2021)
print("in 2021 the number of towns are:", results_2021)
print("\n")
filter_2022 = hdb_million[hdb_million["year"]==2022]
town_2022 = filter_2022["town"].unique()
results_2022 = len(town_2022)
print(town_2022)
Output
['BUKIT MERAH' 'CLEMENTI' 'TOA PAYOH' 'KALLANG/WHAMPOA' 'QUEENSTOWN'
'BISHAN' 'CENTRAL AREA' 'ANG MO KIO' 'GEYLANG']
in 2020 the number of towns are: 9
['BISHAN' 'BUKIT MERAH' 'CENTRAL AREA' 'CLEMENTI' 'QUEENSTOWN' 'SERANGOON'
'TOA PAYOH' 'BUKIT TIMAH' 'KALLANG/WHAMPOA' 'ANG MO KIO']
in 2021 the number of towns are: 10
['ANG MO KIO' 'BISHAN' 'BUKIT TIMAH' 'CENTRAL AREA' 'CLEMENTI' 'GEYLANG'
'KALLANG/WHAMPOA' 'QUEENSTOWN' 'SERANGOON' 'TOA PAYOH' 'BUKIT MERAH'
'YISHUN' 'PASIR RIS' 'WOODLANDS' 'BUKIT BATOK' 'HOUGANG' 'MARINE PARADE'
'PUNGGOL' 'TAMPINES' 'BEDOK']
in 2022 the number of towns are: 20
Instead of repeating the codes, can I define a function to arrive at the same output ? I tried several def functions but am not successful. Most grateful for any insights. thank you
You can iterate through a loop,
for year in [2020, 2021, 2022]:
filter_year = hdb_million[hdb_million["year"]== year]
town = filter_year["town"].unique()
results = len(town)
print(town)
print(f"in {year} the number of towns are:", results)
print("\n")
If you just want the print things to be repeated using a function.
def print_town_info(year, town_input):
filter_year = town_input[town_input["year"] == year]
town = filter_year["town"].unique()
print(town)
print("in " + str(year) + " the number of towns are:", len(town))
print("\n")
Then if you want it in a loop:
for y in [2020, 2021, 2022]:
print_town_info(y, hdb_million)

How To Add Specific Keys In Nested Dictionary In Python

I may be formatting this dictionary wrong (my first time doing this)
I have a dictionary of every province with corrected ID and added it to value "Canada". I'm trying to add the population of ALL the provinces in the nested dictionary
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {ontario, quebec, nova_Scotia, new_brunswick, manitoba, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador}
for key, value in canada.items():
if value and 'population' in value.keys():
# Adding all values of population to receive total population of canada
sum += value['population']
print(sum)
thanks again in advance.
You didn't create dictionary but set (which doesn't have keys)
To create dictionary you would need keys like
canada = {1:ontario, 2:quebec, 3:nova_scotia, 4:new_brunswick, 5:manitoba}
canada = {"Ontario":ontario, "Quebec":quebec, "Nova Scotia":nova_scotia, "New Brunswick":new_brunswick, "Manitoba":manitoba}
and then you can use canada.items() and sum population
(I use variable total because there is function sum())
# --- before `for`-loop ---
total = 0
# --- `for`-loop ---
for key, value in canada.items():
total += value['population']
# --- after `for`-loop ---
print(total)
or shorter
total = sum(value['population'] for value in canada.values())
and then you can add to this dictionary
canada['total'] = total
Full code:
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {1:ontario, 2:quebec, 3:nova_scotia, 4:new_brunswick, 5:manitoba}#, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador
total = 0
for key, value in canada.items():
total += value['population']
print(total)
#total = sum(value['population'] for value in canada.values())
canada['total'] = total
print(canada)
I only added the listed 5 provinces into the nested dictionary.
I used a for loop to calculate the total population of Canada (the
sum of the 5 listed provinces).
Note that my nested dictionary has the same format as a normal dictionary,
"a key : value" --> "1 : ontario"
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada = {1:ontario, 2:quebec, 3:nova_Scotia, 4:new_Brunswick, 5:manitoba}
#canada = {ontario, quebec, nova_Scotia, new_brunswick, manitoba, british_columbia, prince_edward_island, saskatchewan, alberta, newfoundland_and_labrador}
sum = 0
for providence in canada:
# Adding all values of population to receive total population of canada
sum += (canada[providence]["population"])
print(sum)
Try this one.
ontario = dict(capital="Toronto", largest="Toronto", population=14826276)
quebec = dict(capital="Quebec City", largest="Montreal", population=8604495)
nova_Scotia = dict(capital="Halifax", largest='Halifax', population=992055)
new_Brunswick = dict(capital="Fredricton", largest='Moncton', population=789225)
manitoba = dict(capital="Winnipeg", largest="Winnipeg", population=1383765)
canada_list = [ontario, quebec, nova_Scotia, new_Brunswick, manitoba]
total = 0
for item in canada_list:
# Adding all values of population to receive total population of canada
total += item.get('population', 0)
print("Total: {}".format(total))
Output:
Total: 26595816

cascading dropdown shows dictionary/array - Python (Jupyter Notebook)

I am trying to create a series of dropdown menus on Jupyter Notebook.
The first few dropdown lists work fine, but it starts to go wonky on the last one, with the output being read as a string instead of a dictionary
Code as follows:
#Initialise GUI
from ipywidgets import interact,Dropdown
import ipywidgets as widgets
#Initialise Dictionaries
NAICSd = {"21-Mining,Quarrying,and oil and gas extraction(8)":0.08,
"11-Agriculture,forestry,fishing and hunting(9)":0.09,
"55-Management of companies and enterprises(10)":0.08,
"62-Healthcare and social assistance(10)":0.1,
"22-Utilities(14)":0.14,
"92-Public Administration(15)":0.15,
"54-Professional,scientific and technical services(19)":0.19,
"42-Wholesale trade(19)":0.19,
"31-Manufacturing(19)":0.19,
"32-Manufacturing(16)":0.16,
"33-Manufacturing(14)":0.14,
"81-Other Sevices Exept Public Administration(20)":0.2,
"71-Arts,Entertainment and Recreation(21)":0.21,
"72-Accommodation and Food Services(22)":0.22,
"44-Retail Trade(22)":0.22,
"45-Retail Trade(23)":0.23,
"23-Construction(23)":0.23,
"56-Administrative/Support & Waste Management/Remediation Service(24)":0.24,
"61-Educational Services(24)":0.24,
"51-Information (25)":0.25,
"48-Transportation and warehousing(27)":0.27,
"49-Transportation and warehousing(23)":0.23,
"52-Finance and Insurance(28)":0.28,
"53-Real Estate and rental and leasing(29)":0.29}
Stated = {"Undefined(28)":0.28,
"Alaska(10)":0.1,
"Alabama(18)":0.18,
"Arkansas(18)":0.18,
"Arizona(20)":0.2,
"California(20)":0.2,
"Colorado(18)":0.18,
"Connecticut(13)":0.13,
"D.C.(8)":0.08,
"Delaware(18)":0.18,
"Florida(28)":0.28,
"Georgia(27)":0.27,
"Hawaii(16)":0.16,
"Iowa(13)":0.13,
"Idaho(15)":0.15,
"Illonois(23)":0.23,
"Indiana(18)":0.18,
"Kansas(13)":0.13,
"Kentucy(20)":0.20,
"Louisiana(18)":0.18,
"Massachusetts(15)":0.15,
"Maryland(20)":0.20,
"Maine(9)":0.09,
"Michigan(23)":0.23,
"Minnesota(13)":0.13,
"Missouri(15)":0.15,
"Missisipi(15)":0.15,
"Montana(8)":0.08,
"North Carolina(20)":0.2,
"North Dakota(8)":0.08,
"Nebraska(15)":0.15,
"New Hampshire(10)":0.1,
"New Jersey(20)":0.2,
"New Mexico(10)":0.1,
"Nevada(23)":0.23,
"New York(20)":0.2,
"Ohio(18)":0.18,
"Oklahoma(13)":0.13,
"Oregon(17)":0.17,
"Pennsylvania(15)":0.15,
"Rhode Island(8)":0.08,
"South Carolina(20)":0.2,
"South Dakota(8)":0.08,
"Tennesee(23)":0.23,
"Texas(20)":0.2,
"Utah(18)":0.18,
"Virginia(19)":0.19,
"Vermont(8)":0.08,
"Washington(13)":0.13,
"Wisconsin(15)":0.15,
"West Virginia(15)":0.15,
"Wyoming(8)":0.18
}
Businessd = {"New Business <2 years(18.98)":0.1898,
"Normal Business >= 2 years (17.36)":0.1736}
BackedRealEstated = {"Yes(1.64)":0.0164,
"No(21.16)":0.2116}
IsRecessiond ={"Yes(32.21)":0.3221,
"No(16.63)":0.1663}
SBARatiod = {"More than 50%(25)":0.25,
"50% or less(40)":0.4}
NAICSList = Dropdown(options = NAICSd)
StateList = Dropdown(options = Stated)
BusinessList = Dropdown(options = Businessd)
BackedRealEstateList = Dropdown(options = BackedRealEstated)
IsRecessionList = Dropdown(options = IsRecessiond)
SBARatioList = Dropdown(option = SBARatiod)
#interact(Sector = NAICSList, US_State=StateList, New_Business=BusinessList, Real_Estate_Backed=BackedRealEstateList,
Recession = IsRecessionList, Guarantee_Ratio = SBARatioList)
def print_dropdown(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio):
NAICSList.options = NAICSd
StateList.options = Stated
BusinessList = Businessd
BackedRealEstateList = BackedRealEstated
IsRecessionList = IsRecessiond
Guarantee_Ratio = SBARatiod
print(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio)
Sector, US_State, New_Business, Real_Estate_Backed and Recession all return a float, which is what I want. But Guarantee_Ratio returns '{'More than 50%(25)': 0.25, '50% or less(40)': 0.4}'
I saw my problem. I confused the Guarantee_Ratio variable with the list
def print_dropdown(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio):
NAICSList = NAICSd
StateList = Stated
BusinessList = Businessd
BackedRealEstateList = BackedRealEstated
IsRecessionList = IsRecessiond
SBARatioList = SBARatiod
print(Sector, US_State, New_Business, Real_Estate_Backed, Recession, Guarantee_Ratio)]

Determining most common name from web scraped birth name data

I have the task to do web scraping from this page https://www.ssa.gov/cgi-bin/popularnames.cgi. There you can find a list of the most common birth names. Now I have to find the most common name that both girls and boys have for a given year (in other words, the exact same name is used in both genders), but I don't know how I am able to do that. With the code below I solved the previous task to output the list for a given year but I have no clue how I can modify my code so I get the most common name that both girls and boys have.
import requests
import lxml.html as lh
url = 'https://www.ssa.gov/cgi-bin/popularnames.cgi'
string = input("Year: ")
r = requests.post(url, data=dict(year=string, top="1000", number="n" ))
doc = lh.fromstring(r.content)
tr_elements = doc.xpath('//table[2]//td[2]//tr')
cols = []
for col in tr_elements[0]:
name = col.text_content()
number = col.text_content()
cols.append((number, []))
count=0
for row in tr_elements[1:]:
i = 0
for col in row:
val = col.text_content()
cols[i][1].append(val)
i += 1
if(count<4):
print(val, end = ' ')
count += 1
else:
count=0
print(val)
Here's one approach. The first step is to group the data by name and record how many genders have used the name and their aggregate total. After that, we can filter the structure by names with more than one gender using it. Finally, we sort this multi-gender list by counts and take the 0-th element. This is our most popular multi-gender name for the year.
import requests
import lxml.html as lh
url = "https://www.ssa.gov/cgi-bin/popularnames.cgi"
year = input("Year: ")
response = requests.post(url, data=dict(year=year, top="1000", number="n"))
doc = lh.fromstring(response.content)
tr_elements = doc.xpath("//table[2]//td[2]//tr")
column_names = [col.text_content() for col in tr_elements[0]]
names = {}
most_common_shared_names_by_year = {}
for row in tr_elements[1:-1]:
row = [cell.text_content() for cell in row]
for i, gender in ((1, "male"), (3, "female")):
if row[i] not in names:
names[row[i]] = {"count": 0, "genders": set()}
names[row[i]]["count"] += int(row[i+1].replace(",", ""))
names[row[i]]["genders"].add(gender)
shared_names = [
(name, data) for name, data in names.items() if len(data["genders"]) > 1
]
most_common_shared_names = sorted(shared_names, key=lambda x: -x[1]["count"])
print("%s => %s" % most_common_shared_names[0])
If you're curious, here are the results since 2000:
2000 => Tyler, 22187
2001 => Tyler, 19842
2002 => Tyler, 18788
2003 => Ryan, 20171
2004 => Madison, 20829
2005 => Ryan, 18661
2006 => Ryan, 17116
2007 => Jayden, 17287
2008 => Jayden, 19040
2009 => Jayden, 19053
2010 => Jayden, 18641
2011 => Jayden, 18064
2012 => Jayden, 16952
2013 => Jayden, 15462
2014 => Logan, 14478
2015 => Logan, 13753
2016 => Logan, 12099
2017 => Logan, 15117

python Queue multithreading

What is the simplest way to have only two trains(in the same time) on the railroad. My english is bad. this is only way how I can explain it. I know I should use Queue? I can't find info in my language
Thank you!
1>go, 2>go. 3,4wait. 1>finish, 3>go (4th still wait) ..
from threading import Thread
import time
import random
def trains(city):
print city, 'start'
for count in range(1,3):
delay = random.randrange(5,10)
print city, 'delay', delay
time.sleep(delay)
print city, 'end'
cities = ['prague', 'london', 'berlin', 'moscow']
threadlist = []
for city in cities:
t = Thread(target=trains, args=(city,))
t.start()
threadlist.append(t)
for b in threadlist:
b.join()
I'm going to guess at some things here:
from threading import Thread, Lock, BoundedSemaphore
import time
import random
def trains(city):
with railroads:
with iolock:
print city, 'start'
for count in range(1,3):
delay = random.randrange(5,10)
with iolock:
print city, 'delay', delay
time.sleep(delay)
with iolock:
print city, 'end'
cities = ['prague', 'london', 'berlin', 'moscow']
threadlist = []
iolock = Lock()
railroads = BoundedSemaphore(2)
for city in cities:
t = Thread(target=trains, args=(city,))
t.start()
threadlist.append(t)
for b in threadlist:
b.join()
The purpose of iolock is to stop mixed-up output in your terminal: only 1 thread prints at a time. The purpose of railroads is to allow at most two threads to enter the body of the code simultaneously. Here's sample output. Note that "prague" and "london" happen to run at first, but "berlin" doesn't start before "london" ends. Then "moscow" doesn't start until "prague" ends:
prague start
london start
prague delay 8
london delay 5
london delay 6
prague delay 5
london end
berlin start
berlin delay 8
prague end
moscow start
moscow delay 8
berlin delay 6
moscow delay 7
berlin end
moscow end

Categories