blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3b9f714e00d9359083cff5dc0d86080fb62a1197 | PR1MEC0DE/pe-acasa | /pe acasa.py | 315 | 3.71875 | 4 | x = 113
y = 76
z = 40
print("Introdu numarul de barbati la nunta")
x1 = int(input())
print("Introdu numarul de femei la nunta")
y1 = int(input())
print("Introdu numarul de copii la nunta")
z1 = int(input())
a = 455
c =((x1*x)+(y1*y)+(z1*z))
b = (c/1000)
d = (b//0.455)
print("La nunta este nevoie de", d, ("paini")) |
361523894d4c871c5609c979a0dcb0b496109fce | lc2019/pycode-sixmonth | /day6/6.私有属性.py | 621 | 3.796875 | 4 | class Account(object):
def __init__(self, name, balance):
# 私有属性
self.__name = name
self.__balance = balance
# get set
def get_name(self):
return self.__name
def set_money(self, new_b):
if isinstance(new_b,int):
self.__balance += new_b
else:
print('type error')
def get_money(self):
return self.__balance
def show_info(self):
print(self.__name + ' have', self.__balance)
account = Account('lc', 20)
account.show_info()
print(account.get_name())
account.set_money(100)
print(account.get_money()) |
13d95ab5bea89ff04dac0a8ea6ef07924ff3aa2c | ikostan/ProjectEuler | /Problems_1_to_100/Problem_19/tests/test_problem_19.py | 3,783 | 3.59375 | 4 | #!/usr/bin/python
import unittest
import os
from Problems_1_to_100.Problem_19.date import Date
from Problems_1_to_100.Problem_19.calendar import Calendar
from Problems_1_to_100.Problem_19.problem_19 import main
import utils.utils as utils
class MyTestCase(unittest.TestCase):
print("Running unit tests from: " + os.path.basename(__file__) + "\n")
@classmethod
def setUpClass(cls):
"""
Get all leap years from the text file
and organize them as an array
:return:
"""
cls.leap_years = []
file_path = utils.get_full_path('/Problems_1_to_100/Problem_19/tests',
'leap_years.txt')
with open(file_path) as source:
for line in source:
cls.leap_years.append(int(line.strip()))
def test_main_year_1904(self):
expected = 1
stop_date = Date(31,
'',
Calendar.month_name[11],
1904)
current_date = Date(1,
Calendar.week_days[4],
Calendar.month_name[0],
1904)
self.assertEqual(expected,
main(stop_date, current_date))
def test_main_year_1999(self):
expected = 1
stop_date = Date(31,
'',
Calendar.month_name[11],
1999)
current_date = Date(1,
Calendar.week_days[4],
Calendar.month_name[0],
1999)
self.assertEqual(expected,
main(stop_date, current_date))
def test_main_year_1998_1999(self):
expected = 4
stop_date = Date(31,
'',
Calendar.month_name[11],
1999)
current_date = Date(1,
Calendar.week_days[3],
Calendar.month_name[0],
1998)
self.assertEqual(expected,
main(stop_date, current_date))
def test_main(self):
expected = 171
stop_date = Date(31,
'',
Calendar.month_name[11],
2000)
current_date = Date(1,
Calendar.week_days[0],
Calendar.month_name[0],
1900)
self.assertEqual(expected,
main(stop_date, current_date))
def test_is_leap_true(self):
# A leap year occurs on any year evenly divisible by 4,
# but not on a century unless it is divisible by 400
results = []
for year in self.leap_years:
results.append(Calendar.is_leap(year))
self.assertEqual(True, all(results))
def test_is_leap_false(self):
# A leap year occurs on any year evenly divisible by 4,
# but not on a century unless it is divisible by 400
non_leap_years = [year for year in range(1800, 2400, 1)
if year not in self.leap_years]
results = []
for year in non_leap_years:
results.append(Calendar.is_leap(year))
self.assertEqual(False, all(results))
def test_date_set_week_error(self):
with self.assertRaises(ValueError):
Date.__set_week__('blabla')
def test_date_set_month_error(self):
with self.assertRaises(ValueError):
Date.__set_month__('blabla')
def test_date_set_year_error(self):
with self.assertRaises(ValueError):
Date.__set_year__(3000)
|
0686a91de9ef399018f033323a7cdf89a8650425 | narenaryan/ChessMoves | /main.py | 3,197 | 3.59375 | 4 | import argparse, json
chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)]
chess_map_from_alpha_to_index = {
"a" : 0,
"b" : 1,
"c" : 2,
"d" : 3,
"e" : 4,
"f" : 5,
"g" : 6,
"h" : 7
}
chess_map_from_index_to_alpha = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h"
}
def getRookMoves(pos, chessBoard):
column, row = list(pos.strip().lower())
row = int(row) - 1
column = chess_map_from_alpha_to_index[column]
i,j = row, column
solutionMoves = []
# Compute the moves in Rank
for j in xrange(8):
if j != column:
solutionMoves.append((row, j))
# Compute the moves in File
for i in xrange(8):
if i != row:
solutionMoves.append((i, column))
solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in solutionMoves]
solutionMoves.sort()
return solutionMoves
def getKnightMoves(pos, chessBoard):
""" A function that returns the all possible moves
of a knight stood on a given position
"""
column, row = list(pos.strip().lower())
row = int(row) - 1
column = chess_map_from_alpha_to_index[column]
i,j = row, column
solutionMoves = []
try:
temp = chessBoard[i + 1][j - 2]
solutionMoves.append([i + 1, j - 2])
except:
pass
try:
temp = chessBoard[i + 2][j - 1]
solutionMoves.append([i + 2, j - 1])
except:
pass
try:
temp = chessBoard[i + 2][j + 1]
solutionMoves.append([i + 2, j + 1])
except:
pass
try:
temp = chessBoard[i + 1][j + 2]
solutionMoves.append([i + 1, j + 2])
except:
pass
try:
temp = chessBoard[i - 1][j + 2]
solutionMoves.append([i - 1, j + 2])
except:
pass
try:
temp = chessBoard[i - 2][j + 1]
solutionMoves.append([i - 2, j + 1])
except:
pass
try:
temp = chessBoard[i - 2][j - 1]
solutionMoves.append([i - 2, j - 1])
except:
pass
try:
temp = chessBoard[i - 1][j - 2]
solutionMoves.append([i - 1, j - 2])
except:
pass
# Filter all negative values
temp = [i for i in solutionMoves if i[0] >=0 and i[1] >=0]
allPossibleMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp]
allPossibleMoves.sort()
return allPossibleMoves
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--piece", help="chess piece name: ex- rook, knight, pawn etc")
parser.add_argument("-l", "--location", help="chess notation string: ex- E4, D6 etc")
args = parser.parse_args()
piece = args.piece.strip().lower()
location = args.location.strip()
# According to the type of piece adjust function
if (piece == "rook"):
print json.dumps({"piece":piece,
"current_location": location,
"moves": getRookMoves(location, chessBoard)})
elif (piece == "knight"):
print json.dumps({"piece":piece,
"current_location": location,
"moves": getKnightMoves(location, chessBoard)})
|
a4a3a0a1e6b959e922d1bd75eae3cc5bdaf78d45 | Chao8219/practice-adventure | /object_read.py | 2,634 | 4.09375 | 4 | import sqlite3
def read_all_creature(file_path):
"""
Method to read all creature data in the creature_info table
Parameters
----------
file_path: string
The relative db file path
Returns
-------
all_creature_info: list
All creature list.
"""
try:
conn = sqlite3.connect(file_path)
cur = conn.cursor()
cur.execute('SELECT * FROM creature_info')
except sqlite3.OperationalError as err:
print(err)
print('It is possible that the provided file path is wrong.')
return None
all_creature_info = cur.fetchall()
conn.close()
print('Database read successfully')
return all_creature_info
def read_one_creature_by_name(file_path, creature_name):
"""
Method to read one creature data by the given creature name.
Parameters
----------
file_path: string
The relative db file path
creature_name: string
The string name that the code is trying to read.
Returns
-------
creature_data: tuple
The tuple that contains all info about this creature.
"""
try:
conn = sqlite3.connect(file_path)
cur = conn.cursor()
cur.execute('SELECT * FROM creature_info WHERE NAME=?',
(creature_name, ))
except sqlite3.OperationalError as err:
print(err)
print('It is possible that the provided file path is wrong.')
return None
creature_data = cur.fetchone()
conn.close()
if creature_data is None:
print('The creature name that is passed in does not' +
'exist in the db file')
return creature_data
def read_one_creature_by_id(file_path, creature_id):
"""
Method to read one creature data by the given creature name.
Parameters
----------
file_path: string
The relative db file path
creature_id: string
The string id that the code is trying to read.
Returns
-------
creature_data: tuple
The tuple that contains all info about this creature.
"""
try:
conn = sqlite3.connect(file_path)
cur = conn.cursor()
cur.execute('SELECT * FROM creature_info WHERE ID=?',
(creature_id, ))
except sqlite3.OperationalError as err:
print(err)
print('It is possible that the provided file path is wrong.')
return None
creature_data = cur.fetchone()
conn.close()
if creature_data is None:
print('The creature name that is passed in does not' +
'exist in the db file')
return creature_data |
c8df00706f8cac84664ff050b7bde827336e5d6f | waji9876/Python-learning | /python-basics.py | 4,038 | 4.125 | 4 |
#python is case sensitive language
print("Hello World!!")
name="ISHRA HUSSAIN"
roll_no=74543 #underscor can be used in varaiables names
print("PIAIC Artificial Intelligence Batch 3")
print("Name: ", name)
print("Roll No: ", roll_no)
age=23
print("Age is ", age)
marks=85
#it will recocgnize integers so we can use them for calculations
print("Marks: ", marks+5)
print(marks+age)
gpa=1+1
print("Multiple prints: ", gpa ,marks/2, age*2) #print multiple things seperated by comma
gpa+=1 #it is same as gpa=gpa+1
print(marks%gpa, gpa)
gpa*=1.29
print("GPA is:", gpa)
cost=1+3*4 #python works according to DMAS rule but we can also use parathesis
cost1=1+(3*4)
print("Same ", cost, cost1)
first_name="Ishra"
last_name="Hussain"
full_name=first_name+ " " + last_name #plus is used only for concatinating strings
print("My full name is ", full_name)
if name == "ISHRA":
print("My name is Ishra") #pressing tab is necessary for indenting
if 2*4==8:
print("It is correct")
print("Full Marks")
if gpa!=4: #not equal to
print("You are not topper")
if gpa<=3:
print("Work hard")
pet="Pupoo"
if pet=="Ponny":
print("pet name is ponny")
else:
print("My pet name is Pupoo :)")
if pet=="Ponny" :
print("My pet is rabbit")
elif pet=="Pupoo":
print("My pet is a cat")
if pet=="Pupoo" and gpa>3:
print("Its all good")
if name=="ISHRA" or gpa==4:
print("Welcome")
if (name=="ISHRA" or gpa==4) and pet=="Pupoo":
print("This is my home")
if pet=="Pupoo":
if name=="ISHRA":
print("This is nested loop")
elif gpa==4:
print("This is also nested loop")
else:
print("Leave it")
else:
print("Leave it")
#so this is how we can comment using hashes
''' i ca write here too
this is another way
of commenting multiple lines
wow thats good
and there too'''
#List is defined as:
books=["physics", "chemistry", "biology", "maths", "english", "urdu"] #start adress is 0 i.e. books[0]=physics
print("I want to study " + books[3])
#array can also have multiple types of variables
random_stuff=["toy", "computer", 45, "pakistan"]
print( "The number is ", random_stuff[2] )
books.append("Islamiyat") #to add more elements to list
print("Appended book: ", books[6])
random_stuff.append(1947)
books=books+ ["AI", "GIT"]
books.insert(3, "Electronic Devices") #add it to defined place and other elements move to next position
books[8]="Artificial Intelligence" #to update value we do this
print("Books:", books)
students=[] #can also add empty list and update later on
old_books=books[4:8] #for picking slices of list,the number after colon is index of element after the last elemtn of slice, hence is not picked
print("Old Books ", old_books)
some_books=books[:5] #picks from start 0 index
print("Some Books ", some_books)
last_books=books[5:] #picks from defuined index to the last element
print("Picked books", last_books)
#chapter 17 completed
del old_books[0] #to delete element at index 0, python adjusts indexes
print("Some old books deleted:", old_books)
del some_books[2] #2 deleted others index adjusted
print(some_books)
some_books.remove("chemistry") #delete using its value
print("Removed some books", some_books)
removed_books=books.pop(8) #,=move mentioned element to this variable, it is not list it is just a string variable
removed_books_list=[] #create a emmpty list
removed_books_list.append(removed_books) #append to add more elements to the list
removed_books=books.pop(2)
removed_books_list.append(removed_books)
#can also add elements directly to another list like this:
removed_books_list.insert(0, books.pop(1))
#to pop last element of list dont mention position
removed_books_list.insert(0,books.pop())
print("Popped books", removed_books_list)
print("Books now: ", books)
#tuples: list whose elements are fixed and cant be changed
#tuple brackets are round brackets
cities=("Lahore", "Islamabad", "Karachi", "Peshawar", "Quetta")
print("My city is ", cities[1]) |
bb7a2c9600bd77997d93750e2c86509229b82587 | raghunadraju/Practise | /List Elements.py | 556 | 3.953125 | 4 | Names = ["RAGHU", 'SRINI', '', 1, 'SHREYA', 'SURYA']
a = Names[0] # 0 means first object in the list
b = Names[1]
del Names[-1] # Delete string from list
c = Names[-1] # -1 means last object in the list
d = Names[-2]
print(a, b, c, d)
Names.append("SATISH") # Adding string to list
e = len(Names) # Finding number of elements in the list
print(e)
f = "HARI" in Names # Check the specified name exists in the list or not
g = int(f)
print(f, g)
h= Names[1:] # list slicing mean temporary ignoring the elements
i = Names[4:-1]
print(h)
print(i)
|
c42eb05d6f5c50b808287c2dc5fecdc8087049ce | yasinbrcn/PythonProjects | /Project_08 - Email Slicer/email_slicer.py | 1,785 | 3.96875 | 4 | '''
Coded By: Yasin BİRCAN
Date: 11.05.2021
'''
key=1
mail_list = []
username_list = []
domain_list = []
com_list = []
def listString(s):
string = ""
for n in s:
string += n
return string
def checkEmail(e):
j=1
for i in range(len(e)):
mail_list.insert(i,e[i:j])
j=j+1
try:
mail_list.index("@")!=0
check = 1
except:
mail_list.clear()
username_list.clear()
domain_list.clear
com_list.clear()
check = 0
return check
def checkCom():
com = ""
try:
for k in range(mail_list.index("@")):
username_list.append(mail_list[k])
for m in range(mail_list.index("@")+1,len(mail_list)):
domain_list.append(mail_list[m])
for n in range (domain_list.index("."),len(domain_list)):
com_list.append(domain_list[n])
com = str(listString(com_list))
except:
mail_list.clear()
username_list.clear()
domain_list.clear()
com_list.clear()
if com == ".com" and domain_list.index(".") != 0:
checkcom = 1
else:
mail_list.clear()
username_list.clear()
domain_list.clear()
com_list.clear()
checkcom = 0
return checkcom
while key == 1:
email = str(input("What is your email address?: "))
if checkEmail(email) == 1 and checkCom() == 1 and listString(username_list) != "":
key=0
else:
print("Invalid email address. Please enter a valid email address.")
mail_list.clear()
username_list.clear()
domain_list.clear()
com_list.clear()
key=1
print("Hello {}! Your domain adres: {}".format(listString(username_list),listString(domain_list)))
|
c0869189411919a6984d482523835fcc17fb6f46 | TomaszSzyborski/python_tests | /assertions/assertpy/assertpy_failures_exceptions.py | 2,579 | 3.65625 | 4 | # Failure
# The assertpy library includes a fail() method to explicitly force a test failure. It can be used like this:
from assertpy import assert_that,fail
def test_fail():
fail('forced failure')
# A very useful test pattern that requires the fail()
# method is to verify the exact contents of an error message. For example:
from assertpy import assert_that,fail
def test_error_msg():
try:
some_func('foo')
fail('should have raised error')
except RuntimeError as e:
assert_that(str(e)).is_equal_to('some err')
# In the above code, we invoke some_func()
# with a bad argument which raises an exception.
# The exception is then handled by the try..except block
# and the exact contents of the error message are verified.
# Lastly, if an exception is not thrown by some_func()
# as expected, we fail the test via fail().
#
# This pattern is only used when you need to verify the contents
# of the error message.
# If you only wish to check for an expected exception
# (and don't need to verify the contents of the error message itself),
# you're much better off using a test runner that supports expected exceptions.
# Nose provides a @raises decorator. Pytest has a pytest.raises method.
# Expected Exceptions
# We recommend you use your test runner to check for expected exceptions
# (Pytest's pytest.raises context or Nose's @raises decorator).
# In the special case of invoking a function,
# assertpy provides its own expected exception handling via a simple fluent API.
# Given a function some_func():
def some_func(arg):
raise RuntimeError('some err')
# We can expect a RuntimeError with:
assert_that(some_func).raises(RuntimeError).when_called_with('foo')
# Additionally, the error message contents are chained, and can be further verified:
assert_that(some_func).raises(RuntimeError).when_called_with('foo')\
.is_length(8).starts_with('some').is_equal_to('some err')
# Custom Error Messages
# Sometimes you need a little more information in your failures.
# For this case, assertpy includes a described_as()
# helper that will add a custom message when a failure occurs.
# For example, if we had these failing assertions:
assert_that(1+2).is_equal_to(2)
assert_that(1+2).described_as('adding stuff').is_equal_to(2)
# When run (separately, of course), they would produce these errors:
# Expected <3> to be equal to <2>, but was not.
# [adding stuff] Expected <3> to be equal to <2>, but was not.
# The described_as() helper causes the custom message adding stuff to
# be prepended to the front of the second error.
|
4e68bbee9955e0103cde85c7b28a27e7e2ab145d | mikemadden42/auto_curator | /indices.py | 525 | 3.765625 | 4 | #!/usr/bin/env python
"""Process Elastic indices"""
import csv
def get_indices(file):
"""Create dict of indices"""
with open(file, 'rt') as fin:
cin = csv.DictReader(fin, fieldnames=['index', 'age'])
indices = [row for row in cin]
return indices
def print_indices(indices):
"""Print indices"""
for i in indices:
print(i['index'], i['age'])
def main():
"""Process indices"""
i = get_indices('indices.csv')
print_indices(i)
if __name__ == '__main__':
main()
|
ae6bcf0879ed288ac1cf075b4fb14b7f5accdf0b | AliceOh/Applied-Data-Science-With-Python | /Week3Scratch.py | 10,594 | 4.09375 | 4 |
#Week 3 Assignment 3 - Pandas
#scratch pad begin
import pandas as pd
import numpy as np
#scratch pad end
#Assignment 3 - More Pandas
#Question 1 (20%)
import pandas as pd
import numpy as np
def get_Energy():
energy = pd.read_excel('Energy Indicators.xls', na_values='...', header=None, parse_cols = "C:F", skiprows=18, skip_footer=38, names=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'])
energy['Energy Supply'] *= 1000000
energy['Country'] = energy['Country'].str.replace('\d+', '') #remove digit, 'Switzerland17' should be 'Switzerland'.
energy['Country'] = energy['Country'].str.replace('\s+\(+.*\)+', '') #remove parenthesis, 'Bolivia (Plurinational State of)' should be 'Bolivia',
dicts = {"Republic of Korea": "South Korea",
"United States of America": "United States",
"United Kingdom of Great Britain and Northern Ireland": "United Kingdom",
"China, Hong Kong Special Administrative Region": "Hong Kong"}
energy["Country"].replace(dicts, inplace=True)
'''
print (energy.info)
print(energy.columns)
print(energy.index)
'''
return energy
#print (get_energy())
def get_GDP():
GDP = pd.read_csv('world_bank.csv', skiprows=4 )
dicts = {"Korea, Rep.": "South Korea",
"Iran, Islamic Rep.": "Iran",
"Hong Kong SAR, China": "Hong Kong"}
GDP["Country Name"].replace(dicts, inplace=True)
GDP.rename(columns={'Country Name': 'Country'}, inplace = True)
return GDP
#print (get_GDP())
def get_ScimEn():
ScimEn= pd.read_excel('scimagojr.xlsx')
return ScimEn
#get_ScimEn()
'''
def arrformat(arr):
return '\n'.join(''.join( '{:15}'.format(e) for e in row) for row in arr)
res = []
res.append(['dataframe', 'Starts with', 'Ends with' ])
res.append(['-'*10, '-'*10, '-'*10 ])
res.append(['energy', get_energy()['Country'].iloc[0], get_energy()['Country'].iloc[-1]])
res.append(['GDP', get_GDP()['Country'].iloc[0], get_GDP()['Country'].iloc[-1]])
res.append(['ScimEn', get_ScimEn()['Country'].iloc[0], get_ScimEn()['Country'].iloc[-1]])
print(arrformat(res))
'''
def answer_one():
Energy = get_Energy().set_index('Country')
GDP = get_GDP().set_index('Country').loc[:, '2006':'2015']
ScimEn = get_ScimEn().head(15).set_index('Country')
mergedDF = pd.merge(ScimEn, Energy, how='inner', left_index=True, right_index=True)
mergedDF = pd.merge(mergedDF, GDP, how='inner', left_index=True, right_index=True)
'''
print (mergedDF.info)
print (mergedDF.columns)
print (mergedDF.index)
'''
return mergedDF
#answer_one()
#Question 2 (6.6%) The previous question joined three datasets then reduced this to just the top 15 entries. When you joined the datasets, but before you reduced this to the top 15 items, how many entries did you lose?
def answer_two():
Energy = get_Energy().set_index('Country')
GDP = get_GDP().set_index('Country')
ScimEn = get_ScimEn().set_index('Country')
GDPlen = len(GDP)
Energylen = len(Energy)
sciLen = len(ScimEn)
union = pd.merge(GDP, Energy, how='outer', left_index=True, right_index=True)
union = pd.merge(union, ScimEn, how='outer', left_index=True, right_index=True)
union_count = len(union)
#print ('union', union_count)
mergedDF = pd.merge(GDP, Energy, how='inner', left_index=True, right_index=True)
mergedDF = pd.merge(mergedDF, ScimEn, how='inner', left_index=True, right_index=True)
intersection_count = len(mergedDF)
#print ('intersection_count', intersection_count)
return union_count - intersection_count
#print (answer_two())
#Question 3 (6.6%): What is the average GDP over the last 10 years for each country? (exclude missing values from this calculation.)
#This function should return a Series named avgGDP with 15 countries and their average GDP sorted in descending order.
def answer_three():
Top15 = answer_one()
avgGDP = Top15[[str(year) for year in range(2006, 2016)]].mean(axis=1)
avgGDP.sort_values(ascending=False, inplace=True)
return avgGDP
#print (answer_three())
#Question 4 (6.6%): By how much had the GDP changed over the 10 year span for the country with the 6th largest average GDP?
#This function should return a single number.
def answer_four():
Top15 = answer_one()
avgGDP = Top15[[str(year) for year in range(2006, 2016)]].mean(axis=1)
avgGDP.sort_values(ascending=False, inplace=True)
a = Top15.loc[avgGDP.index[5]].loc['2006':'2015']
print (a)
b = a['2015']-a['2006']
return b
#print (answer_four())
#Question 5 (6.6%): What is the mean Energy Supply per Capita?
#This function should return a single number.
def answer_five():
Top15 = answer_one()
return Top15['Energy Supply per Capita'].mean()
#print (answer_five())
#Question 6 (6.6%): What country has the maximum % Renewable and what is the percentage?
#This function should return a tuple with the name of the country and the percentage.
def answer_six():
Top15 = answer_one()
Top15.sort_values(['% Renewable'], ascending=False, inplace=True)
countryName = Top15.index[0];
per = Top15.iloc[0]['% Renewable']
return (countryName, per)
#print (answer_six())
#Question 7 (6.6%): Create a new column that is the ratio of Self-Citations to Total Citations. What is the maximum value for this new column, and what country has the highest ratio?
#This function should return a tuple with the name of the country and the ratio.
def answer_seven():
Top15 = answer_one()
Top15['Ratio-C'] = Top15['Self-citations']/Top15['Citations']
Top15.sort_values(['Ratio-C'], ascending=False, inplace=True)
countryName = Top15.index[0];
per = Top15.iloc[0]['Ratio-C']
return (countryName, per)
#print (answer_seven())
#Question 8 (6.6%): Create a column that estimates the population using Energy Supply and Energy Supply per capita. What is the third most populous country according to this estimate?
#This function should return a single string value
def answer_eight():
Top15 = answer_one()
#print (Top15.columns)
Top15['PopulationEnergy'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
Top15.sort_values(['PopulationEnergy'], ascending=False, inplace=True)
#print (Top15.head())
countryName = Top15.index[2];
return countryName
#print (answer_eight())
#Question 9 (6.6%): Create a column that estimates the number of citable documents per person. What is the correlation between the number of citable documents per capita and the energy supply per capita? Use the .corr() method, (Pearson's correlation).
#This function should return a single number.
def answer_nine():
Top15 = answer_one()
Top15['PopulationEnergy'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['PopulationEnergy']
return Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])
#print (answer_nine())
#Question 10 (6.6%):Create a new column with a 1 if the country's % Renewable value is at or above the median for all countries in the top 15, and a 0 if the country's % Renewable value is below the median.
#This function should return a series named HighRenew whose index is the country name sorted in ascending order of rank.
def answer_ten():
Top15 = answer_one()
medianRenew = Top15['% Renewable'].median()
def decideValue(x):
retValue = 0;
if(x>=medianRenew):
retValue = 1;
return retValue
HighRenew = Top15['% Renewable'].map(decideValue)
return HighRenew
# print (answer_ten())
#Question 11 (6.6%): Use the following dictionary to group the Countries by Continent, then create a dateframe that displays the sample size (the number of countries in each continent bin), and the sum, mean, and std deviation for the estimated population of each country.
#This function should return a DataFrame with index named Continent ['Asia', 'Australia', 'Europe', 'North America', 'South America'] and columns ['size', 'sum', 'mean', 'std']
ContinentDict = {'China':'Asia',
'United States':'North America',
'Japan':'Asia',
'United Kingdom':'Europe',
'Russian Federation':'Europe',
'Canada':'North America',
'Germany':'Europe',
'India':'Asia',
'France':'Europe',
'South Korea':'Asia',
'Italy':'Europe',
'Spain':'Europe',
'Iran':'Asia',
'Australia':'Australia',
'Brazil':'South America'}
def answer_eleven():
Top15 = answer_one()
Top15['PopulationEnergy'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
Top15['Continent'] = Top15.index.map(lambda x: ContinentDict[x])
group = Top15.groupby('Continent')
return pd.DataFrame({"size": group.count()["2010"],
"sum": group['PopulationEnergy'].sum(),
"mean": group['PopulationEnergy'].mean(),
"std": group['PopulationEnergy'].std()})
#print (answer_eleven())
#Question 12 (6.6%): Cut % Renewable into 5 bins. Group Top15 by the Continent, as well as these new % Renewable bins. How many countries are in each of these groups?
#This function should return a Series with a MultiIndex of Continent, then the bins for % Renewable. Do not include groups with no countries.
def answer_twelve():
Top15 = answer_one()
Top15['Continent'] = Top15.index.map(lambda x: ContinentDict[x])
group = Top15.groupby(['Continent',
pd.cut(Top15['% Renewable'], 5,
labels=["bin{0}".format(bin) for bin in range(5)])])
s = group['2010'].count()
return s
#print (answer_twelve())
#Question 13 (6.6%) Convert the Population Estimate series to a string with thousands separator (using commas). Do not round the results.
# e.g. 317615384.61538464 -> 317,615,384.61538464
# This function should return a Series PopEst whose index is the country name and whose values are the population estimate string.
def answer_thirteen():
Top15 = answer_one()
Top15['PopulationEnergy'] = Top15['Energy Supply']/Top15['Energy Supply per Capita']
return Top15['PopulationEnergy'].map(lambda x: "{0:,}".format(x))
print (answer_thirteen())
|
3e6a5b1bfe8c18187dbf843dcffa45f84c694ad9 | ewartj/MedCAT_Deidentification | /dictionaries/nhsNumber/nhs_number_generator.py | 7,583 | 4.375 | 4 | """Generate 10-digit NHS numbers with optional formatting.
This module allows you to generate 10-digit NHS numbers, which are the unique patient identifier used by the National
Health Service. Note that, at some point point in the past, NHS numbers were 9-digits long.
Examples:
The file can be called from the command line, in which case it prints the numbers directly to the screen:
$ python generate_nhs_numbers.py
Alternatively, you can use one of the two types of generator function:
This one will start at '4000000004' and count up, skipping any invalid numbers or numbers not routinely issued
>>> deterministic_gen = deterministic_nhs_number_generator()
>>> next(deterministic_gen)
This one is (pseudo)random and will generate NHS numbers in the range specified
>>> random_gen = random_nhs_number_generator([(489000000, 489999999)])
>>> next(random_gen)
FROM: https://github.com/Iain-S/nhs_number_generator
"""
from __future__ import unicode_literals
import random
from random import randint, choice
from argparse import ArgumentParser
check_digit_weights = {0: 10,
1: 9,
2: 8,
3: 7,
4: 6,
5: 5,
6: 4,
7: 3,
8: 2}
def calculate_check_digit(nhs_number):
"""Given the first 9 or 10 digits of a 10-digit NHS number, calculates what the check digit should be.
Returns:
int: The check digit. Note that this function may return 10, in which case the NHS number is invalid.
"""
# The procedure for calculating the check digit, according to:
# https://www.datadictionary.nhs.uk/data_dictionary/attributes/n/nhs/nhs_number_de.asp
# Step 1) Multiply each of the first nine digits by a weighting factor
products = [int(nhs_number[i]) * check_digit_weights[i] for i in range(9)]
# Step 2) Add the results of each multiplication together.
sum_products = sum(products)
# Step 3) Divide the total by 11 and establish the remainder.
remainder = sum_products % 11
# Step 4) Subtract the remainder from 11 to give the check digit.
eleven_minus_remainder = 11 - remainder
# If the result is 11 then a check digit of 0 is used. If the result is 10 then the NHS number is invalid.
if eleven_minus_remainder == 11:
return 0
else:
return eleven_minus_remainder
def deterministic_nhs_number_generator(ranges=[(400000000, 499999999), (600000000, 708800001)]):
"""Returns a generator for a predictable sequence of 10-digit NHS numbers.
The default ranges are the ones currently issued in England, Wales and the Isle of Man. Numbers outside of this
range may be valid but could conflict with identifiers used in Northern Ireland and Scotland.
See https://en.wikipedia.org/wiki/NHS_number
Args:
ranges [(int, int), ...]: Specify the ranges for the sequence. You must exclude the check digits.
"""
for _range in ranges:
if _range[1] < _range[0]:
raise ValueError("The high end of the range should not be lower than the low end.")
if (_range[1] - _range[0]) == 0:
only_possible_check_digit = calculate_check_digit('{:09d}'.format(_range[0]))
if only_possible_check_digit == 10:
raise ValueError("{:09d} is not a valid NHS number.".format(_range[0]))
for _range in ranges:
i = _range[0]
while i <= _range[1]:
candidate_number = '{:09d}'.format(i)
check_digit = calculate_check_digit(candidate_number)
if check_digit != 10:
yield candidate_number + str(check_digit)
i += 1
return
def random_nhs_number_generator(ranges=[(400000000, 499999999), (600000000, 708800001)]):
"""Returns a generator for an unpredictable sequence of 10-digit NHS numbers.
The default ranges are the ones currently issued in England, Wales and the Isle of Man. Numbers outside of this
range may be valid but could conflict with identifiers used in Northern Ireland and Scotland.
See https://en.wikipedia.org/wiki/NHS_number
Args:
ranges [(int, int), ...]: Specify the ranges for the sequence. You must exclude the check digits.
"""
# JS added a random seed
random.seed(42)
for _range in ranges:
if _range[1] < _range[0]:
raise ValueError("The high end of the range should not be lower than the low end.")
if (_range[1] - _range[0]) == 0:
only_possible_check_digit = calculate_check_digit('{:09d}'.format(_range[0]))
if only_possible_check_digit == 10:
raise ValueError("{:09d} is not a valid NHS number.".format(_range[0]))
while True:
# Pick a tuple (a, b) at random from ranges and get a random int >= a and <= b.
# Note that this weights the ranges equally, no matter their size
candidate_number = '{:09d}'.format(randint(*choice(ranges)))
check_digit = calculate_check_digit(candidate_number)
if check_digit != 10:
yield candidate_number + str(check_digit)
def add_separators(nhs_number, separator=' '):
"""Returns the NHS number in 3-3-4 format with a separator in between (a space by default)."""
return nhs_number[0:3] + separator + nhs_number[3:6] + separator + nhs_number[6:10]
def remove_separators(nhs_number):
"""Remove separators, if there are any, to go from e.g. 123-456-7890 to 1234567890."""
if not nhs_number[3].isnumeric() and not nhs_number[7].isnumeric():
return nhs_number[0:3] + nhs_number[4:7] + nhs_number[8:]
else:
return nhs_number
def is_valid_nhs_number(nhs_number):
"""Checks whether the NHS number is valid.
NHS numbers in 3-3-4 format should be converted first, i.e. with remove_separators().
"""
if (type(nhs_number) != str and type(nhs_number) != unicode) or len(nhs_number) != 10 or not nhs_number.isnumeric():
return False
check_digit = calculate_check_digit(nhs_number)
# The check digit shouldn't be 10 (how could it be, it is only one digit)
if check_digit == 10:
return False
if str(check_digit) == nhs_number[9]:
return True
else:
return False
def main():
"""Generate 10-digit NHS numbers from the command line."""
# Define our command line options with sensible defaults and help messages
parser = ArgumentParser(description="Generate 10-digit NHS numbers.")
parser.add_argument('-n', required=False, type=int, help="the amount to generate", default=10)
parser.add_argument('-d', '--deterministic', action='store_const',
const=True, default=False,
help='whether to generate predictably, starting at 4000000004')
parser.add_argument('-f', '--format', action='store_const',
const=True, default=False,
help='whether to format using spaces e.g. 565 228 3297')
# Get the arguments passed in by the user
arguments = parser.parse_args()
if arguments.deterministic:
generator = deterministic_nhs_number_generator()
else:
generator = random_nhs_number_generator()
if arguments.format:
formatter = add_separators
else:
formatter = lambda x: x
for i in range(arguments.n):
print(formatter(next(generator)))
if __name__ == "__main__":
main() # pragma: no cover
|
bd8845c3c2155e4ecbceb0e46121970e40362813 | choroba/perlweeklychallenge-club | /challenge-059/lubos-kolouch/python/ch-1.py | 1,750 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def append(self, value):
current = self
while current.next:
current = current.next
current.next = LinkedList(value)
def partition(self, k):
less_head = None
greater_head = None
less_tail = None
greater_tail = None
current = self
while current:
if current.value < k:
if less_tail:
less_tail.next = current
else:
less_head = current
less_tail = current
else:
if greater_tail:
greater_tail.next = current
else:
greater_head = current
greater_tail = current
current = current.next
if less_tail:
less_tail.next = greater_head
else:
less_head = greater_head
if greater_tail:
greater_tail.next = None
return less_head
def __str__(self):
current = self
result = []
while current:
result.append(str(current.value) + " → ")
current = current.next
result.append("END")
return "".join(result)
if __name__ == "__main__":
linked_list = LinkedList(1)
linked_list.append(4)
linked_list.append(3)
linked_list.append(2)
linked_list.append(5)
linked_list.append(2)
print("Original list:", linked_list)
k_val = 3
partitioned_list = linked_list.partition(k_val)
print(f"Partitioned list with k={k_val}:", partitioned_list)
|
2ddf2b5b92bd9e7e1a9f57936f083649061f66ea | nreszetnik/Year9DesignCS-PythonNR | /DILists.py | 707 | 4.125 | 4 |
food1 = input("Input food 1: ")
food2 = input("Input food 2: ")
food3 = input("Input food 3: ")
foods = [food1, food2, food3]
foods.sort()
print(foods)
a = 4 #Create a variable called a and store 4 in it
#Lists has a legth of 6 and indexes 0 - 5
# 0 1 2 3 4 5
list = [1,2,3,4,5,6]
#To access the data in the list we need the list name and the index
print (a)
print (list)
print (list[0]) #List at index 0
print (list[1]) #list at index 1
print (list[5]) #List at index 5
lenList = len(list)
print (list[lenList-1])
list[0] = 999
print (list)
list[lenList-1] = 9999
print (list)
#The append list.append command adds the sugested feature to the
#end of your list
list.append(76)
print (list) |
e7e63a4fe05cdca2d7e05a3e3a41575c21b61c89 | Streats22/Flex-HelloYou | /Loops_Robin.py | 399 | 3.5 | 4 | import turtle
colors = [ "red","purple","blue","green","orange","yellow"]
YEEET = turtle.Turtle()
YEEET.speed(10)
for x in range(180):
YEEET.pencolor(colors[x % 6])
YEEET.forward(100)
YEEET.right(30)
YEEET.forward(20)
YEEET.left(60)
YEEET.forward(50)
YEEET.right(30)
YEEET.penup()
YEEET.setposition(0, 0)
YEEET.pendown()
YEEET.right(2)
turtle.done()
|
e7e8278a4966e6e378629f9fdde1cbd0cbdde846 | VBharwani2001/Python-Bootcamp | /Day 24/snake.py | 1,284 | 3.984375 | 4 | from turtle import *
start_position = [(0, 0), (-20, 0), (-40, 0)]
class Snake:
def __init__(self):
self.turtles = []
self.create_snake()
self.head = self.turtles[0]
def create_snake(self):
for position in start_position:
self.add_snake(position)
def add_snake(self, position):
turtle = Turtle()
turtle.shape("square")
turtle.color("white")
turtle.penup()
turtle.goto(position)
self.turtles.append(turtle)
def extend_snake(self):
self.add_snake(self.turtles[-1].position())
def move(self):
for turtle in range(len(self.turtles)-1, 0, -1):
new_x = self.turtles[turtle-1].xcor()
new_y = self.turtles[turtle-1].ycor()
self.turtles[turtle].goto(new_x, new_y)
self.turtles[0].forward(20)
def reset(self):
for turtle in self.turtles:
turtle.hideturtle()
self.turtles.clear()
self.create_snake()
self.head = self.turtles[0]
def up(self):
self.turtles[0].setheading(90)
def down(self):
self.turtles[0].setheading(270)
def left(self):
self.turtles[0].setheading(180)
def right(self):
self.turtles[0].setheading(0)
|
10d35d30bed89d7db53ba5e6f83a40195e9d26be | Jan-zou/LeetCode | /python/String/14_longest_common_prefix.py | 692 | 3.875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Description:
Write a function to find the longest common prefix string amongst an array of strings.
Tags: String
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
lognest = strs[0]
for string in strs[1:]:
i = 0
while i < len(string) and i < len(lognest) and string[i] == lognest[i]:
i += 1
lognest = lognest[:i]
return lognest
if __name__ == '__main__':
Solution().longestCommonPrefix(["hello", "heaven", "heavy"])
|
d5ff0d704d84bd58ec2a07ec537a1639166bf6ee | bakliwalvaibhav1/python_basic_udemy | /3_Greatest_of_Three/greatest_of_three.py | 185 | 4.0625 | 4 | a= int(input('Enter First Number'))
b= int(input('Enter Second Number'))
c= int(input('Enter Third Number'))
if b<= a >=c:
print(a)
elif a<= b >=c:
print (b)
else:
print(c)
|
ca4d697ec13b6fb492bdc124bc5fce7607e87b63 | 1miaocat/Exercise4 | /Modularization Ex.py | 2,644 | 3.5625 | 4 | #1
def sample(*args):
x = print(list(args)) #list
y = print(args) #tuple
return x,y
sample(3,5,7,23)
#2
def translate(text):
trans = ''
for i in text:
if i not in('aeiou '):
trans += i + 'o' + i
else:
trans += i
return trans
x = translate('this is fun')
print(x)
#3
import calendar
def calendar_month(theyear, themonth, w=0, l=0):
x = calendar.TextCalendar()
y = x.formatmonth(theyear, themonth, w=0, l=0)
return y
print(calendar_month(2012, 10, 5, 2))
#4
def is_member(x,a):
for i in a:
if i == x:
return True
else:
return False
print( is_member(3,[1,2]))
#5
def overlapping(lst1,lst2):
for i in lst1:
for j in lst2:
if i == j:
return True
else:
return False
#6
def hisotgram(lst):
star = '*'
for i in lst:
x = i * star
print(x)
hisotgram([4,9,7])
#7
def list_of_word(list):
length = []
for i in range(len(list)):
length.append(len(list[i]))
return length
#8
def find_longest_word(lwords):
length = []
for i in lwords:
length.append((len(i), i)) #make a tuple of words from list
length.sort() #sort the tuple
return length[-1][1] #last data has to be the largest
#9
def filter_long_words(lwords, n):
length = []
for i in range(len(lwords)):
if len(lwords[i]) > n:
length.append(lwords[i])
return length
#10
def check_if_pangram(word):
alphabet = 'qwertyuiopasdfghjklzxcvbnm '
for word in alphabet:
if word not in alphabet:
return False
return True
#11
def char_freq(string):
freq = {}
for i in string:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
return freq
print(char_freq('aaaa'))
#12
def make_forms(verb):
for i in verb:
if i.endswith('y'):
result = i.replace(i[-1], 'ies')
# return result
elif i.endswith(('o', 'cs', 's', 'sh', 'z')):
result = i + 'es'
# return result
else:
result = i + 's'
print(result)
make_forms(['try', 'brush', 'run', 'fix'])
#13
def make_forming(verb):
for i in verb:
if i.endswith('e') and not i.endswith('ie'):
result = i.replace(i[-1], 'ing')
elif i.endswith('ie'):
result = i.replace(i[-2:], 'y') + 'ing'
print(result)
make_forming(['lie'])
|
6258afc8475776e96ad8ca51978ddb9cd6ca10f5 | Miklosam/Python-projects | /Registration_AMM.py | 424 | 3.65625 | 4 | #!/usr/bin/env python3
# Anthony Miklos
# module 2 homework. registration program
print("Student Registration Form")
#fname = ""
#lname = "Williams"
#byear = 1973
#pword = "secret"
print ()
fname = input("First Name ")
lname = input("Last Name ")
byear = input("Birth Year ")
pword = (fname + "*" + byear)
print ("Wlecome" + " " + fname + " " + lname + " ")
print ("Your password is " + pword)
|
b528a7a0524b5a8c401629da2c0d9a777fe49d50 | myConsciousness/metis | /metis/sql.py | 14,143 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
SQLite is a relational database management system contained in a C programming library.
In contrast to many other database management systems, SQLite is not a client–server database engine.
Rather, it is embedded into the end program.
SQLite is ACID-compliant and implements most of the SQL standard,
using a dynamically and weakly typed SQL syntax that does not guarantee the domain integrity.
SQLite is a popular choice as embedded database software
for local/client storage in application software such as web browsers.
It is arguably the most widely deployed database engine,
as it is used today by several widespread browsers, operating systems,
and embedded systems (such as mobile phones), among others.
SQLite has bindings to many programming languages.
:copyright: (c) 2018 by Kato Shinya.
:license: MIT, see LICENSE for more details.
'''
import sqlite3
__author__ = 'Kato Shinya'
__date__ = '2018/04/21'
class MstParameterDao:
'''MST_PARAMETER.TBLへのトランザクション処理を定義するDAOクラス。'''
def select_params_by_primary_key(self, cursor: sqlite3.Cursor, primary_key: str) -> tuple:
'''主キーを用いてMST_PARAMETER.TBLから値を取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str primary_key: 検索ワード。
:rtype: tuple
:return: 検索結果。
'''
cursor.execute('''
SELECT
VALUE
FROM
MST_PARAMETER
WHERE
PARAM_NAME = ?
''', (primary_key,))
return cursor.fetchone()
def update_params_by_primary_key(self, cursor: sqlite3.Cursor, update_value: str, primary_key: str):
'''主キーを用いてMST_PARAMETER.TBLの値を更新するクエリ。
:param sqlite3.Cursor cursor: カーソル。
:param str update_value: 更新値。
:param str primary_key: プライマリーキー。
'''
cursor.execute('''
UPDATE
MST_PARAMETER
SET
VALUE = ?
WHERE
PARAM_NAME = ?
''', (update_value, primary_key,))
class ManageSerialDao:
'''MANAGE_SERIAL.TBLへのトランザクション処理を定義するDAOクラス。'''
def insert_serial_no(self, cursor: sqlite3.Cursor, serial_no: str):
'''生成したシリアル番号をMANAGE_SERIAL.TBLへ挿入するクエリ。
:param sqlite3.Cursor cursor: カーソル。
:param str serial_no: クローラ起動用のシリアル番号。
'''
cursor.execute('''
INSERT INTO
MANAGE_SERIAL
VALUES (
?,
datetime('now', 'localtime')
)
''',(serial_no,))
def count_records_by_primary_key(self, cursor: sqlite3.Cursor, primary_key: str) -> tuple:
'''主キーを用いてMANAGE_SERIAL.TBLから値を取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str primary_key: 検索ワード。
:rtype: tuple
:return: 検索結果。
'''
cursor.execute('''
SELECT
COUNT(1)
FROM
MANAGE_SERIAL
WHERE
SERIAL_NO = ?
''', (primary_key,))
return cursor.fetchone()
def count_records(self, cursor: sqlite3.Cursor):
'''MANAGE_SERIAL.TBLのレコード数を取得するクエリ。
:param sqlite3.Cursor cursor: カーソル。
:rtype: tuple
:return: 取得件数。
'''
cursor.execute('''
SELECT
COUNT(1)
FROM
MANAGE_SERIAL
''')
return cursor.fetchone()
def delete_records(self, cursor: sqlite3.Cursor):
'''MANAGE_SERIAL.TBLから全レコードを削除するクエリ。
:param sqlite3.Cursor cursor: カーソル。
'''
cursor.execute('''
DELETE FROM
MANAGE_SERIAL
''')
class ArticleInfoHatenaDao:
'''ARTICLE_INFO_HATENA.TBLへのトランザクション処理を定義するDAOクラス。'''
def select_by_search_word(self, cursor: sqlite3.Cursor, search_word: str) -> tuple:
'''ARTICLE_INFO_HATENA.TBLから記事情報を取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str search_word: 検索ワード。
:rtype: tuple
:return: 検索結果。
'''
cursor.execute('''
SELECT
URL,
TITLE,
PUBLISHED_DATE,
BOOKMARKS,
TAG,
REGISTER_DATE,
UPDATED_DATE,
RESERVED_DEL_DATE
FROM
ARTICLE_INFO_HATENA
WHERE
TAG
LIKE
?
''',(search_word,))
return cursor.fetchall()
def select_by_primary_key(self, cursor: sqlite3.Cursor, url: str) -> tuple:
'''主キーを用いてARTICLE_INFO_HATENA.TBLから記事情報を取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str url: 検索対象URL。
:rtype: tuple
:return: 検索結果。
'''
cursor.execute('''
SELECT
URL,
TITLE,
PUBLISHED_DATE,
BOOKMARKS,
TAG,
REGISTER_DATE,
UPDATED_DATE,
RESERVED_DEL_DATE
FROM
ARTICLE_INFO_HATENA
WHERE
URL = ?
''', (url,))
return cursor.fetchone()
def select_all_url(self, cursor: sqlite3.Cursor) -> tuple:
'''ARTICLE_INFO_HATENA.TBLから全URLを取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:rtype: tuple
:return: 登録されている全URL。
'''
cursor.execute('''
SELECT
URL
FROM
ARTICLE_INFO_HATENA
''')
return cursor.fetchall()
def select_order_by_bookmarks_desc(self, cursor: sqlite3.Cursor, search_word: str) -> tuple:
'''ARTICLE_INFO_HATENA.TBLからブックマーク数を基準に降順でソートされたレコードを取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str search_word: 検索ワード。
:rtype: tuple
:return: ブックマーク数を基準に降順でソートされたレコード。
'''
cursor.execute('''
SELECT
URL,
TITLE,
PUBLISHED_DATE,
BOOKMARKS,
TAG,
REGISTER_DATE,
UPDATED_DATE,
RESERVED_DEL_DATE
FROM
ARTICLE_INFO_HATENA
WHERE
TAG
LIKE
?
ORDER BY
BOOKMARKS DESC
''', (search_word,))
return cursor.fetchall()
def select_order_by_bookmarks_asc(self, cursor: sqlite3.Cursor, search_word: str) -> tuple:
'''ARTICLE_INFO_HATENA.TBLからブックマーク数を基準に昇順でソートされたレコードを取得するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str search_word: 検索ワード。
:rtype: tuple
:return: ブックマーク数を基準に昇順でソートされたレコード。
'''
cursor.execute('''
SELECT
URL,
TITLE,
PUBLISHED_DATE,
BOOKMARKS,
TAG,
REGISTER_DATE,
UPDATED_DATE,
RESERVED_DEL_DATE
FROM
ARTICLE_INFO_HATENA
WHERE
TAG
LIKE
?
ORDER BY
BOOKMARKS ASC
''', (search_word,))
return cursor.fetchall()
def update_bookmarks_by_primary_key(self, cursor: sqlite3.Cursor, bookmarks: str, primary_key: str):
'''主キーを用いてARTICLE_INFO_HATENA.TBLのブックマーク数を更新するクエリ。
返り値はtuple型。
:param sqlite3.Cursor cursor: カーソル。
:param str bookmarks: ブックマーク数。
:param str primary_key: 主キー。
'''
cursor.execute('''
UPDATE
ARTICLE_INFO_HATENA
SET
BOOKMARKS = ?
WHERE
URL = ?
''',(bookmarks, primary_key,))
def insert_article_infos(self, cursor: sqlite3.Cursor, article_infos: dict):
'''取得した記事情報をARTICLE_INFO_HATENA.TBLへ挿入するクエリ。
:param sqlite3.Cursor cursor: カーソル。
:param dict article_infos: カラムと挿入する記事情報の対応辞書。
'''
cursor.execute('''
INSERT INTO
ARTICLE_INFO_HATENA
VALUES (
:URL,
:TITLE,
:PUBLISHED_DATE,
:BOOKMARKS,
:TAG,
datetime('now', 'localtime'),
datetime('now', 'localtime'),
:RESERVED_DEL_DATE
)
''',(article_infos))
def transfer_article_info_from_work(self, cursor: sqlite3.Cursor):
'''WORK_ARTICLE_INFO_HATENA.TBLからARTICLE_INFO_HATENA.TBLへ記事情報を移行させるクエリ。
:param sqlite3.Cursor cursor: カーソル。
:param dict article_infos: カラムと挿入する記事情報の対応辞書。
'''
cursor.execute('''
INSERT INTO
ARTICLE_INFO_HATENA
SELECT
URL,
TITLE,
PUBLISHED_DATE,
BOOKMARKS,
TAG,
REGISTER_DATE,
UPDATED_DATE,
RESERVED_DEL_DATE
FROM
WORK_ARTICLE_INFO_HATENA
''')
class WorkArticleInfoHatenaDao:
'''WORK_ARTICLE_INFO_HATENA.TBLへのトランザクション処理を定義するDAOクラス。'''
def count_records(self, cursor: sqlite3.Cursor):
'''WORK_ARTICLE_INFO_HATENA.TBLのレコード数を取得するクエリ。
:param sqlite3.Cursor cursor: カーソル。
'''
cursor.execute('''
SELECT
COUNT(1)
FROM
WORK_ARTICLE_INFO_HATENA
''')
return cursor.fetchone()
def insert_article_infos(self, cursor: sqlite3.Cursor, article_infos: dict):
'''取得した記事情報をWORK_ARTICLE_INFO_HATENA.TBLへ挿入するクエリ。
:param sqlite3.Cursor cursor: カーソル。
:param dict article_infos: カラムと挿入する記事情報の対応辞書。
'''
cursor.execute('''
INSERT INTO
WORK_ARTICLE_INFO_HATENA
VALUES (
:URL,
:TITLE,
:PUBLISHED_DATE,
:BOOKMARKS,
:TAG,
datetime('now', 'localtime'),
datetime('now', 'localtime'),
:RESERVED_DEL_DATE
)
''',(article_infos))
def delete_records(self, cursor: sqlite3.Cursor):
'''WORK_ARTICLE_INFO_HATENA.TBLから全レコードを削除するクエリ。
:param sqlite3.Cursor cursor: カーソル。
'''
cursor.execute('''
DELETE FROM
WORK_ARTICLE_INFO_HATENA
''')
|
fbf5eabef14be51ecf8070f4f1edc0b5ab7097df | lhj940825/algorithm | /leetcode/Two_Pointer/q141_linked_list_cycle.py | 634 | 3.6875 | 4 | '''
* User: Hojun Lim
* Date: 2021-03-05
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head:
return False
cur_node = head.next
cycle_check_pnt = head
step = 0
while cur_node:
if cur_node == cycle_check_pnt:
return True
if step % 2 == 1:
cycle_check_pnt = cycle_check_pnt.next
cur_node = cur_node.next
step += 1
return False
|
a60754bf27bd5783f22071209cfcb082e687397e | nehamarne2700/python | /untitled/basic/design.py | 267 | 3.828125 | 4 | import turtle
wn=turtle.Screen()
wn.bgcolor("black")
colors=["red","purple","blue","green","orange","yellow","white"]
draw=turtle.Turtle()
for x in range(360):
draw.pencolor(colors[x%7])
draw.width(x/120+1)
draw.forward(x)
draw.left(51)
turtle.done() |
74441f94367cdf10a79d784793b18781e7789a48 | suhang319/exercise | /第5天/对象练习题1.py | 980 | 3.578125 | 4 | #_*_ coding:utf-8 _*_
#@Time :2020-12-2011:58
#@Author :lemon_suhang
#@Email :1147967632@qq.com
#@File :对象练习题1.py
#@Software:PyCharm
# 打印小猫爱吃鱼,打印小猫要喝水
class Cat():
def chi(self):
print(f'小猫爱吃鱼')
def he(self):
print(f"小猫要喝水")
xiaomao1=Cat()
xiaomao2=Cat()
xiaomao1.chi()
xiaomao2.he()
class Cat():
def chi(self,food):
print(f'小猫爱吃鱼{food}')
def he(self,wood):
print(f"小猫要喝水{wood}")
xiaomao1 = Cat()
xiaomao2 = Cat()
xiaomao1.chi('鱼')
xiaomao2.he("水")
# 性别为男的梁超老师教测试
"""""
属性
性别 男
姓名 梁超
方法 教测试
老师 对象
职业 类
"""
class Zhiye():
def __init__(self,gendre,name):
self.gender=gendre
self.name = name
def jiao(self,jiao):
print(f"性别为{self.gendre}的{self.name}老师教{jiao}")
teter=Zhiye("男","梁超")
teter.jiao('测试')
|
2b166e1f5daabe83b5045651bc1bae1632fb9d4d | ashishkhiani/Daily-Coding-Problems | /challenges/problem_180/unit_test.py | 1,222 | 4.03125 | 4 | import unittest
from challenges.problem_180.solution import interleave
class InterleaveTest(unittest.TestCase):
def test_example_1(self):
"""Tests the given example"""
_input = [1, 2, 3, 4, 5]
expected = [1, 5, 2, 4, 3]
actual = interleave(_input)
self.assertEqual(expected, actual)
def test_example_2(self):
"""Tests the given example"""
_input = [1, 2, 3, 4]
expected = [1, 4, 2, 3]
actual = interleave(_input)
self.assertEqual(expected, actual)
def test_example_3(self):
"""Tests the given example"""
_input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
expected = [1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6]
actual = interleave(_input)
self.assertEqual(expected, actual)
def test_empty_input(self):
"""Tests the case where the input is an empty array"""
_input = []
expected = []
actual = interleave(_input)
self.assertEqual(expected, actual)
def test_null_input(self):
"""Tests the case where the input is null"""
_input = None
expected = []
actual = interleave(_input)
self.assertEqual(expected, actual)
|
fac5d5727b65213ed936d6a9f15b0b56d9b3e667 | kjklug/class-work | /fromcount.py | 296 | 3.859375 | 4 | inp=input("Enter the name of a text file: \n")
fhand=open(inp)
count=0
for line in fhand:
words=line.split()
# print 'Debug:', words
if len(words) >= 2 and words[0] == 'From' :
print(words[1])
count=count+1
print('There were', count, 'lines in the file with From as the first word.') |
503163475669d14fe8552955f3b06422943be4f0 | MarcosFantastico/Python | /Exercicios/ex086.py | 1,451 | 3.78125 | 4 | '''matriz = [[], [], []]
for i in range(0, 3):
for j in range(0, 3):
matriz[i].append(int(input(f'Digite um valor para [{i}, {j}]: ')))
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]:^5}]', end='')
print()'''
# matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
matriz = [[0] * 3, [0] * 3, [0] * 3]
print(matriz)
for i in range(0, 3):
for j in range(0, 3):
matriz[i][j] = int(input(f'Digite um valor para [{i}, {j}]: '))
print('-=' * 30)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]:^5}]', end='')
print()
'''li = [[], [], []]
for c in range(1, 10):
while True:
try:
if c < 4:
n = int(input(f'\033[30;1mDigite um valor para a posição [1, {c}]: '))
li[0].append(n)
elif c < 7:
n = int(input(f'Digite um valor para a posição [2, {c - 3}]: '))
li[1].append(n)
else:
n = int(input(f'Digite um valor para a posição [3, {c - 6}]: '))
li[2].append(n)
break
except ValueError:
print('\033[31mDigite um valor válido.\033[30m')
print(f'\n\033[35mSua Matriz 3x3:{"_" * 20}\033[30m'
f'[ {li[0][0]} ] [ {li[0][1]} ] [ {li[0][2]} ]'
f'[ {li[1][0]} ] [ {li[1][1]} ] [ {li[1][2]} ]'
f'[ {li[2][0]} ] [ {li[2][1]} ] [ {li[2][2]} ]')
''' |
82f289cfe5bf178f21ffc6355b943bade4deb55d | MarcoMadera/Re-py | /helloMe.py | 240 | 3.78125 | 4 | def main():
name = str(input('¿Cuál es tu nombre? '))
age = int(input('¿Cuál es tu edad? '))
if age > 18:
print('Hola, señor ' + name + '!')
else:
print('Hola, joven ' + name + '!')
if __name__ == '__main__':
main() |
e59ed82f3008fd71e2916159fc6d35b89c43a97d | GsekarGuna/Gunasekar | /Set 6-55.py | 117 | 4.09375 | 4 | a=int(input("Enter the value:"))
b=int(input("Enter the value:"))
if(a*b%2==0):
print("Even")
else:
print("Odd")
|
511955a2a6153b298bd83ae099f68db46d18de5f | LeBoucEtMistere/Website-Monitor | /task.py | 1,088 | 3.859375 | 4 | from time import time, sleep
from threading import Event
class Task:
""" A generic class used to represent a threaded task that repeat every period and can be stopped."""
def __init__(self, period):
""" The constructor of the class
Parameters:
period (int): The period in seconds of the task.
"""
self.stopping = Event()
self.period = period
def stop(self):
""" A method that stops the main loop of the task and allow the thread to join."""
self.stopping.set()
def run(self):
""" The main loop of the task, execute the code logic in the method do_work() that should be defined by child classes."""
origin_time = time()
while not self.stopping.is_set():
if time() - origin_time > self.period:
origin_time = time()
self.do_work()
else:
sleep(0.1)
def do_work(self):
""" The method that implements the task logic, should be redefined by children classes."""
raise NotImplementedError
|
6016fc1bc7704aaa1af51fb47b4bf73974dd844c | ericbgarnick/AOC | /y2018/day11/day11.py | 2,563 | 3.59375 | 4 | from sys import argv
from typing import Tuple, List, Dict
SERIAL_NUMBER = 3628
RACK_ID_INCREMENT = 10
GRID_SIZE = 300
def find_best_power_coord(square_size: int) -> Tuple[Tuple[int, int], int]:
best_p = 0
best_power_coord = (0, 0)
grid = []
for y in range(GRID_SIZE):
grid.append([])
for x in range(GRID_SIZE):
p = _power_level((x, y))
vert_sum = _calc_vert_sum(x, y, grid, p, square_size)
enough_cols = _enough_cols(x, square_size)
grid[y].append({'power': p,
'vert_sum': vert_sum})
if vert_sum and enough_cols:
new_p = sum(grid[y][x_coord]['vert_sum'] for
x_coord in range(x - (square_size - 1), x + 1))
if new_p > best_p:
best_p = new_p
best_power_coord = (x - (square_size - 2),
y - (square_size - 2))
return best_power_coord, best_p
def _calc_vert_sum(x: int, y: int, grid: List[List[Dict]],
current_power: int, square_size: int) -> int:
if y < square_size - 1:
return 0
else:
return sum(grid[y_coord][x]['power'] for y_coord in
range(y - (square_size - 1), y)) + current_power
def _enough_cols(x: int, square_size: int) -> bool:
if x < square_size - 1:
return False
else:
return True
def _power_level(coord: Tuple[int, int]) -> int:
# power level calculated using 1-indexing
x, y = [c + 1 for c in coord]
rack_id = x + RACK_ID_INCREMENT
power_str = str((y * rack_id + SERIAL_NUMBER) * rack_id)
try:
p = int(str(power_str)[-3])
except IndexError:
p = 0
return p - 5
if __name__ == '__main__':
size = int(argv[1])
if size:
best_coord, best_power = find_best_power_coord(size)
best_size = size
else:
best_coord = (0, 0)
best_size = 0
best_power = 0
for s in range(1, GRID_SIZE + 1):
new_coord, new_power = find_best_power_coord(s)
if new_power > best_power:
best_coord = new_coord
best_power = new_power
best_size = s
elif new_power < best_size:
break
print("BEST COORD: {} HAS POWER: {} AT SIZE: {}".format(best_coord,
best_power,
best_size))
|
88b44dce43c7e469e4076e5aae2c2e2bf487fea5 | stanleychilton/portfolio | /exmaple files/comp/num tester.py | 418 | 3.609375 | 4 | for e in range(1, 1000):
for f in range(1,1000):
for c in range(2,2000):
count = 0
print ("test start")
print (e,f,c)
f += e
while e != 0 or f < c:
if f >= c:
d = f//c
count += d
f = (f % c) + d
else:
break
print(count)
|
56dda08a9a62257613aadf6f06ba1a6e11226344 | WONGUYBEE/python-projekt | /filterData.py | 4,500 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 16:36:55 2017
@author: mb-fa
"""
import pandas as pd
import numpy as np
from inputNumber import inputIntNumber
from inputNumber import inputFloatNumber
def filterData(data, data0):
dataTypeMenu = "Choose which datatype you want to apply a filter to \n1 = Temperature \n2 = Growthrate \n3 = Bacteriatype'\n4 = Reset \n5 = Show data \n0 For return to main menu."
bacteriaString = "Choose which bacteriatype you want filter for \n1 = Salmonella enterica \n2 = Bacillus cereus \n3 = Listeria \n4 = Brochothrix thermosphacta \n0 = return"
upLim = "Insert your upper-limit T < u.limit, as a number [e.g. 3.45]"
lowLim = "Insert your lower-limit T > l.limit, as a number [e.g. 3.45]"
limitMenu = "1 for lowerLimitation \n2 for upperlimitation \n3 for between two limits\n 0 to return to main menu"
bacList = np.array([0, "Salmonella enterica", "Bacillus cereus", "Listeria", "Brochothrix thermosphacta"])
while True:
mainC = inputIntNumber(dataTypeMenu)
if(mainC == 0): #returns to main menu
print("The size of samples after filtering is: {:d} | Total samples filtered out are {:d}".format(len(data),(len(data0)-len(data)))) #prints number of current and removed samples
break
if(mainC == 1): #sorts for temperature
while True:
print("To sort for temperature, you must now specify filtering limits" )
limitType = inputIntNumber(limitMenu) #allows the user to choose specific limitations for samples
if(limitType == 0):
break
if(limitType == 1):
data = data[data[:,0]>inputFloatNumber(lowLim)]
print("Limit has been set")
break
if(limitType == 2):
data = data[data[:,0]<inputFloatNumber(upLim)]
print("Limit has been set")
break
if(limitType == 3):
data = data[data[:,1]<inputFloatNumber(upLim)]
data = data[data[:,1]>inputFloatNumber(lowLim)]
print("Temperature - limit has been set")
break
if(mainC == 2): #sorts for growthrate
while True:
print("To sorts for GrowthRate, you must now specify filtering limits" )
limitType = inputIntNumber(limitMenu) #allows the user to choose specific limitations for samples
if(limitType == 0):
break
if(limitType == 1):
data = data[data[:,1]>inputFloatNumber(lowLim)]
print("Growthrate limit has been set")
break
if(limitType == 2):
ul = inputFloatNumber(upLim)
data = data[data[:,1]<ul]
print("Growthrate limit has been set")
break
if(limitType == 3):
data = data[data[:,1]<inputFloatNumber(upLim)]
data = data[data[:,1]>inputFloatNumber(lowLim)]
print("Growthrate limit has been set")
break
if(mainC == 3): #sorts for bacteria type
while True: #we are here checking is numbers (types) is within a given range [1..4] or 0 for return
bacType = inputIntNumber(bacteriaString)
if(bacType in [0, 1, 2, 3, 4]):
if(bacType in [1, 2, 3, 4]):
data = data[data[:,2]==bacType] #sorts for the specific type, which is given in bacType
print("Data has been filtered for:", bacList[bacType])
break
else:
print("\nPlease enter a valid statement")
if(mainC == 4): #resets data
data = data0
if(mainC == 5): #prints data
print("Current data is left with the implemented filters:")
print(data)
return(data)
|
9450be73499c4230d9aa71a45c548e86151d06bb | rami6/Algorithm | /01_Python/02_LeetCode/0509_FibonacciNumber.py | 636 | 3.65625 | 4 | """
Problem description
- https://leetcode.com/problems/fibonacci-number/
Result
- Runtime: 16 ms, faster than 100.00% of Python online submissions for Fibonacci Number.
- Memory Usage: 10.9 MB, less than 5.25% of Python online submissions for Fibonacci Number.
"""
class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if N == 0:
return 0
elif N == 1:
return 1
pre_2 = 0
pre_1 = 1
for i in range(2, N + 1):
temp = pre_1
pre_1 += pre_2
pre_2 = temp
return pre_1
|
ea459ed68b4af30d5385610bb22ea53d04e0b535 | shen-huang/selfteaching-python-camp | /19100401/Newonefromhere/d4_exercise_control_flow.py | 466 | 3.71875 | 4 | #使用 for...in 循环打印九九乘法表
for i in range(1,10):
for j in range(1,i+1):
result=i*j
print(f'{i}*{j}={result}',end=' ')
print("")
print('\n')
#使用 while 循环打印九九乘法表并用条件判断把偶数行去掉
i=1
while i <10:
j=1
while i%2 !=0:
while j <=i:
re=i*j
print(f'{i}*{j}={re}',end=' ')
j+=1
else:
print('')
break
i+=1 |
cdaff7909bb7501769f16f0cd3a6a144650b0f43 | Mukesh656165/basics | /mycalculator.py | 520 | 4.03125 | 4 | def add(x,y):
return x+y
def sub(x,y):
return x-y
def multi(x,y):
return x*y
def div(x,y):
return x/y
print('select operation')
print('1. add')
print('2. sub')
print('3. multiply')
print('1. devide')
choice = input('enter your choice 1/2/3/4:')
num1 = int(input('Enter your 1st number:'))
num2 = int(input('Enter your 2nd number:'))
if choice == '1':
print(add(num1,num2))
elif choice =='2':
print(sub(num1,num2))
elif choice =='3':
print(multi(num1,num2))
else:
print(div(num1,num2)) |
1c7e030c2a00dac2db32a5a392cc7883ed97a985 | williamboco21/pythonfundamentals | /FUNDPRO/NestedLoops.py | 94 | 3.515625 | 4 | for number in range(4):
for number_2 in range(3):
print(f"({number}, {number_2})") |
a02c82b753642dad1b0ee5ee805b8a30653e190c | Larissa-Rodrigues/Python3-CursoEmVideo | /Mundo1/ex023.py | 455 | 3.921875 | 4 | #DESAFIO 023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados por unidade, dezena, centena e milhar.
numero = int(input('Informe um número: '))
unidade = numero % 10
dezena = (numero // 10) % 10
centena = (numero // 100) % 10
milhar = numero // 1000
print(f'Analisando o número {numero}')
print(f'Unidade: {unidade}')
print(f'Dezena: {dezena}')
print(f'Centena: {centena}')
print(f'Milhar: {milhar}') |
00bef9b61f4b4356eb4ca468740dc4bee0f0284a | iamkumarvishal/python_source_code | /Chapter_2/variable.py | 453 | 3.875 | 4 | a = "Vishal" # This is a string
b = 'Rohan' # This is a string
c = '''Shubham
is
my
friend
''' # This is used to multiline string
d = 345
e = 54.89
f = True
g = None
# Printing the variables
# print(a)
# print(b)
# print(c)
# print(d)
# print(e)
# print(f)
# print(g)
# Printing the type of variables
# print(type(a))
# print(type(b))
# print(type(c))
# print(type(d))
# print(type(e))
# print(type(f))
# print(type(g))
|
aa03562d3a68a73862c6704b4869616261e2bf73 | luizhmfonseca/Estudos-Python | /AULA 13 - Estrutura de repetição 'for'/exemplo10.py | 122 | 3.953125 | 4 | for c in range(0, 10):
n = int(input('Digite um valor: ')) # INPUT dentro de "FOR" faz ler várias vezess
print('FIM') |
f012bb646f391dc922c9df89dd87390f088e78f3 | celsopa/theHuxley | /HUX - 1057.py | 115 | 3.796875 | 4 | from math import sqrt
c1 = float(input())
c2 = float(input())
hip = sqrt(c1**2 + c2**2)
print("{:.2f}".format(hip)) |
242b24955e8da37e66663f87a898ff2f6a09000c | rehmanalira/Python-Programming | /54 jsON in pYthon.py | 444 | 3.640625 | 4 | # j son is used to storing and exchange of data
# javascript object notation json
# if we have a string in json and want to conver into python we used
#json.load
import json
data='{"name": "RA" , "Age" :"20"}'
y=json.loads(data)
print(y["name"])
# if we have python strings and want to convert into the json we use
#json.dumps
data1={ # this is pythin data
"Name": "RA JUTT",
"Age": "19"
}
l=json.dumps(data1)
print(l) |
88862d6bee5d83dd5f1c656a06a9dc46a5254b10 | thallysrc/lislav | /lislav.py | 2,862 | 3.609375 | 4 | import math
import operator as op
Symbol = str
Number = (int, float)
Atom = (Symbol, Number)
List = list
Exp = (Atom, List)
Env = dict
def standard_env() -> Env:
"An environment with some scheme standard procedures"
env = Env()
env.update(vars(math)) # sin, cos, sqrt, pi ...
env.update({
'+':op.add, '-':op.sub, '*':op.mul, '/':op.truediv,
'>':op.gt, '>':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq,
'abs':abs,
'append':op.add,
'apply':lambda proc, args: proc(*args),
'begin':lambda *x: x[-1],
'car':lambda x: x[0],
'cdr':lambda x: x[1:],
'cons':lambda x,y: [x] + y,
'eq?':op.is_,
'expt':pow,
'equal?':op.eq,
'length':len,
'list':lambda *x: List(x),
'list?':lambda x: isinstance(x, List),
'map':map,
'max':max,
'min':min,
'not':op.not_,
'null?':lambda x: x == [],
'number?':lambda x: isinstance(x, Number),
'print':print,
'procedure?':callable,
'round':round,
'symbol?':lambda x: isinstance(x, Symbol),
})
return env
global_env = standard_env()
def eval(x: Exp, env=global_env) -> Exp:
"Evaluate an expression in an environment."
if isinstance(x, Symbol): # variable reference
return env[x]
elif not isinstance(x, List): # constant number
return x
elif x[0] == 'if': # conditional
(_, test, conseq, alt) = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define': # definition
(_, symbol, exp) = x
env[symbol] = eval(exp, env)
else: # procedure call
proc = eval(x[0], env)
args = [eval(arg, env) for arg in x[1:]]
return proc(*args)
def tokenize(chars: str) -> list:
"convert a string of characters into a list of tokens"
return chars.replace('(', ' ( ').replace(')', ' ) ').split()
def parse(program: str) -> Exp:
"Read a scheme expression from a string"
return read_from_tokens(tokenize(program))
def read_from_tokens(tokens: list) -> Exp:
"Read an expression from a sequence of tokens"
if len(tokens) == 0:
raise SyntaxError('unexpected EOF')
token = tokens.pop(0)
if token == '(':
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return L
elif token == ')':
raise SyntaxError('unexpected )')
else:
return atom(token)
def atom(token: str) -> Atom:
"Numbers become numbers; every other token is a symbol"
try: return int(token)
except ValueError:
try: return float(token)
except ValueError:
return Symbol(token)
program = "(begin (define r 10) (* pi (* r r)))"
print(eval(parse(program)))
|
d51f4334fe0fdf3400ee8f4dd6956617f1b838db | HsinYu7330/HackerRank | /44_validating_email_address_with_a_filter.py | 899 | 3.890625 | 4 | # Validating Email Addresses With a Filter
import re
def fun(s):
if s.count('@') == 1 and s.count('.') == 1:
username = s.split('@')[0]
websitename = s.split('@')[1].split('.')[0]
extension = s.split('@')[1].split('.')[1]
condition1 = len(username) > 0 and bool(re.match(r'^[A-Za-z0-9_-]*$', username))
condition2 = len(websitename) > 0 and bool(re.match(r'^[A-Za-z0-9]*$', websitename))
condition3 = len(extension) <= 3
if condition1 and condition2 and condition3:
return True
else:
return False
else:
return False
def filter_mail(emails):
return list(filter(fun, emails))
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.append(input())
filtered_emails = filter_mail(emails)
filtered_emails.sort()
print(filtered_emails)
|
94abf79bb7fdcfa82988f04419e0a5e9a7c7acf3 | jejabour/Python_Learning | /errors.py | 752 | 4.34375 | 4 | #This program is going to be an example to deal with errors
#This is an example of: ValueError: invalid literal for int() with base 10
#Enter letters instead of numbers here
# age = int(input('Age: '))
# print(age)
#To fix:
# try:
# age = int(input('Age: '))
# print(age)
# except ValueError:
# print('Invalid value')
#Example of :ZeroDivisionError
#Enter 0 for the age
# try:
# age = int(input('Age: '))
# income = 20000
# risk = income / age
# print(age)
# except ValueError:
# print('Invalid value')
#To fix
try:
age = int(input('Age: '))
income = 20000
risk = income / age
print(age)
except ZeroDivisionError:
print('Age cannot be 0.')
except ValueError:
print('Invalid value')
|
880bf6d7055999633120124db122e806c4f016c6 | keonwoo-Park/efp | /chapter4/p18.py | 1,219 | 4.125 | 4 | #- coding:utf-8 -*-
#!/usr/bin/env python
import sys
temperature_int = 0
def version_input(sentance):
return input(sentance) if sys.version_info >= (3,0) else raw_input(sentance)
def type_checking(temperature):
global temperature_int
try:
temperature_int = int(temperature)
if temperature_int < 0:
return False
return True
except ValueError:
return False
if __name__ == "__main__":
print("Press C to convert from Fahrenheit to Celsius.\nPress F to convert from Celsius to Fahrenheit.")
choice = version_input("Your choice: ")
temperature = version_input("Please enter the temperature in Fahrenheit: ")
if type_checking(temperature) == False:
print("Plese enter correct integer or enter an integer greater than 0.")
sys.exit()
if choice == "C" or choice =="c":
exchange_temperature = (temperature_int - 32)*5/9
print("The temperature in Celsius is %d."% exchange_temperature)
elif choice == "F" or choice =="f":
exchange_temperature = (temperature_int * 9 /5)+32
print("The temperature in Fahrenheit is %d."% exchange_temperature)
else:
print("Please enter C or F.")
|
9b609495634be5d56b696078d101d43db4442961 | davudduran/CodecraftCS50 | /hafta6/task6-ceasar.py | 1,901 | 3.5625 | 4 | # kütüphaneleri çağırıyoruz
from cs50 import get_string
from sys import argv
def main():
#kullanıcıdan anahtar almak için get_key fonksiyonunu çağırıyoruz
key = get_key()
# kullanıcıdan şifrelenecek yazıyı almak için get_plaintext fonksiyonunu çağırıyoruz
plaintext = get_plaintext("plaintext: ")
# şifrelenmiş mesajı printliyoruz, şifrelenmiş mesaja ulaşmak için
# encipher_text fonskiyonunu çağırıyoruz
print("ciphertext:", encipher_text(plaintext, key))
def get_key():
# Programın tam olarak 1 girdi ile çalıştırıldığını kontrol et
# eğer doğru çalıştırıldıysa onu bir integer olarak al
if len(argv) == 2:
return int(argv[1])
# eğer yanlış çalıştırıldıysa, doğrusunu göster.
else:
print("Usage: python caesar.py key")
exit(1)
# kullanıcıdan normal yazıyı bir string olarak al
def get_plaintext(prompt):
return get_string(prompt)
# Yazıyı şifreler
# Büyük-küçük harf düzenini değiştirmez
# Alfabeden olmayan karakterler aynı kalır
# ord() fonksiyonu bir char(karakter) değeri alır ve ascii(integer) değerini geri döndürür
# chr() fonksiyonu bir ascii değeri(integer olarak) alır ve char değerini döndürür
def encipher_text(text, key):
# sonra doldurmak üzere boş bir String(yazı) değişkeni oluşturuyoruz.
str = ""
for char in text:
if not char.isalpha():
# alfabe karakteri değilse doğrudna ekle
str += char
if char.isupper():
# Büyük harf ise, ascii değeri = 65
str += chr(((ord(char) - 65) + key) % 26 + 65)
if char.islower():
# Küçük harf ise, ascii değeri = 97
str += chr(((ord(char) - 97) + key) % 26 + 97)
# şifreleme tamamlandı değeri geri döndürüyoruz!
return str
main()
|
f0d805fa862ecd0becdf50e4d61ad8697c531703 | haidfs/LeetCode | /Hot100/求众数.py | 440 | 3.609375 | 4 | from collections import defaultdict
class Solution:
def majorityElement(self, nums: [int]) -> int:
word_count = defaultdict(lambda: 0)
for i in nums:
word_count[i] += 1
word_count = dict(sorted(word_count.items(), key=lambda x: x[1], reverse=True))
return list(word_count.keys())[0]
if __name__ == '__main__':
s = Solution()
arr = [1, 2, 3, 1, 1]
print(s.majorityElement(arr)) |
426ebb2060615eba959221ac190e0451f3025f23 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4178/codes/1679_1105.py | 656 | 3.609375 | 4 | # Teste seu código aos poucos. Não teste tudo no final, pois fica mais difícil de identificar erros.
# Ao testar sua solução, não se limite ao caso de exemplo. Teste as diversas possibilidades de saída
x = input("Sua casa: ").lower()
if (x == "lobo"):
msg = "Stark"
elif (x == "leao"):
msg = "Lennister"
elif (x == "veado"):
msg = "Baratheon"
elif (x == "dragao"):
msg = "Targaryen"
elif (x == "rosa"):
msg = "Tyrell"
elif (x == "sol"):
msg = "Martell"
elif (x == "lula"):
msg = "Greyjoy"
elif (x == "esfolado"):
msg = "Bolton"
elif (x == "turta"):
msg = "Tully"
else:
msg = "Brasao invalido"
print ("Entrada: ", x)
print ("Casa: ",msg)
|
e17728273de243eb67c8a63be20641a6331cdfa9 | game-Tnadon/-1 | /Lab3.py | 864 | 3.90625 | 4 | '''
print("student ID 62055008")
value[] = {60, 100, 120};
weight[] = {10, 20, 30};
w = 50;
solution: 220
---------------------------------
value[] = {2, 5, 10, 5};
weight[] = {20, 30, 10, 50};
w = 50;
'''
def knapSack(W , wt , val , n):
# Base Case
if n == 0 or W == 0 :
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n-1] > W):
return knapSack(W , wt , val , n-1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1),
knapSack(W , wt , val , n-1))
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print (knapSack(W , wt , val , n))
|
cc9f1faaa3c9be19b614138e6ebfd2b8f3f3b2ee | ongwech/andela-crackthecodechallenge | /shooting_range_puzzle.py | 1,055 | 3.90625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'isWin' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER n
# 2. STRING setup
#
def isWin(n, setup):
# return WIN if you win otherwise return LOSE
win = [0]
for n in range(1, 301):
s = set()
for a in range(n // 2 + 1):
s.add(win[a] ^ win[n - 1 - a])
s.add(win[a] ^ win[n - 2 - a])
m = 0
while m in s:
m += 1
win.append(m)
def solve(setup_x):
r = 0
for s in setup_x.split('X'):
r ^= win[len(s)]
return "WIN" if r else "LOSE"
for _ in range(n):
return (solve(setup))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
setup = input()
result = isWin(n, setup)
fptr.write(result + '\n')
fptr.close() |
2b49d84cce36d3b3d6bbbb8470b71da6d6c68b6a | vishalbelsare/jubakit | /example/regression_csv.py | 1,653 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
"""
Using Regression and CSV file
==================================================
This is a simple example that illustrates:
* How to load CSV files and convert int into Jubakit dataset.
* Training the regression using the dataset.
* Getting regression result.
"""
import numpy as np
from jubakit.regression import Regression, Schema, Dataset, Config
from jubakit.loader.csv import CSVLoader
# Load a CSV file.
loader = CSVLoader('wine.csv')
# Define a Schema that defines types for each columns of the CSV file.
schema = Schema({
'quality': Schema.TARGET,
}, Schema.NUMBER)
# Create a Dataset
dataset = Dataset(loader, schema).shuffle()
n_samples = len(dataset)
n_train_samples = int(n_samples * 0.75)
# Create a Regression Service
cfg = Config.default()
regression = Regression.run(cfg)
print("Started Service: {0}".format(regression))
# Train the regression using the first half of the dataset.
train_ds = dataset[:n_train_samples]
print("Training...: {0}".format(train_ds))
for _ in regression.train(train_ds): pass
# Test the regression using the last half of the dataset.
test_ds = dataset[n_train_samples:]
print("Testing...: {0}".format(test_ds))
mse, mae = 0, 0
for (idx, label, result) in regression.estimate(test_ds):
diff = np.abs(label - result)
mse += diff**2
mae += diff
mse /= len(test_ds)
mae /= len(test_ds)
# Stop the regression.
regression.stop()
# Print the result
print('Root Mean Squared Error: {0:.3f}'.format(np.sqrt(mse)))
print('Mean Absolute Error: {0:.3f}'.format(mae))
|
70306573f71137056b8d6f9d6e40f473c7c0c6aa | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_06_STRING/fabio06_07_conjugar_verbo_regular.py | 2,874 | 4.25 | 4 | def main():
verbo = input('Digite um verbo regular terminado em -ER: ')
print('Primeira pessoa do singular: EU %s'%verbo_primeira_singular(verbo))
print('Segunda pessoa do singular: TU %s'%verbo_segunda_singular(verbo))
print('Terceira pessoa do singular: ELE %s'%verbo_terceira_singular(verbo))
print('Primeira pessoa do plural: NÓS %s'%verbo_primeira_plural(verbo))
print('Segunda pessoa do plural: VÓS %s'%verbo_segunda_plural(verbo))
print('Terceira pessoa do plural: ELES %s'%verbo_terceira_plural(verbo))
def verbo_primeira_singular(verbo):
i = 0
novo_verbo = ''
while i < len(verbo):
if (verbo[i]=='e') and (verbo[i+1]=='r'):
novo_verbo += 'o'
elif (verbo[i]=='r') and (verbo[i-1]=='e'):
novo_verbo += ''
else:
novo_verbo += verbo[i]
i += 1
return novo_verbo
def verbo_segunda_singular(verbo):
i = 0
novo_verbo = ''
while i < len(verbo):
if (verbo[i]=='r') and (verbo[i-1]=='e'):
novo_verbo += 's'
else:
novo_verbo += verbo[i]
i += 1
return novo_verbo
def verbo_terceira_singular(verbo):
i = 1
novo_verbo = ''
anterior = ''
while i <= len(verbo):
caractere = ord(verbo[i-1])
# 3 pessoa do singular
if (caractere==82 or caractere==114) and\
(anterior==69 or anterior==101):
novo_verbo = novo_verbo + ''
else:
str_caractere = chr(caractere)
novo_verbo = novo_verbo + str_caractere
anterior = caractere
i += 1
return novo_verbo
def verbo_primeira_plural(verbo):
i = 0
novo_verbo = ''
while i < len(verbo):
if (verbo[i]=='e') and (verbo[i+1]=='r'):
novo_verbo += 'emos'
elif (verbo[i]=='r') and (verbo[i-1]=='e'):
novo_verbo += ''
else:
novo_verbo += verbo[i]
i += 1
return novo_verbo
def verbo_segunda_plural(verbo):
i = 0
novo_verbo = ''
while i < len(verbo):
if (verbo[i]=='e') and (verbo[i+1]=='r'):
novo_verbo += 'eis'
elif (verbo[i]=='r') and (verbo[i-1]=='e'):
novo_verbo += ''
else:
novo_verbo += verbo[i]
i += 1
return novo_verbo
def verbo_terceira_plural(verbo):
i = 0
novo_verbo = ''
while i < len(verbo):
if (verbo[i]=='e') and (verbo[i+1]=='r'):
novo_verbo += 'em'
elif (verbo[i]=='r') and (verbo[i-1]=='e'):
novo_verbo += ''
else:
novo_verbo += verbo[i]
i += 1
return novo_verbo
if __name__ == '__main__':
main()
|
6f2a7401f64bc854bdd2255ffc99ebb525367968 | 3ntropia/pythonDojo | /functions/function9/operateDate.py | 1,391 | 4.0625 | 4 | """
Escribir una funcion diasiguiente(…) que reciba como parametro una fecha cualquiera
expresada por tres enteros (correspondientes al día, mes y año) y calcule y
devuelva tres enteros correspondientes el día siguiente al dado.
Utilizando esta funcion, desarrollar programas que permitan:
a. Sumar N dias a una fecha.
b. Calcular la cantidad de dias existentes entre dos fechas cualesquiera.
"""
from functions.function2 import validDate
def next_date(day, month, year):
if validDate.is_date_valid(day, month, year):
day += 1
if day > 28 and month == 2:
if not validDate.is_leap_year(year):
day = 1
month += 1
if day == 31:
if month == 2 or month == 4 or month == 6 or month == 8 or month == 10:
day = 1
month += 1
elif day > 31:
day = 1
month += 1
if month > 12:
month = 1
year += 1
return day, month, year
def add_n_days(day, month, year, number):
for x in range(number):
(day, month, year) = next_date(day, month, year)
return day, month, year
def diff_dates(day, month, year, day2, month2, year2):
counter = 0
while day != day2 or month != month2 or year != year2:
(day, month, year) = next_date(day, month, year)
counter += 1
return counter
|
ad3c637374e4328fc7b8b8b5af5b1fd9a55086cb | SkanderSP/2020-hackathon-zero-python-retos-pool-8 | /tests/kata1/rps.py | 645 | 3.71875 | 4 | import random
_piedra='piedra'.lower();
_papel='papel'.lower();
_tijera='tijeras'.lower();
posibles=(_piedra,_papel,_tijera)
def quienGana(a,b):
a=a.lower()
b=b.lower()
print(a)
print(b)
try:
if (posibles.index(a)>=0) and (posibles.index(b)>=0):
if (a==b):
return 'Empate!'
elif (a==_piedra and b==_tijera) or (a==_papel and b==_piedra) or (a==_tijera and b==_papel):
return 'Ganaste!'
else:
return 'Perdiste!'
except:
return '????'
if __name__== '__main__':
# X=input('Jugador 1:')
ia=random.choice(posibles)
yo=input('Eleccion:')
print(quienGana(yo,ia))
|
65e5d93f724ed56ad8ed17237347f3abfa9893df | arbalest339/myLeetCodeRecords | /offer53search.py | 445 | 3.609375 | 4 | class Solution:
def search(self, nums, target: int) -> int:
if target in nums:
start = nums.index(target)
else:
return 0
res = 0
i = start
while i < len(nums) and nums[i] == target:
res += 1
i += 1
return res
if __name__ == "__main__":
solution = Solution()
nums = [5, 7, 7, 8, 8, 10]
target = 8
solution.search(nums, target)
|
c9b715c77018cd2389cf9ab767e91c6b64cc8044 | Minari766/study_python | /Paiza/Rank_D/paizad041_本棚選び.py | 168 | 3.578125 | 4 | # coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!
a, b, c = input().split()
if int(b)*int(c) >= int(a):
print("OK")
else:
print("NG") |
f23c6cc0555540084db4304a9073f7920e10692f | ChunaLiu/biosys-analytics | /assignments/03-python-grad/grid.py | 990 | 3.84375 | 4 | #!/usr/bin/env python3
"""
Author : chunanliu
Date : 2019-02-04
Purpose: Rock the Casbah
"""
import os
import sys
# --------------------------------------------------
def main():
num = sys.argv[1:]
if len(num) != 1:
print('Usage: {} NUM'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
i = int(num[0])
if not 2 <= i <=9:
print('NUM ({}) must be between 1 and 9'.format(i))
sys.exit(1)
else:
grid_list = list(range(1, i**2+1))
grid = [grid_list[x:x+i] for x in range(0, len(grid_list), i)]
# generate i*i matrix
#method 1:
for row in grid:
print(''.join((' '*(3-len(str(item)))+str(item)) for item in row))
# total length of each integer is 3
#method 2:
# for item in row:
# print('{:3}'.format(item), end='')
# print()
#method 3:
#divde i == 0
# --------------------------------------------------
main()
|
c838d36155c8d1a4bc35edf25f5404a5df8ead04 | AyuOrniThrONE/Patterns | /Python/Geometrical_Patterns/Pattern3.py | 216 | 4 | 4 | """
Pattern
1 1 1 1
2 2 2
3 3
4
n = 4
"""
print("Enter the number of rows")
n=int(input())
print("Here is the pattern")
for i in range(1,n+1):
for j in range(i,n+1):
print(i,end=" ")
print("\n") |
7edc88c9cc20a82163d66c8fe6521aa44e594d7c | lsjsss/PythonClass | /PythonBookAdditional/第03章 选择与循环/code/例3_21.py | 1,294 | 3.625 | 4 | #这个循环用来保证必须输入大于2的整数作为评委人数
while True:
try:
n = int(input('请输入评委人数:'))
if n <= 2:
print('评委人数太少,必须多于2个人。')
else:
#如果输入大于2的整数,就结束循环
break
except:
Pass
#用来保存所有评委的打分
scores = []
for i in range(n):
#这个while循环用来保证用户必须输入0到100之间的数字
while True:
try:
score = input('请输入第{0}个评委的分数:'.format(i+1))
#把字符串转换为实数
score = float(score)
#用来保证输入的数字在0到100之间
assert 0<=score<=100
scores.append(score)
#如果数据合法,跳出while循环,继续输入下一个评委的得分
break
except:
print('分数错误')
#计算并删除最高分与最低分
highest = max(scores)
lowest = min(scores)
scores.remove(highest)
scores.remove(lowest)
#计算平均分,保留2位小数
finalScore = round(sum(scores)/len(scores), 2)
formatter = '去掉一个最高分{0}\n去掉一个最低分{1}\n最后得分{2}'
print(formatter.format(highest, lowest, finalScore))
|
fa337473b7329563b22e957b35435c7ec21186d3 | NCRivera/COP1990-Introduction-to-Python-Programming | /Assignments/OCT22/IncClass02_OCT22.py | 623 | 4.0625 | 4 | def main():
# local variables
num1 = 0.0
num2 = 0.0
sum = 0.0
# get num1
num1 = float(input("Enter a number: "))
# print number
showNumber(num1)
# get num2
num2 = float(input("Enter a number: "))
# print number
showNumber(num2)
sum = calculate_the_sum_show(num1, num2)
print("The sum of the numbers", num1,"+",num2, "is", sum)
# showNumber function displays the number.
def showNumber(num1):
print("The number is", num1)
def calculate_the_sum_show(number_1, number_2):
sum_t = number_1 + number_2
return sum_t
main() |
42b231d154b6f87e07f0387c8de96f42e171ac39 | tanya1019/CodeInc | /Python/Fibonacci_Series.py | 259 | 3.59375 | 4 | # Fibonacci Series
def Fib(n):
numbers = [0, 1]
if numbers[-1] < n:
return numbers.append(numbers[-1] + numbers[-2])
return numbers
def Sum(n):
a = Sum(n)
b = [t fir t in range Fib if t%2 == 0]
return b
result = Sum(400000) |
36596b0a81e91cd9828b081aa38ef9d79be91f2f | pramodswainn/LeetCode | /Week6/725.py | 2,194 | 3.515625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
count=0
temp=bienchay=ListNode(0)
current1=current2=current3=root
while current1:
count+=1
current1=current1.next
result=[]
if count==0:
for i in range(0,k):
result.append(current2)
elif count<=k:
while current2:
temp.next=ListNode(current2.val,None)
result.append(temp.next)
current2=current2.next
if count<k:
for i in range(0,k-count):
result.append(current2)
else:
dic={}
dic[count//k+1]=count-count//k*k
dic[count//k]=k-(count-count//k*k)
count1=0
while current2 and dic[count//k+1]>0:
if count1==count//k+1:
bienchay.next=None
result.append(temp.next)
temp=bienchay=ListNode(0)
count1=0
dic[count//k+1]-=1
bienchay.next=ListNode(current2.val,None)
count1+=1
current2=current2.next
bienchay=bienchay.next
while current2 and dic[count//k]>0:
if count1==count//k:
bienchay.next=None
result.append(temp.next)
temp=bienchay=ListNode(0)
count1=0
dic[count//k]-=1
bienchay.next=ListNode(current2.val,None)
count1+=1
current2=current2.next
bienchay=bienchay.next
bienchay.next=None
result.append(temp.next)
return result |
87754374e16786f7d672b0c49c0365f95a0dc15c | navekazu/sandbox-python | /04 other control syntax/01_if.py | 153 | 3.984375 | 4 | # coding:utf-8
# if文
x=int(raw_input("Please enter an integer: "))
if x==0:
print '0'
elif x<10:
print '10未満'
else:
print '10以上'
|
0fa4821c10c21c42f791f71bce8e606ef3c22125 | JRobayo99/Talleres-de-algotimos | /Taller Estructuras de Control Secuenciales/Ejercicio_10.py | 634 | 3.75 | 4 | chel= float(input("La catidad de chelines para saber su precio en pesetas: "))
dracg= float(input("La cantida de dragmas griegos para saber su precion en francos: "))
psets= float (input("la cantidad de pesetas para su tasas de cambio en dolares y liras italianas es: "))
pst= chel*956.871
fr = (dracg*88.507)/(100*20.110)
lrt=(psets*100)/9.289
USD = psets/122.499
print("De chelines a pesetas son: "+str(pst), " Pesetas")
print ("De dragmas a francos so: " "{:.3F}".format(fr), " Francos FRA")
print ("De pesetas a liras italianas es: ""{:.3F}".format(lrt), " Liras ITA")
print ("Pesetas a dolores es: ""{:.3F}".format(USD), " USD") |
4a27973f45a09e6306ac05573b24f09a4ed1f6e7 | sshashan08/01-Basic-DS | /C7.py | 975 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 09:53:16 2016
@author: shashank
"""
import math
BilledAmt = 1000
TipPercent = 10
TotalDue = ((100+TipPercent)/100)*BilledAmt
print("Billed Amount: ", BilledAmt, "\t Tip %: ", TipPercent, "%", "Total Amount: ",TotalDue)
mySchool = "I Study at ASU"
print(mySchool)
for i in range(0,math.floor(len(mySchool)/2),1):
print(mySchool[i], end="")
print("\n")
for i in range(math.floor(len(mySchool)/2)+1,len(mySchool),1):
print(mySchool[i], end="")
print("\n")
print(mySchool[::-1])
print("".join(reversed(mySchool)))
print("\n")
print(mySchool[::1])
print(mySchool.find("ASU"))
x1 = 1
y1 = 2
x2 = 10
y2 = 20
DistanceMhtn = abs(x1 - x2) + abs(y1 - y2)
DistanceEuc = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
DistanceMink = math.pow((abs((x1 - x2)**3) + abs((y1 - y2)**3)),(1/3))
print("Manhattan Distance: ", DistanceMhtn)
print("Manhattan Distance: ", DistanceEuc)
print("Manhattan Distance: ", DistanceMink) |
1c78953944dad1e5cb75c64237ffee2330bcce8f | aadhityasw/Competitive-Programs | /questions/q32_even_matrix/q32.py | 1,085 | 3.78125 | 4 | # Codechef June2020
# EVENM
# Even Matrix
# https://www.codechef.com/problems/EVENM
"""
Chef has an integer N and he wants to generate a matrix M with N rows (numbered 1 through N) and N columns (numbered 1 through N). He thinks that M would be delicious if:
Each element of this matrix is an integer between 1 and N2 inclusive.
All the elements of the matrix are pairwise distinct.
For each square submatrix containing cells in rows r through r+a and in columns c through c+a (inclusive) for some valid integers r, c and a≥0:
Mr,c+Mr+a,c+a is even
Mr,c+a+Mr+a,c is even
Can you help Chef generate a delicious matrix? It can be proved that a solution always exists. If there are multiple solutions, you may find any one.
"""
test = int(input())
for t in range(test) :
n = int(input())
p = 1
c = 1
r = 0
while (p <= (n*n)) :
if r%2 == 0 :
print(p, end=" ")
else :
print(((r+1)*n)-c, end=" ")
if p%n == 0 :
print()
r += 1
c = 0
else :
c += 1
p += 1
|
b6ca87e4fa01f86306c0c1a1df7d83efe31206e6 | bharathram1225/python-Lab-programs | /inheritance/hierarchical.py | 1,339 | 4.0625 | 4 | class Student:
def __init__(self,usn,name,age):
self.usn = usn
self.name = name
self.age = age
def getdata(self):
self.usn = int(input("Enter the USN:"))
self.name = input("Enter the Name:")
self.age = int(input("Enter the Age:"))
def displaystu(self):
print("The student name is ",self.name," with an age ",self.age," also has usn",self.usn);
class pgstudent(Student):
def __init__(self,sem = 0 ,fees = 0,stipend = 0):
self.sem = sem
self.fees = fees
self.stipend = stipend
def pggetdata(self):
self.sem = int(input("Enter the sem:"))
self.fees = int(input("Enter the fees:"))
self.stipend = int(input("Enter the stipend:"))
def display(self):
print("The student sem is ",self.sem," with an fees ",self.fees," also has stipend",self.stipend);
class ugstudent(Student):
def __init__(self,sem = 0,fees = 0,stipend = 0):
self.sem = sem
self.fees = fees
self.stipend = stipend
def uggetdata(self):
self.sem = int(input("Enter the sem:"))
self.fees = int(input("Enter the fees:"))
self.stipend = int(input("Enter the stipend:"))
def display(self):
print("The UG student sem is ",self.sem," with an fees ",self.fees," also has stipend",self.stipend);
pg = pgstudent()
pg.pggetdata()
pg.display()
ug = ugstudent()
ug.uggetdata()
ug.display()
pg.getdata()
pg.displaystu()
|
7fa203254742550c112294b7c9689230f71fb388 | restlesspuppet/PracticePython | /04-Divisors.py | 248 | 3.90625 | 4 | ##############
# Divisors
# by RestlessPuppet
# 11-9-19
###############
num = int(input("Enter a number: "))
i = 1
l = []
while i <= num:
if num % i ==0:
l.append(i)
i+=1
print(str(l)+" are all divisible by " + str(num))
|
e0c0a4046de7fb3d4437aa8d7f6c952143831ccf | Isha5/PyProj | /dictionaries.py | 2,598 | 4.125 | 4 | # add_ten function :
def add_ten(my_dictionary):
for key in my_dictionary:
my_dictionary[key] += 10
return my_dictionary
print(add_ten({1:5, 2:2, 3:3}))
# prints {1:15, 2:12, 3:13}
print(add_ten({10:1, 100:2, 1000:3}))
# prints {10:11, 100:12, 1000:13}
# sum_of_even_keys function here:
def sum_even_keys(my_dictionary):
sum = 0
for key in my_dictionary:
if key % 2 == 0:
sum += my_dictionary[key]
return sum
print(sum_even_keys({1:5, 2:2, 3:3}))
# prints 2
print(sum_even_keys({10:1, 100:2, 1000:3}))
# prints 6
def sum_values(my_dictionary ):
sum = 0
for values in my_dictionary:
sum += my_dictionary[values]
return sum
print(sum_values({"milk":5, "eggs":2, "flour": 3}))
# prints 10
print(sum_values({10:1, 100:2, 1000:3}))
# prints 6
#This function returns a list of all values in the dictionary that are also keys.
def values_that_are_keys(my_dictionary):
keys = my_dictionary.keys()
vals = my_dictionary.values()
common = []
for k in keys:
if k in vals:
common.append(k)
return common
#calculates the frequency of words
def frequency_dictionary (words):
dict={}
for w in words:
if w not in dict:
dict[w] = 1
else:
dict[w] += 1
return dict
print(frequency_dictionary(["apple", "apple", "cat", 1]))
# prints {"apple":2, "cat":1, 1:1}
print(frequency_dictionary([0,0,0,0,0]))
# prints {0:5}
#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# word_length_dictionary function here:
def word_length_dictionary(words):
dict = {}
for w in words:
dict[w] = len(w)
return dict
print(word_length_dictionary(["apple", "dog", "cat"]))
# should print {"apple":5, "dog": 3, "cat":3}
print(word_length_dictionary(["a", ""]))
# should print {"a": 1, "": 0}
#************************************************************
# max_key function here:
def max_key(my_dictionary):
largest_key = float("-inf")
largest_value = float("-inf")
for key, value in my_dictionary.items():
if value > largest_value:
largest_value = value
largest_key = key
return largest_key
print(max_key({1:100, 2:1, 3:4, 4:10}))
# should print 1
print(max_key({"a":100, "b":10, "c":1000}))
# should print "c"
#
##########################################################
# unique_values function
def unique_values(my_dictionary):
unique_sum=[]
for val in my_dictionary.values():
if val not in unique_sum:
unique_sum.append(val)
return len(unique_sum)
print(unique_values({0:3, 1:1, 4:1, 5:3}))
# should print 2
print(unique_values({0:3, 1:3, 4:3, 5:3}))
# should print 1
|
4b591002cba5476b7c691657f0f34eb2a154690e | ffcccc/MachineLearning | /preProcess.py | 3,766 | 4.09375 | 4 | import numpy as np
import sys
'''
Function: Normalization
Description: Normalize input data. For vector x, the normalization process is given by
normalization(x) = (x - min(x))/(max(x) - min(x))
Input: data dataType: ndarray description: input data
Output: normdata dataType: ndarray description: output data after normalization
'''
def Normalization(data):
# get the max and min value of each column
minValue = data.min(axis=0)
maxValue = data.max(axis=0)
diff = maxValue - minValue
# normalization
mindata = np.tile(minValue, (data.shape[0], 1))
normdata = (data - mindata) / np.tile(diff, (data.shape[0], 1))
return normdata
'''
Function: Standardization
Description: Standardize input data. For vector x, the normalization process is given by
Standardization(x) = x - mean(x)/std(x)
Input: data dataType: ndarray description: input data
Output: standarddata dataType: ndarray description: output data after standardization
'''
def Standardization(data):
# get the mean and the variance of each column
meanValue = data.mean(axis=0)
varValue = data.std(axis=0)
standarddata = (data - np.tile(meanValue, (data.shape[0], 1))) / np.tile(varValue, (data.shape[0], 1))
return standarddata
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: x1 dataType: ndarray description: input vector
x2 dataType: ndarray description: input vector
Output: d dataType: float description: distance between input vectors
'''
def calculateDistance(distance_type, x1, x2):
if distance_type == "Euclidean":
d = np.sqrt(np.sum(np.power(x1 - x2, 2), axis=1))
elif distance_type == "Cosine":
d = np.dot(x1, x2)/(np.linalg.norm(x1)*np.linalg.norm(x2))
elif distance_type == "Manhattan":
d = np.sum(x1 - x2)
else:
print("Error Type!")
sys.exit()
return d
'''
Function: calcuateDistance
Description: calcuate the distance between input vector and train data
Input: input dataType: ndarray description: input vector
traind_ata dataType: ndarray description: data for training
train_label dataType: ndarray description: labels of train data
k dataType: int description: select the first k distances
Output: prob dataType: float description: max probability of prediction
label dataType: int description: prediction label of input vector
'''
# def calculateDistance(input, train_data, train_label, k):
# train_num = train_data.shape[0]
# # calcuate the distances
# distances = np.tile(input, (train_num, 1)) - train_data
# distances = distances**2
# distances = distances.sum(axis=1)
# distances = distances**0.5
# # get the labels of the first k distances
# disIndex = distances.argsort()
# labelCount = {}
# for i in range(k):
# label = train_label[disIndex[i]]
# labelCount[label] = labelCount.get(label, 0) + 1
# prediction = sorted(labelCount.items(), key=op.itemgetter(1), reverse=True)
# label = prediction[0][0]
# prob = prediction[0][1]/k
# return label, prob
'''
Function: calculateAccuracy
Description: show detection result
Input: test_data dataType: ndarray description: data for test
test_label dataType: ndarray description: labels of test data
Output: accuracy dataType: float description: detection accuarcy
'''
def calculateAccuracy(test_label, prediction):
test_label = np.expand_dims(test_label, axis=1)
# prediction = self.prediction
accuracy = sum(prediction == test_label)/len(test_label)
return accuracy
|
9ed31b22807d011a09e33e8d6e07b35275c5d0c5 | AbhinavUtkarsh/Code-Chef | /Chef and Feedback/Chef and Feedback.py | 219 | 3.671875 | 4 | #https://www.codechef.com/problems/ERROR
for i in range(int(input())):
string=input()
if ("101" in string):
print("Good")
elif ("010" in string):
print("Good")
else:
print("Bad") |
eb56514cfd0823b0c014bb7ed40c13d320df3c08 | taariksiers/udemy-complete-python-bootcamp | /Section10_ErrorsAndExceptions/homework.py | 790 | 3.9375 | 4 | print('Problem One:')
for i in ['a', 'b', 'c']:
try:
print(i**2)
except TypeError:
print(f'Incorrect type provided \'{i}\'')
print(f'\n{"-" * 100}\nProblem Two:')
x = 5
y = 0
try:
z = x/y
except ZeroDivisionError:
print(f'Cannot divide {x} by {y}')
finally:
print('All Done.')
print(f'\n{"-" * 100}\nProblem Three:')
def ask():
"""Take a number(type int) as input and square it"""
result = 0
while True:
try:
num = int(input('Please provide a number: '))
except:
print('An error occured! Please try again!')
continue
else:
result = num**2
break
finally:
pass
return result
result = ask()
print(f'Squared = {result}')
# help(ask)
|
919aec3d5314a12fe2f2f98a34786873e5ab7767 | PedroHenriqueSimoes/Exercicios-Python | /Mundo 2/File 058.py | 378 | 3.875 | 4 | from random import randint
cpu = randint(0, 10)
jog = (int(input('Tente advinhar um valor de 0 - 10: ')))
tent = 1
while jog != cpu:
if jog > cpu:
jog = (int(input('Menos, tente outra vez: ')))
elif jog < cpu:
jog = (int(input('Mais, tente outra vez: ')))
tent = tent + 1
print('Isso, pensei no numero {}, você tentou {} vezes !'.format(cpu, tent))
|
995f0c874bb93e30a3e657afa6004d28d31c6189 | limetree-indigo/allForAlgolithmWithPython | /Part2 재귀 호출/06 하노이의 탑 옮기기/p06-1-hanoi.py | 829 | 3.703125 | 4 | # 하노이의 탑
# 입력: 옮기려는 원반의 개수 n
# 옮길 원반이 현재 있느 출발점 기둥 from_pos
# 원반을 옮길 도착적 기둥 to_pos
# 옮기는 과정에서 사용할 보조 기둥 axu_pos
# 출력: 원반을 옮기는 순서
def hanoi(n, from_pos, to_pos, aux_pos):
if n == 1:
print(from_pos, "->", to_pos)
return
# 원반 n-1개를 aux_pos로 이동(to_pos를 보조 기둥으로)
hanoi(n-1, from_pos, aux_pos, to_pos)
# 가장 큰 원반을 목적지로 이동
print(from_pos, "->", to_pos)
# aux_pos에 있는 원반 n-1개를 목적지로 이동(from_pos를 보조 기둥으로)
hanoi(n-1, aux_pos, to_pos, from_pos)
print("n=1")
hanoi(1, 1, 3, 2)
print("-"*10)
print("n=2")
hanoi(2, 1, 3, 2)
print("-"*10)
print("n=3")
hanoi(3, 1, 3, 2)
|
f1e8fb8c09ab653526a6a728a7dec4f886f05b76 | solomonmartinez/python | /practice.py | 1,251 | 3.578125 | 4 | class leCustomer:
def __init__ (self, first, last, balance, password):
self.first = first
self.last = last
self.balance = balance
self.password = password
def printName(self):
return self.first + " "+ self.last
def balance(self):
return self.balance + ""
def deposit(self):
x = int(raw_input("How much do you want to deposit into your account?"))
return self.balance + x
def withdrawal(self):
x = int(raw_input("How much do you want to withdraw from your account?"))
return self.balance - x
def changePassword(self):
newPass = raw_input("Put in new password.")
self.password = newPass
class Investor(Employee):
def __init__ (self, first, last, balance, password, stock=None):
super(Investor, self).__init__(first, last, balance, password)
if stock == None:
stock = {}
else:
stock = None
inv1 = Investor( first, last, balance, password, {"amazon": 50000, "apple": 30000})
c1 = leCustomer("Solomon", "Martinez", 1000000, "kittenmitten")
#print c1.printName()
#print c1.balance()
#print c1.deposit()
#print c1.withdrawal()
#print c1.changePassword()
#print c1.password
|
c24ba9560e2948ec620f80b8e9b9cef71fc504de | GGXH/coding | /dynamic_programming/recurs_mult/sol.py | 345 | 3.90625 | 4 | def recursMult(a, b):
if b > a:
return recursMult(b, a)
if b == 0:
return 0
if b == 1:
return a
adda = 0
if b & 1 == 1:
adda = a
b >>= 1
halfres = recursMult(a, b)
return halfres + halfres + adda
if __name__ == "__main__":
print recursMult(3, 2)
print recursMult(30, 2)
print recursMult(5, 11)
|
697c2fb537c91651b6eae46cf7eda7e7b58c2d79 | AlexandrSB/Mandala | /main.py | 1,719 | 3.71875 | 4 | # You can edit this code and run it right here in the browser!
# First we'll import some turtles and shapes:
from turtle import *
from shapes import *
# Create a turtle named Tommy:
tommy = Turtle()
tommy.shape("turtle")
tommy.speed(150)
# Draw Romb
n = 20
fill_color = {
1 : "red",
2 : "darkblue",
3 : "green",
4 : "yellow",
5 : "blue",
6 : "cyan",
7 : "pink",
8 : "orange",
9 : "violet" ,
0 : "red"
}
def list_gen(*args):
a = args[::-1]
return args+a
step = list_gen(2, 1, 1, 1, 1, 9, 8, 4)
step1 = []
tommy.goto(0, 0)
tommy.setheading(0)
k = len(step)
tommy.penup()
tommy.backward(k*n)
while k >=1:
for i in range(1,k):
draw_romb(tommy, fill_color[step[i-1]], 180, n)
run(tommy, 108, 108, n)
draw_romb(tommy, fill_color[step[-1]], 180, n)
for i in range(1,k):
draw_romb(tommy, fill_color[step[i-1]], 108, n)
run(tommy, 36, 108, n)
draw_romb(tommy, fill_color[step[-1]], 108, n)
for i in range(1,k):
draw_romb(tommy, fill_color[step[i-1]], 36, n)
run(tommy, 324, 108, n)
draw_romb(tommy, fill_color[step[-1]], 36, n)
for i in range(1,k):
draw_romb(tommy, fill_color[step[i-1]], 324, n)
run(tommy, 252, 108, n)
draw_romb(tommy, fill_color[step[-1]], 324, n)
for i in range(1,k):
draw_romb(tommy, fill_color[step[i-1]], 252, n)
run(tommy, 180, 108, n)
draw_romb(tommy, fill_color[step[-1]], 252, n)
k -= 1
for i in range(len(step)-1):
step1.append(step[i]+step[i+1])
if step1[-1] >= 10:
a = str(step1[-1])
a = int(a[0])+int(a[1])
step1[-1] = a
step = step1
step1 = []
tommy.penup()
tommy.forward(n)
tommy.penup()
tommy.goto(0, 0)
tommy.ht()
input() |
89bce90ac16c46b64de4df124313875fd56cc158 | sparklynjewel/Atm_updated | /atm updated.py | 4,198 | 3.921875 | 4 | import csv
from random import randint
file = open("customer.txt", "w")
file.close()
file = open("staff.txt", "w")
file.write("sparklynjewel,dolphin45,kiah2002@gmail.com,Annaliese Ronke")
file.write("\ntallest,kissus,temmy@gmail.com,Maggie Bailey")
file.close()
menu = True
while True:
menu = int(input("would you like to login or close the app, \nEnter 1 to login and 2 to close the app: \n"))
if menu == 1:
print("You have chosen to login")
break
if menu == 2:
print("you have chosen to close the app")
break
elif menu != 1 and menu != 2:
print("invalid input")
def account_details():
pass
while menu == 1:
def main():
with open("staff.txt", "r") as file:
file_reader = csv.reader(file)
user_find(file_reader)
file.close()
def user_find(file):
user = input("enter your username\n")
for row in file:
if row[0] == user:
print("username found", user)
user_found = [row[0], row[1]]
pass_check(user_found)
break
else:
print("try again")
def pass_check(user_found):
user = input("enter your password\n")
if user_found[1] == user:
print("password match")
else:
print("password not match")
main()
print(
"welcome to the system, please create a new account, check account details, carry out banking transactions or "
"log out.")
print("Options: \nCreate a new bank account \nCheck account details \nBank transactions \nLog out")
class BankAccount:
def __init__(self, name, balance, account_type, email):
self.name = name
self.balance = balance
self.account_type = account_type
self.email = email
def get_data(self, name, balance, account_type, email):
self.name = name
self.balance = balance
self.account_type = account_type
self.email = email
def put_data(self):
print(self.name)
print(self.balance)
print(self.account_type)
print(self.email)
class Banking:
def __init__(self):
self.balance = 0
def deposit(self):
amount = float(input("enter amount to be deposited \n"))
self.balance += amount
return f"this is the amount deposited %s : %amount "
def withdraw(self):
amount = float(input("enter the amount to be withdrawn : "))
if self.balance >= amount:
self.balance -= amount
return f"\n You withdrew : {amount}"
else:
return "Insufficient balance"
def banking_options(self):
selected_option = (int(input("enter 1 for deposit or 2 for withdrawal \n")))
if selected_option == 1:
self.deposit()
elif selected_option == 2:
self.withdraw()
pass
else:
print("Enter a valid option")
while True:
option = (input("> "))
if option == "Create a new bank account":
cus1 = BankAccount("", "", "", "")
name = (input("Enter name\n"))
balance = (input("Enter opening balance\n"))
account_type = (input("Enter type of account, Savings/Current\n"))
email = (input("Enter email\n"))
cus1.get_data(name, balance, account_type, email)
cus1.put_data()
n = 10
account_number = ''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
print(("this is your account number:" + account_number))
break
elif option == "Bank transactions":
Bank_transactions = Banking()
print(Bank_transactions.banking_options())
elif option == "Check account details":
if account_number == input("Enter account number"):
A = open("customer.txt")
A.read()
elif option == "Log out":
break
else:
print("login page")
|
38d1f84a86fa395c54e9371cd34ac4ff5f29228c | merada/adventofcode | /2015/advent_12.py | 1,032 | 3.953125 | 4 | import json
from pprint import pprint
import sys
def main():
''' The elves need help with their accounting. Balance their books (given as
JSON input), by summing all the numbers but ignoring objects (dicts) that
contain the value 'red', as these have been incorrectly counted twice.
'''
filename = sys.stdin.read().strip()
with open(filename) as f:
data = json.load(f)
total = calculate_sum(data, dict)
print ("The sum is {}.".format(total))
def calculate_sum(entry, entry_type):
total = 0
for value in entry:
if entry_type is dict:
value = entry[value]
value_type = type(value)
if value_type is int:
total += value
elif value == 'red' and entry_type is dict:
return 0
elif value_type is dict:
total += calculate_sum(value, value_type)
elif value_type is list:
total += calculate_sum(value, value_type)
return total
if __name__ == "__main__":
main()
|
e6b937c50f58172e3ec777f1c1ad5b3130a41558 | vampireshj2013/corepython | /P8-2.py | 176 | 3.703125 | 4 | # -*-coding:utf-8-*-
fr = raw_input("input from:\n")
to = raw_input("input to:\n")
i = raw_input("increment step:\n")
for ii in range(int(fr), int(to), int(i)):
print ii
|
f66b6b3f45cb737e3054de1841d850d7485e8be0 | jordanpaulchan/coding-challenges | /median-stream/median-stream.py | 1,580 | 3.9375 | 4 | from random import randint
def find_median(array):
if not array:
return None
smallest = float('inf')
largest = float('-inf')
count = 0
for num in array:
count += 1
smallest = min(smallest, num)
largest = max(largest, num)
median = count // 2
guess = (largest + smallest) // 2
while smallest <= largest:
running_median = 0
num_equals = 0
for num in array:
if num < guess:
running_median += 1
elif num == guess:
num_equals += 1
if running_median <= median:
if num_equals > 0 and running_median + num_equals > median:
return guess
smallest = guess + 1
else:
largest = guess - 1
guess = (largest + smallest) // 2
return smallest
print(find_median([]))
print(find_median([1, 2, 3, 5, 8]))
print(find_median([8, 2, 1, 5, 3]))
print(find_median([1, 1, 1, 2, 2, 2, 8]))
print(find_median([1, 1, 1, 2, 2, 2, 8, 9, 10, 11]))
print(find_median([8, 8, 1, 8, 8, 1]))
print(find_median([8, 8, 8, 8, 8, 8]))
print(find_median([1, 1, 1, 1, 1, 1]))
print(find_median([2**31 - 1, 2**31 - 1, 2 **
31 - 1, 2**31 - 1, 2**31 - 1, 2**31 - 1]))
print(find_median([-2**31, -2**31, -2**31, -2**31, -2**31, -2**31]))
print(find_median([1]))
elements = [randint(1, 100) for _ in range(100)]
sorted_elements = sorted(elements)
print('Expected median: {}'.format(sorted_elements[len(elements)//2]))
print('Median fn: {}'.format(find_median(elements)))
|
4930b2dbc0a9fef60ef1bef11b67c04f562cc39b | andriitugai/codility-lessons-python | /NumberOfDiscIntersections.py | 1,891 | 3.6875 | 4 | """
We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].
We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).
The figure below shows discs drawn for N = 6 and A as follows:
A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0
There are eleven (unordered) pairs of discs that intersect, namely:
discs 1 and 4 intersect, and both intersect with all the other discs;
disc 2 also intersects with discs 0 and 3.
Write a function:
def solution(A)
that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
Given array A shown above, the function should return 11, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [0..2,147,483,647].
"""
def solution(A):
if not A:
return 0
starts = []
stops = []
for center in range(len(A)):
starts.append(center - A[center])
stops.append(center + A[center])
starts.sort()
stops.sort()
num_open = 0
result = 0
c_idx = 0
for o_idx in range(len(starts)):
if starts[o_idx] > stops[c_idx]:
while stops[c_idx] < starts[o_idx]:
num_open -= 1
c_idx += 1
result += num_open
if result > 10_000_000:
return -1
num_open += 1
return result
if __name__ == "__main__":
print(solution([1, 5, 2, 1, 4, 0]))
|
8ff4ebbad2c303b5e7b477392eb51781000a44a8 | Mdmetelus/Intro-Python-I | /src/cal.py | 2,011 | 4.71875 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`calendar.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
"""
import sys
import calendar
from datetime import datetime
year = datetime.now().year
month = datetime.now().month
cal = calendar.Calendar().itermonthdates(year, month)
def get_cal(month=month, year=year):
months_dict = dict((v, k) for k, v in enumerate(calendar.month_abbr))
user_input = input(
"Enter: month [year] ").split()
if len(user_input) > 2:
print("Try input again..")
elif len(user_input) == 2:
[month, year] = [user_input[0][:3].lower(), int(user_input[1])]
for x in months_dict:
if type(x) != int:
if x.lower() == month:
month = months_dict[x]
print(calendar.TextCalendar(
0).formatmonth(year, month))
elif len(user_input) == 1:
month = user_input[0][:3].lower()
for x in months_dict:
if type(x) != int:
if x.lower() == month:
month = months_dict[x]
print(calendar.TextCalendar(
0).formatmonth(year, month))
else:
print(calendar.TextCalendar(0).formatmonth(year, month))
get_cal() |
e3b87077f3779b06cd1405bdd1acb297e59bc0b0 | SilvesSun/learn-algorithm-in-python | /tree/1373_二叉搜索树的最大键值和.py | 2,147 | 3.578125 | 4 | # 给你一棵以 root 为根的 二叉树 ,请你返回 任意 二叉搜索子树的最大键值和。
#
# 二叉搜索树的定义如下:
#
#
# 任意节点的左子树中的键值都 小于 此节点的键值。
# 任意节点的右子树中的键值都 大于 此节点的键值。
# 任意节点的左子树和右子树都是二叉搜索树。
#
#
#
#
# 示例 1:
#
#
#
#
# 输入:root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]
# 输出:20
# 解释:键值为 3 的子树是和最大的二叉搜索树。
#
#
# 示例 2:
#
#
#
#
# 输入:root = [4,3,null,1,2]
# 输出:2
# 解释:键值为 2 的单节点子树是和最大的二叉搜索树。
#
#
# 示例 3:
#
#
# 输入:root = [-4,-2,-5]
# 输出:0
# 解释:所有节点键值都为负数,和最大的二叉搜索树为空。
#
#
# 示例 4:
#
#
# 输入:root = [2,1,3]
# 输出:6
#
#
# 示例 5:
#
#
# 输入:root = [5,4,8,3,null,6,3]
# 输出:7
#
#
#
#
# 提示:
#
#
# 每棵树有 1 到 40000 个节点。
# 每个节点的键值在 [-4 * 10^4 , 4 * 10^4] 之间。
#
# Related Topics 树 深度优先搜索 二叉搜索树 动态规划 二叉树
# 👍 60 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
max_sum = 0
def maxSumBST(self, root: TreeNode) -> int:
self.traverse(root)
return self.max_sum
def traverse(self, root):
# return [isValidBST, minRoot, maxRoot, sum]
if root is None:
return [True, float("inf"), -float('inf'), 0]
left = self.traverse(root.left)
right = self.traverse(root.right)
if left[0] and right[0] and left[2] < root.val < right[1]:
res = [True, min(left[1], root.val), max(root.val, right[2]), left[3] + right[3] + root.val]
self.max_sum = max(res[3], self.max_sum)
else:
res = [False, -float("inf"), float('inf'), 0]
return res
|
4e1ee873349f58a3bfd97ce6e1700b25dfe98097 | sky-dream/LeetCodeProblemsStudy | /[0079][Medium][Word_Search]/Word_Search_3.py | 1,618 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# leetcode time cost : 372 ms
# leetcode memory cost : 30.2 MB
class Solution:
# def exist(self, board: List[List[str]], word: str) -> bool:
def exist(self, board, word):
if not word:
return True
if not board:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.exist_helper(board, word, i, j):
return True
return False
def exist_helper(self, board, word, i, j):
if board[i][j] == word[0]:
if not word[1:]:
return True
board[i][j] = " " # indicate used cell
# check all adjacent cells
if i > 0 and self.exist_helper(board, word[1:], i-1, j):
return True
if i < len(board)-1 and self.exist_helper(board, word[1:], i+1, j):
return True
if j > 0 and self.exist_helper(board, word[1:], i, j-1):
return True
if j < len(board[0])-1 and self.exist_helper(board, word[1:], i, j+1):
return True
board[i][j] = word[0] # update the cell to its original value
return False
else:
return False
def main():
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word = "ABCCED" #expect is true
obj = Solution()
result = obj.exist(board, word)
assert result == True, ["hint: result is wrong"]
print("return result is :",result)
if __name__ =='__main__':
main() |
2bd7779867c3eb93f513050ce58613641f476966 | sofia819/leetcode_practice | /901-1000/977.py | 659 | 3.625 | 4 | """
977. Squares of a Sorted Array
https://leetcode.com/problems/squares-of-a-sorted-array/
"""
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
neg = []
pos = []
sq = []
for n in A:
if n < 0:
neg.append(n)
else:
pos.append(n)
for n in pos:
while neg and abs(neg[-1]) <= n:
last = neg.pop(-1)
sq.append(last ** 2)
sq.append(n ** 2)
for i in neg[::-1]:
sq.append(i * i)
return sq |
eac30147699fe214350ca82a73a631e44b99b9b1 | NikiDimov/SoftUni-Python-Basics | /exam_preparation/agency_profit.py | 450 | 3.828125 | 4 | company = input()
total_tickets_for_adults = int(input())
total_tickets_for_kids = int(input())
price_ticket_for_adult = float(input())
price_ticket_for_kid = price_ticket_for_adult - price_ticket_for_adult*0.7
taxes = float(input())
profit = (total_tickets_for_adults*(price_ticket_for_adult+taxes)
+ total_tickets_for_kids*(price_ticket_for_kid+taxes))*0.2
print(f"The profit of your agency from {company} tickets is {profit:.2f} lv.")
|
e192991a0a344d1f357ddf0f9d4704937f1a417d | TerryKim11/ICS3U1d-2018-19 | /Working/2_Control_Flow/2_4_if_statements.py | 248 | 3.515625 | 4 | def squirrel_play(temp, is_summer):
if is_summer and 60 <= temp <= 100:
print(True)
elif 60 <= temp <= 90:
print(True)
else:
print(False)
squirrel_play(70, False)
squirrel_play(95, False)
squirrel_play(95, True) |
5864a8a46a0751244bdeab3e47e7be9fc1252969 | parkgunuk/baekjoon_problem | /Python/Baekjoon_algo/baekjoon_1918.py | 1,113 | 3.953125 | 4 | #후위 표기식
operator = ['*', '/', '+', '-']
bracket = ['(', ')']
def main():
infix = list(input())
postfix = []
stack = []
for c in infix :
if is_num(c):
postfix.append(c)
elif c in operator:
p = pref(c)
while len(stack)>0:
top = stack[-1]
if pref(top) < p:
break
postfix.append(stack.pop())
stack.append(c)
elif c == '(':
stack.append(c)
elif c == ')':
while True:
x = stack.pop()
if x == '(':
break
postfix.append(x)
while len(stack) >0:
postfix.append(stack.pop())
print(''.join(postfix))
def is_num(x):
if x not in operator and x not in bracket:
return True
else:
return False
def pref(x):
if x is '*' or x is '/' :
return 2
elif x is '+' or x is '-':
return 1
else:
return 0
if __name__=="__main__":
main() |
86699a6d647413a5a743606fa41bd994fd8e3379 | MSannat/Question-Answering-using-Deep-Learning | /BaseLine-RNN-LSTM-Model/rnnlm.py | 12,122 | 3.515625 | 4 | import time
import tensorflow as tf
import numpy as np
def matmul3d(X, W):
"""Wrapper for tf.matmul to handle a 3D input tensor X.
Will perform multiplication along the last dimension.
Args:
X: [m,n,k]
W: [k,l]
Returns:
XW: [m,n,l]
"""
Xr = tf.reshape(X, [-1, tf.shape(X)[2]])
XWr = tf.matmul(Xr, W)
newshape = [tf.shape(X)[0], tf.shape(X)[1], tf.shape(W)[1]]
return tf.reshape(XWr, newshape)
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, n_steps, n_input)
# Permuting batch_size and n_steps
#x = tf.transpose(x, [1, 0, 2])
# Reshaping to (n_steps*batch_size, n_input)
#x = tf.reshape(x, [-1, n_input])
def MakeFancyRNNCell(H, keep_prob, num_layers=1):
"""Make a fancy RNN cell.
Use tf.nn.rnn_cell functions to construct an LSTM cell.
Initialize forget_bias=0.0 for better training.
Args:
H: hidden state size
keep_prob: dropout keep prob (same for input and output)
num_layers: number of cell layers
Returns:
(tf.nn.rnn_cell.RNNCell) multi-layer LSTM cell with dropout
"""
cell = tf.contrib.rnn.BasicLSTMCell(H, forget_bias=0.0)
cell = tf.contrib.rnn.DropoutWrapper(
cell, input_keep_prob=keep_prob, output_keep_prob=keep_prob)
cell = tf.contrib.rnn.MultiRNNCell([cell] * num_layers)
return cell
# Decorator-foo to avoid indentation hell.
# Decorating a function as:
# @with_self_graph
# def foo(self, ...):
# # do tensorflow stuff
#
# Makes it behave as if it were written:
# def foo(self, ...):
# with self.graph.as_default():
# # do tensorflow stuff
#
# We hope this will save you some indentation, and make things a bit less
# error-prone.
def with_self_graph(function):
def wrapper(self, *args, **kwargs):
with self.graph.as_default():
return function(self, *args, **kwargs)
return wrapper
class RNN_LSTM_Model(object):
def __init__(self, graph=None, *args, **kwargs):
"""Init function.
This function just stores hyperparameters. You'll do all the real graph
construction in the Build*Graph() functions below.
Args:
V: vocabulary size
H: hidden state dimension
num_layers: number of RNN layers (see tf.nn.rnn_cell.MultiRNNCell)
"""
# Set TensorFlow graph. All TF code will work on this graph.
self.graph = graph or tf.Graph()
self.SetParams(*args, **kwargs)
@with_self_graph
def SetParams(self, V, H, softmax_ns=200, num_layers=1):
# Model structure; these need to be fixed for a given model.
self.V = V
self.H = H
self.num_layers = num_layers
# Training hyperparameters; these can be changed with feed_dict,
# and you may want to do so during training.
with tf.name_scope("Training_Parameters"):
# Number of samples for sampled softmax.
self.softmax_ns = softmax_ns
self.learning_rate_ = tf.placeholder_with_default(
0.1, [], name="learning_rate")
# For gradient clipping, if you use it.
# Due to a bug in TensorFlow, this needs to be an ordinary python
# constant instead of a tf.constant.
self.max_grad_norm_ = 5.0
self.use_dropout_ = tf.placeholder_with_default(
False, [], name="use_dropout")
# If use_dropout is fed as 'True', this will have value 0.5.
self.dropout_keep_prob_ = tf.cond(
self.use_dropout_,
lambda: tf.constant(0.5),
lambda: tf.constant(1.0),
name="dropout_keep_prob")
# Dummy for use later.
self.no_op_ = tf.no_op()
@with_self_graph
def BuildCoreGraph(self):
"""Construct the core RNNLM graph, needed for any use of the model.
This should include:
- Placeholders for input tensors (input_w_, initial_h_, target_y_)
- Variables for model parameters
- Tensors representing various intermediate states
- A Tensor for the final state (final_h_)
- A Tensor for the output logits (logits_), i.e. the un-normalized argument
of the softmax(...) function in the output layer.
- A scalar loss function (loss_)
Your loss function should be a *scalar* value that represents the
_average_ loss across all examples in the batch (i.e. use tf.reduce_mean,
not tf.reduce_sum).
You shouldn't include training or sampling functions here; you'll do
this in BuildTrainGraph and BuildSampleGraph below.
We give you some starter definitions for input_w_ and target_y_, as
well as a few other tensors that might help. We've also added dummy
values for initial_h_, logits_, and loss_ - you should re-define these
in your code as the appropriate tensors.
See the in-line comments for more detail.
"""
# Input ids, with dynamic shape depending on input.
# Should be shape [batch_size, max_time] and contain integer word indices.
self.input_w_ = tf.placeholder(tf.int32, [None, None], name="w")
# Initial hidden state. You'll need to overwrite this with cell.zero_state
# once you construct your RNN cell.
self.initial_h_ = None
# Final hidden state. You'll need to overwrite this with the output from
# tf.nn.dynamic_rnn so that you can pass it in to the next batch (if
# applicable).
self.final_h_ = None
# Output logits, which can be used by loss functions or for prediction.
# Overwrite this with an actual Tensor of shape [batch_size, max_time]
self.logits_ = None
# Should be the same shape as inputs_w_
self.target_y_ = tf.placeholder(tf.int32, [None, None], name="y")
# Replace this with an actual loss function
self.loss_ = None
# Get dynamic shape info from inputs
with tf.name_scope("batch_size"):
self.batch_size_ = tf.shape(self.input_w_)[0]
with tf.name_scope("max_time"):
self.max_time_ = tf.shape(self.input_w_)[1]
# Get sequence length from input_w_.
# TL;DR: pass this to dynamic_rnn.
# This will be a vector with elements ns[i] = len(input_w_[i])
# You can override this in feed_dict if you want to have different-length
# sequences in the same batch, although you shouldn't need to for this
# assignment.
self.ns_ = tf.tile([self.max_time_], [self.batch_size_, ], name="ns")
#### YOUR CODE HERE ####
# See hints in instructions!
# Construct embedding layer
with tf.name_scope("EmbeddingLayer"):
self.W_in_ = tf.Variable(tf.random_uniform([self.V, self.H], 0.0, 1.0), name="W_in")
self.x_ = tf.nn.embedding_lookup(self.W_in_, self.input_w_)
#self.x_shape = tf.shape(self.x_)
# Construct RNN/LSTM cell and recurrent layer.
with tf.name_scope("RecurrentLayer"):
#self.seq_length = tf.placeholder(tf.int32, [None])
self.W_out_ = tf.Variable(tf.random_uniform([self.H, self.V], 0.0, 1.0), name="W_out")
self.b_out_= tf.Variable(tf.zeros([self.V,], dtype=tf.float32), name="b_out")
self.cell_ = MakeFancyRNNCell(self.H, self.dropout_keep_prob_)
self.initial_h_ = self.cell_.zero_state(self.batch_size_, tf.float32)
self.outputs, self.final_h_ = tf.nn.dynamic_rnn(self.cell_,
self.x_,
dtype=tf.float32,
#sequence_length=self.seq_length,
initial_state=self.initial_h_)
#self.outputs_shape = tf.shape(self.outputs)
# Softmax output layer, over vocabulary. Just compute logits_ here.
# Hint: the matmul3d function will be useful here; it's a drop-in
# replacement for tf.matmul that will handle the "time" dimension
# properly.
with tf.name_scope("OutputLayer"):
self.logits_ = tf.add(matmul3d(self.outputs, self.W_out_), self.b_out_, name="logits")
# Loss computation (true loss, for prediction)
# Full softmax loss, for scoring
with tf.name_scope("Cost_Function"):
self.per_example_loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.target_y_,
logits=self.logits_,
name="per_example_loss")
self.loss_ = tf.reduce_mean(self.per_example_loss_, name="loss")
self.optimizer_total_ = tf.train.AdagradOptimizer(self.learning_rate_)
self.step_ = self.optimizer_total_.minimize(self.loss_)
#### END(YOUR CODE) ####
@with_self_graph
def BuildTrainGraph(self):
"""Construct the training ops.
You should define:
- train_loss_ : sampled softmax loss, for training
- train_step_ : a training op that can be called once per batch
Your loss function should be a *scalar* value that represents the
_average_ loss across all examples in the batch (i.e. use tf.reduce_mean,
not tf.reduce_sum).
"""
# Replace this with an actual training op
self.train_step_ = None
# Replace this with an actual loss function
self.train_loss_ = None
#### YOUR CODE HERE ####
# See hints in instructions!
# Define approximate loss function.
# Note: self.softmax_ns (i.e. k=200) is already defined; use that as the
# number of samples.
# Loss computation (sampled, for training)
with tf.name_scope("Training"):
self.inputs_to_sampled_softmax_loss = tf.reshape(self.outputs, [-1, tf.shape(self.outputs)[2]])
self.target_y_sampled = tf.reshape(self.target_y_, [-1,1])
self.per_example_train_loss_ = tf.nn.sampled_softmax_loss(weights=tf.transpose(self.W_out_),
biases=self.b_out_,
labels=self.target_y_sampled,
inputs=self.inputs_to_sampled_softmax_loss,
num_sampled=self.softmax_ns,
num_classes=self.V,
num_true =1,
name="per_example_sampled_softmax_loss")
self.train_loss_ = tf.reduce_mean(self.per_example_train_loss_, name="sampled_softmax_loss")
# Define optimizer and training op
self.optimizer_ = tf.train.AdagradOptimizer(self.learning_rate_)
self.train_step_ = self.optimizer_.minimize(self.train_loss_)
#### END(YOUR CODE) ####
@with_self_graph
def BuildSamplerGraph(self):
"""Construct the sampling ops.
You should define pred_samples_ to be a Tensor of integer indices for
sampled predictions for each batch element, at each timestep.
Hint: use tf.multinomial, along with a couple of calls to tf.reshape
"""
#### YOUR CODE HERE ####
self.pred_samples_ = tf.multinomial(tf.reshape(self.logits_, [-1, tf.shape(self.logits_)[2]]), 1, name = "pred_random")
newshape = [tf.shape(self.logits_)[0], tf.shape(self.logits_)[1], 1]
self.pred_samples_ = tf.reshape(self.pred_samples_, newshape)
#### END(YOUR CODE) ####
|
affabcd67beafcb7fc4af9a3a3bdb1add62447bd | Suriya0404/Algorithm | /pzl/valid_bst.py | 996 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
root_list = []
if not root:
return True
root_list.append(root)
for root in root_list:
if root.left:
if (root.left.val >= root.val) or not root.left.val:
return False
else:
root_list.append(root.left)
if root.right:
if (root.right.val <= root.val) or not root.right.val:
return False
else:
root_list.append(root.right)
return True
if __name__ == '__main__':
sol = Solution()
# [10, 5, 15, null, null, 6, 20]
# Expected: False
# returns: True
sol. |
885d141034b9f7d798a2aa8dc2d52b64cf239a08 | Jireh-Fang/one-hundred-exercise-problem | /18.py | 295 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 14:39:20 2019
@author: Administrator
"""
#统计1到100中能被3整除的数的和
sum = 0
for i in range(3,101,3):
sum += i
print(sum)
#sum = 0
#for i in range(1,101):
# if i%3 == 0:
# sum += i
#print(sum) |
5a4e395b4ff24c3895480b103a21518e901e03c9 | sankar-vs/Python-and-MySQL | /Data Structures/Dictionary/7_Unique_items.py | 623 | 4.28125 | 4 | '''
@Author: Sankar
@Date: 2021-04-09 09:17:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-09 09:28:09
@Title : Dictionary_Python-7
'''
'''
Write a Python program to print all unique values in a dictionary.
Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
'''
list = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
set = set(value for dict in list for value in dict.values())
print("Unique Values: ", set) |
5def7b3dcb0b716e007c8b92bdd3c74a4ee3b307 | Yanoka/CS7 | /3B.py | 124 | 3.640625 | 4 |
print('Celcius\t\t Fahrenheit')
for temp in range(21):
f = 9 / 5 * temp + 32
print(temp,'\t\t','{:.0f}'.format(f)) |
dd7738fda27c86faa1b0abd83bf4b3f6e5462ec1 | hsuanhauliu/leetcode-solutions | /easy/missing-number/solution.py | 702 | 3.875 | 4 | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
for i, n in enumerate(nums):
if i != n:
return i
return len(nums)
def missingNumber2(self, nums2):
"""
A very clever solution posted on the Discussion forum.
Basically, we calculate the sum from 0 to n WITHOUT missing numbers, by
doing n * (n+1) / 2. Then, we subtract the sum of all elements that we
actually have. The resulting number is the number that is missing.
"""
n = len(nums2)
return n * (n + 1) / 2 - sum(nums2) |
ab869372cbb5384844972bf0b59d80e760818654 | dmekhanikov/Search-Engine | /common.py | 166 | 3.609375 | 4 | def read_stopwords(filename):
words = set()
with open(filename) as f:
for word in f.readlines():
words.add(word.strip())
return words
|
9918a34f0c64c1dfc6c49d133eb904d4cfcb6973 | Janhvi-Chauhan/programs | /mudit/identity matrix.py | 261 | 3.96875 | 4 | n=int(input("Enter a number: "))
print("Your identity matrix will be")
for i in range(0,n):
for j in range(0,n):
if(i==j):
print("1",sep=" ",end=" ")
else:
print("0",sep=" ",end=" ")
print()
input()
|
37fad5ff3dc5f8f879cf1a04ba35fc198f241488 | Ahmetyilmazz/Python | /Print calismalari.py | 231 | 3.859375 | 4 | # Calisma Programı.7_Calisma
# Programmer : Ahmet YILMAZ
counter = 100
miles = 1000.0
name = "John"
print (counter)
print (miles)
print (name)
a = input("Bir kelime gir ulen : ")
print("Girdiginiz isim : "+a) |
5801a0a1e5a6dfff90aa8a330e2942822cc695ef | DavidNester/SportStreamer | /scrframe.py | 3,460 | 3.90625 | 4 | """
Author: David Nester
Date: 1.23.2018
# Python 3.6
Modification of code for vertical scroll frame from http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
Class that places a canvas on the window with frame containing widgets inside. Frame can be scrolled.
It is a little buggy but still works well. Only scrolls the frame with the mouse in it.
Old frame refers to the tkinter frame and not the ttk frame
"""
from Utility import *
def MouseWheelHandler(event):
def delta(event):
if event.num == 5 or event.delta < 0:
return -1
return 1
return delta(event)
class VerticalScrolledFrame(Frame):
"""A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling
"""
def __init__(self, parent, bgcolor, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
self.canvas = canvas = Canvas(self, bg=bgcolor, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=self.canvas.yview)
# reset the view
self.canvas.xview_moveto(0)
self.canvas.yview_moveto(0)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
self.canvas.bind("<Button-4>", self._on_mousewheel)
self.canvas.bind("<Button-5>", self._on_mousewheel)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = OldFrame(self.canvas, bg=bgcolor)
interior_id = self.canvas.create_window(0, 0, window=interior,
anchor=NW)
self.interior.bind('<Enter>', self._bound_to_mousewheel)
self.interior.bind('<Leave>', self._unbound_to_mousewheel)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
self.canvas.bind('<Configure>', _configure_canvas)
# functions for only scrolling when the mouse is over the frame
def _bound_to_mousewheel(self, event):
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
def _unbound_to_mousewheel(self, event):
self.canvas.unbind_all("<MouseWheel>")
def _on_mousewheel(self, event):
self.canvas.yview_scroll(MouseWheelHandler(event), "units")
if __name__ == "__main__":
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.