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 |
|---|---|---|---|---|---|---|
f72e611a5282dfb43cb9cebb06665c8c0e2b24ff | kannangates/autoclean_csv | /autoclean.py | 4,899 | 3.5625 | 4 | import streamlit as st
import pandas as pd
st.set_page_config(layout="wide")
st.title('Auto_clean your csv file for data exploration')
# @st.cache(allow_output_mutation=True)
def load_data(file):
df = pd.read_csv(file)
return df
@st.cache
# IMPORTANT: Cache the conversion to prevent computation on every rerun
def convert_df(file):
return file.to_csv().encode('utf-8')
def download_button(csv):
st.download_button(
label="Download revised file as CSV",
data=csv,
file_name='df1_new.csv',
mime='text/csv'
)
upload_file = st.file_uploader("Upload a file", type=("csv"))
if upload_file is not None:
df1 = load_data(upload_file)
is_check = st.checkbox("View Full data")
if is_check:
st.dataframe(df1)
total_records = df1.shape[0]*df1.shape[1]
df1_shape = df1.shape
#df1_columns = df1.columns.tolist()
df1_columns = [col for col in df1]
# st.write("Columns", df1_columns)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.write("Total Records :", df1.shape[0]*df1.shape[1])
with col2:
st.write("Shape of Data :", df1_shape)
with col3:
st.write("No. of Duplicated Rows :", df1.duplicated().sum())
with col4:
st.write("Missing Rows:", df1.isnull().sum().sum())
is_duplicated = df1.duplicated().sum()
if is_duplicated > 0:
is_extract_duplciate = st.checkbox("Extract duplicate rows")
if is_extract_duplciate:
st.write("Duplcaited Rows")
st.dataframe(df1.loc[df1.duplicated(), :])
is_radio = st.radio("Which Duplciate to Delete",
("First", "Last", "Keep Duplicates", "Drop All", "Custom Columns"))
check_now = st.checkbox("Clear Now")
# with st.form("form1"):
# if st.form_submit_button("Submit"):
if check_now:
if is_radio == "First":
st.write("Total records before removing Duplciates: ",
total_records)
df1_new = df1.drop_duplicates()
df1_total_records = df1_new.shape[0]*df1_new.shape[1]
st.write("Total records after removing Duplciates::",
df1_total_records)
csv = convert_df(df1_new)
download_button(csv)
if is_radio == "Last":
st.write("Total records before removing Duplciates: ",
total_records)
df1_new = df1.drop_duplicates(keep='last')
df1_total_records = df1_new.shape[0]*df1_new.shape[1]
st.write("Total records after removing Duplciates::",
df1_total_records)
csv = convert_df(df1_new)
download_button(csv)
if is_radio == "Keep Duplicates":
df1_new = df1.copy(deep=True)
df1_total_records = df1_new.shape[0]*df1_new.shape[1]
st.write("No Data is removed, total records: ",
df1_total_records)
csv = convert_df(df1_new)
download_button(csv)
if is_radio == "Drop All":
st.write("Total records before removing Duplciates: ",
total_records)
df1_new = df1.drop_duplicates(keep=False)
df1_total_records = df1_new.shape[0]*df1_new.shape[1]
st.write("Total records after removing Duplciates::",
df1_total_records)
csv = convert_df(df1_new)
download_button(csv)
if is_radio == "Custom Columns":
columns_del = st.multiselect(
"Select Column to remove duplicate", df1_columns)
form_submit1 = st.checkbox('Clear Duplicates')
st.write("columns_del", list(columns_del))
if form_submit1:
st.write("columns_del", df1[columns_del])
st.write(
"Total records before removing Duplciates: ", total_records)
df1.drop_duplicates(subset=list(columns_del))
st.write(
"Total records before removing Duplciates: ", total_records)
#df1_new = df1.drop_duplicates(keep=False)
# df1_new = df1.drop_duplicates(keep=False)
# df1_total_records = df1_new.shape[0]*df1_new.shape[1]
# st.write("Total records after removing Duplciates::",df1_total_records)
#csv = convert_df(df1_new)
# download_button(csv)
|
4fb20a239432c5608cf0f1f32bee92a496a6a369 | Aasthaengg/IBMdataset | /Python_codes/p03323/s350032161.py | 120 | 3.65625 | 4 | import sys
s = input().split(' ')
x, y = int(s[0]), int(s[1])
if (x > 8 or y > 8):
print (":(")
else:
print ("Yay!") |
0fb4ab0d13bd84012b92f2dd417e7385b8e05b39 | khanmazhar/Python12Projects | /p4_rock_paper_scissors.py | 574 | 3.953125 | 4 | import random
def play():
user_choice = input(
"What is your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
comp_choice = random.choice(['r', 'p', 's'])
if user_choice == comp_choice:
return 'It\'s a tie!'
if is_win(user_choice, comp_choice):
return 'You won!'
return 'You lost!'
def is_win(player, oponent):
# r > s, p > r, s > p
if (player == 'r' and oponent == 's') or (player == 'p' and oponent == 'r') or (player == 's' or player == 'p'):
return True
print(play())
|
9858d17e09712baeb9ad6b221360e04cf67f34ab | VSRLima/Python | /Scripts/Tupla/Tupla D2.py | 679 | 3.75 | 4 | times = ('Athletico-PR', 'Atlético-GO', 'Atlético-MG', 'Bahia', 'Botafogo', 'Bragantino', 'Ceará',
'Corinthias', 'Corinthians', 'Coritiba', 'Flamengo', 'Fluminense', 'Fortaleza', 'Goiás', 'Grêmio',
'Internacional', 'Palmeiras', 'Santos', 'São Paulo', 'Sport', 'Vasco')
print('Os 5 primeiros são:', end=' ')
for c in range(0, 6):
print(times[c], end=' -> ')
print('Fim')
print('~' * 100)
print('Os 4 últimos são:', end=' ')
for i in range(17, 21):
print(times[i], end=' -> ')
print('Fim')
print('~' * 100)
print(f'A tabela em ordem alfabética: {sorted(times)}')
print('~' * 100)
print(f'O Bahia está na {times.index("Bahia")+ 1}ª posição')
|
37ec5c271a4d442095219abaecf0feefcd4ddfe0 | jacksteveanderson/python-assignment | /primenumber.py | 1,357 | 4.15625 | 4 | # Prime Number Check (Finds 5 Prime Number)
times = 0
while times < 5 :
enterprime = True
while enterprime:
number = input("Enter a positive integer number : ")
digits = len(number)
if not number.isdigit():
if number.count(",") == 1 and number.replace(",", "1").isnumeric() and digits >= 2 or number.count(".") == 1 and number.replace(".", "1").isnumeric() and digits >= 2:
print("Please enter only integer number not float.")
elif number.count("-") == 1 and number.index("-") == 0 and number.replace("-","1").isnumeric():
print("Please enter a positive number.")
else:
print("Please Do not use any entries other than numeric values.")
else:
enterprime = False
if int(number) == 0 or int(number) == 1:
print(number, "is NOT a prime number.")
elif int(number) == 2:
print(number, " is the smallest Prime Number.")
times += 1
enterprime = False
else:
for i in range(2,int(number)):
if int(number) % i == 0:
print(number, "is NOT a prime number.")
break
if i == int(number)-1:
print(number, " is a Prime Number.")
times += 1
enterprime = False
break |
43f8a6e2cd3fda84a3661d821ea32222daccd4cc | gtraiano/SiCalcPy | /Terminal.py | 1,934 | 4.1875 | 4 | from Calculator import Calculator
class Terminal:
"""
A terminal for the Calculator class
"""
def __init__(self):
self._input = ""
self._calc = Calculator()
def main(self):
while True:
self._input = input("> ").lower()
if self._input == "exit":
break
if not self._calc.is_valid_expression(self._input):
print("Invalid input")
else:
try:
if self._input == "store":
self._calc.store()
print("Stored", self._calc.recall())
elif self._input == "recall":
print("Recalled", self._calc.recall())
print("> ", self._calc.recall(), sep = "", end = "")
self._input = "" # clear input
self._input = str(self._calc.recall()) + input().lower() # attach recall value, then user input
if not self._calc.is_valid_expression(self._input):
print("Invalid input")
continue
print(self._input, "=", self._calc.calculate(self._input))
elif self._input == "clear":
self._calc.clear()
print("Cleared")
elif self._input == "help":
self._calc.help()
else:
print(self._input, "=", self._calc.calculate(self._input))
except (ZeroDivisionError, ValueError) as e:
print(e)
if __name__ == '__main__':
t = Terminal()
t.main() |
906d2388e95ed4183abf0a80106dfa099419c8d3 | whitebluecloud/padp_ko | /tasks/9th/FrogJump_cloud.py | 1,116 | 4.03125 | 4 | '''
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
def solution(X, Y, D)
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
'''
class FrogJump():
def __init__(self):
pass
def cry(self):
return '개굴'
def jump(self, X, Y, D):
n = (Y - X) // D
r = (Y - X) % D
return n if r == 0 else n + 1
|
05270ffda10fee046f46648d56a47be0744348ee | drieswijns/ahorn | /ahorn/GameBase/Actor.py | 850 | 3.96875 | 4 | import abc
class Actor(metaclass=abc.ABCMeta):
"""An actor performs actions and drives a game from state to state.
Parameters
----------
Returns
-------
"""
@abc.abstractmethod
def __init__(self):
pass
@abc.abstractmethod
def get_action(self, state):
"""Return the action the actor wants to take in a given state.
Parameters
----------
State:
The state in which the actor must perform an action
Returns
-------
action: Action
The action the actor wants to take in this state."""
pass
@abc.abstractmethod
def __str__(self):
"""A name for this actor
Parameters
----------
Returns
-------
name: str
The name for this actor."""
pass
|
112bd30151f96ec93cebe7016776be232374ccf8 | DanielZuerrer/AdventOfCode2020 | /day-4/a/main.py | 533 | 3.859375 | 4 | with open('input.txt', 'r') as f:
input = f.read()
double_space_separated = input.replace('\n', ' ')
passports = double_space_separated.split(' ')
necessary_fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
def is_valid(passport):
is_valid = True
for field in necessary_fields:
is_valid &= f'{field}:' in passport
return is_valid
passport_validities = map(is_valid, passports)
number_of_valid_passports = len(list(filter(lambda x: x, passport_validities)))
print(number_of_valid_passports)
|
c9441a85001a7fbfa220ebdbe4b552dc4788dfec | kakukosaku/DSA | /sort/py_impl/merge_sort.py | 1,555 | 4.0625 | 4 | #!/usr/bin/env python3
# coding: utf-8
#
# author: kaku
# date: 19/10/10
#
# GitHub:
#
# https://github.com/kakukosaku
#
# © 2019-2022 Kaku Kosaku All Rights Reserved
from typing import List, NoReturn
def merge(arr: List[int], low: int, mid: int, high: int, arr_tmp: List[int]) -> NoReturn:
for i in range(low, high + 1):
arr_tmp[i] = arr[i]
i, j = low, mid + 1
k = i
while i <= mid and j <= high:
# from small to lager
if arr_tmp[i] <= arr_tmp[j]:
arr[k] = arr_tmp[i]
i += 1
else:
arr[k] = arr_tmp[j]
j += 1
k += 1
while i <= mid:
arr[k] = arr_tmp[i]
i += 1
k += 1
while j <= high:
arr[k] = arr_tmp[j]
j += 1
k += 1
def _merge_sort(arr: List[int], low: int, high: int, arr_tmp: List[int]) -> NoReturn:
"""merge sort, c style :)
Notes:
1. In Python arguments pass by reference to mutable variables, needn't return arr.
2. Pass array size to function `even in Python can get array(list) len on runtime`.
3. Replace for loop with while since Python for loop is not friendly to use index.
"""
if low < high:
mid = (low + high) // 2
_merge_sort(arr, low, mid, arr_tmp)
_merge_sort(arr, mid + 1, high, arr_tmp)
merge(arr, low, mid, high, arr_tmp)
def merge_sort(arr: List[int], array_size: int):
# arr_tmp avoid `new` list object each time
arr_tmp = list(arr)
_merge_sort(arr, 0, array_size - 1, arr_tmp)
|
dc18276eaca427c2b7c4d3528600d43eac41fc31 | R4f4Lc/Programacion1Daw | /Primer Trimestre/7- Python/Ej8Dimension.py | 724 | 4.03125 | 4 | """
Realiza un programa que pida la temperatura media que ha hecho en cada mes
de un determinado año y que muestre a continuación un diagrama de barras
horizontales con esos datos. Las barras del diagrama se pueden dibujar a base
de asteriscos o cualquier otro carácter.
__author__ = "Rafael López Cruz"
"""
mes = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio","Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
temperatura = []
for x in range(0,12):
temperatura.append(input("Introduce la temperatura de "+ mes[x] + ":"))
print("_________________________________________")
for x in range(0,12):
print(mes[x] + "=" + temperatura[x] + "Cº");
print("_________________________________________")
|
1321cf87a1f5edfb3c7f97c6daef4a3811ac6111 | guyalone/pyptest | /pavan-sample-programs/sample_funtions.py | 404 | 4.21875 | 4 | uservalue = input("Enter a value to get factorial:")
def fact(number):
factorial = 1
if number < 0:
print ("factorial doesnot exist for negative numbers")
exit()
elif number == 0:
print ("Factorial of 0 is 1")
exit()
else:
for i in range(1, number + 1):
factorial = (factorial*i)
print factorial
return ;
fact(uservalue)
|
dc751522efe8d70fd5ae0a3b903c64627033a049 | AP-MI-2021/lab-4-AndreiFeier | /main.py | 4,500 | 4.03125 | 4 | def citire_lista():
'''
Citeste lista
:return:list,lista de numere
'''
lista =input("lista : ")
lista=lista.split()
lista=[int(el)for el in lista]
return lista
def afisare_negative(lista):
'''
Afiseaza numerele negative din lista
:param lista:list,lista de numere initiala
:return:None
'''
for el in lista :
if el < 0:
print(el)
def afisare_mic(lista,cifra):
'''
Afiseaza cel mai mic numar pozitiv cu ultima cifra parametrul cifra
:param lista:list,lista de numere initiala
:param cifra: int,ultima cifra
:return: int,cel mai mic numar
'''
ok=False
for el in lista:
if el % 10 ==cifra and el>10:
ok=True
minim=el
break
if ok == True:
for el in lista :
if el % 10==cifra and minim >el and el > 10:
minim = el
print(minim)
else:
print("Nu exista")
def is_prime(n):
'''
Verifica daca n este numar prim
:param n: int,numarul pe care vrem sa il verificam
:return: True daca n prim,False altfel
'''
for i in range(2,n-1):
if n%i == 0:
return False
return True
def test_is_prime():
assert(is_prime(5)==True)
assert (is_prime(2) == True)
assert (is_prime(4) == False)
assert (is_prime(13) == True)
def is_superprim(n):
'''
Verifica daca numarul n este superprim
:param n: int,numarul pe care vrem sa il verificam
:return: True daca n superprim,False altfel
'''
if n<=1:
return False
while n!=0:
if is_prime(n)==False:
return False
n=n//10
return True
def test_is_superprim():
assert(is_superprim(123)==False)
assert (is_superprim(239) == True)
assert (is_superprim(23) == True)
assert (is_superprim(1045) == False)
def afisare_superprim(lista):
'''
Afiseaza toate numerele superprime din lista
:param lista: list,lista initiala
:return: None
'''
for el in lista :
if is_superprim(el)==True:
print(el)
def cmmdc(a,b):
'''
Afla cmmdc dintre a si b
:param a:int
:param b:int
:return:int,cmmdc dintre a si b
'''
if b==0:
return a
return cmmdc(b,a%b)
def test_cmmdc():
assert(cmmdc(24,16)==8)
assert (cmmdc(18, 27) == 9)
assert (cmmdc(11, 23) == 1)
assert (cmmdc(1,5) == 1)
def invers(a):
'''
Calculeaza numarul negativ inversat din numarul dat
:param a:int
:return:int,inversul lui a
'''
a=-a
aux=0
while a!=0:
aux=aux*10+a%10
a=a//10
return -aux
def test_invers():
assert(invers(-13)==-31)
assert (invers(-1234) == -4321)
assert (invers(-51) == -15)
assert (invers(-6) == -6)
def afisare_modificat(lista):
'''
Afiseaza lista de numere modificate dupa cerinta
:param lista:list,lista initiala
:return:None
'''
rezultat=[]
ok=True
for el in lista :
if el >0:
ok=False
d=el
break
if ok==False:
for el in lista:
if el>0:
d=cmmdc(d,el)
for el in lista:
if el >0:
rezultat.append(d)
else :
rezultat.append(invers(el))
print("lista este: ",rezultat)
def print_menu():
print("1. Citirea unei liste de numere întregi. Citirile repetate suprascriu listele precedente.")
print("2. Afișarea tuturor numerelor negative nenule din listă")
print("3. Afișarea celui mai mic număr care are ultima cifră egală cu o cifră citită de la tastatură.")
print("4. Afișarea tuturor numerelor din listă care sunt superprime.")
print("5. Afișarea listei obținute din lista inițială în care numerele pozitive și nenule au fost înlocuite cu CMMDC-ul lor și numerele negative au cifrele în ordine inversă.")
print("6. Exit")
def start():
lista=[]
while True:
print_menu()
optiune=input("Selectati optiunea")
if optiune == "1":
lista=citire_lista()
elif optiune=="2":
afisare_negative(lista)
elif optiune=="3":
cifra=int(input("Ultima cifra : "))
afisare_mic(lista,cifra)
elif optiune=="4":
afisare_superprim(lista)
elif optiune=="5":
afisare_modificat(lista)
else:
break
test_is_prime()
test_is_superprim()
test_cmmdc()
test_invers()
start()
|
7bf4a0b968658e5517f40c3844520865e0a74935 | ralenth/testing-homework | /homework.py | 1,398 | 3.65625 | 4 | import argparse
import json
import os
from typing import List, Union
current_dir = os.path.dirname(__file__)
def take_from_list(li: list, indices: Union[int, List[int]]):
"""
This function returns list of elements for given indices.
:param li: list of elements
:param indices: single index or list of indices
:return: list of elements selected using indices
"""
if isinstance(indices, int):
indices = [indices]
if not isinstance(indices, list) or not all(isinstance(i, int) for i in indices):
raise ValueError(f"Indices should be integer or list of integers, not {type(indices)}")
for index in indices:
if index >= len(li):
raise IndexError(f"Index {index} is to big for list of length {len(li)}")
return [li[i] for i in indices]
def calculate(in_file: str, out_file: str):
with open(in_file, 'r') as f_p:
data = json.load(f_p)
result = take_from_list(data["list"], data["indices"])
with open(out_file, 'w') as f_p:
json.dump(result, f_p)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("input_file", default=os.path.join(current_dir, "input.json"), nargs="?")
parser.add_argument("output_file", default=os.path.join(current_dir, "output.json"), nargs="?")
args = parser.parse_args()
calculate(args.input_file, args.output_file)
|
2884191b57020d0a4d9ba2334870d348312d1632 | jitendra1310/codeing_problems | /code/prime_number.py | 581 | 3.96875 | 4 | import math
class Prime:
def __init__(self):
num = input("Enter a number: ")
self.num = int(num)
def method1(self):
print(math.floor(math.sqrt(self.num)))
for i in range(2,math.floor(math.sqrt(self.num))):
if self.num % i ==0:
return False
return True
def method2(self):
i=2
while (i <= self.num):
if self.num % i ==0:
return False
return True
obj = Prime();
print(obj.method2()) |
d16363816a863f9c810391015ec21e98dec64bd9 | Color4/2017_code_updata_to_use | /绘图代码/plot_v8.py | 327 | 3.6875 | 4 | import matplotlib.pyplot as plt
fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,8,6]
left,bottom,width,height = 0.1,0.1,0.8,0.8
ax1 = fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')
left,bottom,width,height = 0.2,0.6,0.25,0.25
ax2 = fig.add_axes([left,bottom,width,height])
ax2.plot(y,x,'b')
plt.show()
|
70ca7c0485140ade11e0dff3c86ad8649c83c7d8 | skok1025/python_ch2.3 | /symbol_table.py | 748 | 3.84375 | 4 |
def f():
l_a = 2
l_b = '마이콜'
print("f_local: ",locals())
class MyClass:
x=10
y=20
print(globals())
g_a = 1
g_b = "둘리"
# print(globals())
f()
# 1. 정의된 함수
f.k = 'hello'
print("--",f.__dict__)
# 2. 클래스 객체
MyClass.z = 10
# print(MyClass.__dict__)
# 내장 함수는 심볼 테이블이 없다 -> 확장 x
# print(print.__class__)
# 내장 클래스는 symbol table 은 있으나 확장금지
# str.z = 10
# print(str.__dict__)
# 내장클래스로 생성된 객체
# 심벌테이블 x -> 확장 x
# g_a.z = 10
# print(g_a.__dict__)
# 사용자 정의된 클래스로 생성된 객체
# 심볼 테이블 -> 확장
o = MyClass()
print(o.__dict__)
o.z = 10
print(o.__dict__)
print(globals())
|
09fb7e8bc5951c7445088b16f7fdea6633d6460b | ozzi7/Hackerrank-Solutions | /Python/Itertools/itertools-permutations.py | 160 | 3.71875 | 4 | from itertools import permutations
text = input().split()
s = text[0]
k = int(text[1])
li = list(permutations(s,k))
li.sort()
for x in li:
print("".join(x)) |
fad1c62e82bc4aff21d1faab54564ed7e3a65d7b | cristiano250/pp1 | /04-Subroutines/zad. 37.py | 152 | 3.578125 | 4 | tab=[2,3,1,2,5,6,4,5,6,3]
def unikat(tab):
u=[]
for i in tab:
if tab.count(i)==1:
u.append(i)
print(u)
unikat(tab) |
75c9bec35fab1baf964840ee3bde3c063dade0e5 | JaneHQ1/Path-to-Python3-v2 | /pythonic/c8.py | 2,342 | 4.6875 | 5 | '''
14-8 __len__与__bool__内置方法
'''
"""
class Test():
def __bool__(self):
return False
def __len__(self):
return 0
"""
# 这两个方法的返回结果将影响test对象最终的bool取值。
# 这两个方法如何影响最终的bool返回结果?
# __len__ 返回0,False
# __len__ 返回非0,True
"""
class Test():
def __len__(self):
# return '8'
# return 1.0
return True
print(bool(Test()))
"""
# TypeError: 'str' object cannot be interpreted as an integer
# TypeError: 'float' object cannot be interpreted as an integer
# True
# 不能返回字符串
# 不能返回浮点
# __len__ 返回True,True
# 如果Bool方法不出现,test的bool取值由len方法的返回结果决定。
# bool(Test())实质上是调用对象内部len的方法。
# 除了bool,len()也会调用对象内部的len。
# print(len(Test()))
# 1
# True 对应数字1
"""
class Test():
pass
print(len(Test()))
"""
# TypeError: object of type 'Test' has no len()
# 如果没有私有len方法,无法对对象查长度。
# 不要对内置函数想得太神秘了,实质上是调用对象里的某一个方法.
# 不用全局方法也可以,实例化以后调用len方法也可以.
# 全局函数更加方便我们调用.
"""
class Test():
def __len__(self):
return 8
test = Test()
print(test.__len__())
"""
# 8
# 一旦我们加入bool方法,len的结果将不再影响整个对象的bool取值,而是由bool方法控制bool取值.
"""
class Test():
def __bool__(self):
# return False
return 0
def __len__(self):
return True
print(bool(Test()))
# False
"""
# TypeError: __bool__ should return bool, returned int
# bool方法用0取代False会报错.
# 我们经常0,空字符串,空列表和False等同起来,但是类型不一样.
# 这里限定是bool类型就只能使用bool类型.
class Test():
# Nonzero决定对象最终取值
# 但是在Python3里Nonzero不能定义bool类型
def __nonzero__(self):
pass
def __bool__(self):
print('bool called')
return False
def __len__(self):
print('len called')
return True
print(bool(Test()))
# bool called
# False
# 有bool方法就不会调用len方法.
# 没有bool方法,len方法将会被调用.
|
09bf2e12c7d2990267ab54c39ec44001ac0db469 | mooksys/Python_Algorithms | /Chapter39/file_39_3e.py | 399 | 3.5625 | 4 | def my_divmod(a, b, results):
return_value = True
if b == 0:
return_value = False
else:
results[0] = a // b
results[1] = a % b
return return_value
# 메인 코드
res = [None] * 2
val1 = int(input())
val2 = int(input())
ret = my_divmod(val1, val2, res)
if ret == True:
print(res[0], res[1])
else:
print("잘못된 입력값입니다!");
|
467142fb96d266c3c40af877cbd67ee2289cd671 | kumarvadivel/python-training | /sample38.py | 87 | 3.5625 | 4 | x,y=map(int,input().split(","))
print("true" if x==y or x+y==5 or x-y==5 else "false") |
eb3330a9dc29227e32859f6be6d60ff0cbb9b934 | abiB1994/CMEECourseWork | /Week2/Code/loops.py | 498 | 3.90625 | 4 | # !/usr/bin/env python
"""Loops and infinite loops in python"""
__author__ = "Abigail Baines a.baines17@imperial.ac.uk"
__version__ = '0.0.1'
# for loops in Python
for i in range(5):
print i
my_list = [0, 2, "geronimo!", 3.0, True, False]
for k in my_list:
print k
total = 0
summands = [0, 1, 11, 111, 1111]
for s in summands:
total = total + s
print total
# while loops in Python
z = 0
while z < 100:
z = z + 1
print (z)
b = True
while b:
print "GERONIMO! infinite loop! ctrl+c to stop!"
# ctrl + c to stop!
|
b916cd8121a2bfe0ecda309892bd9d8cb26e438b | rahuljnv/Python_Tutorial_rg | /E8_Factotrial_Trailing_Zero.py | 1,028 | 4.15625 | 4 | # Part 1: cal the factorial
# Part 2: cal the no of trailing zeros in factorial
def factorial(number):
if number == 0 or number == 1:
return 1
else:
return number * factorial(number-1)
# # Iterative method
# i = 1
# fac = 1
# for i in range (i,number+1,1):
# fac = fac *i
# return fac
def factorialTrailingZeros(number):
# 5! = 5*4*3*2*1
count = 0
# 100! = (100//5) + (100//5*5) jab tak zero na aa jaye
i = 5
while(number//i != 0):
count += number//i
i = i*5
return count
# fac = factorial(number)
# print (fac)
# count = 0
# while (fac%10 == 0):
# count+=1
# fac = fac/10
# return count
if __name__ == '__main__':
try:
number = int(input("enter the number:"))
# fac = factorial(number)
# print(f"Factorial of {number} is {fac}")
facT = factorialTrailingZeros(number)
print(f"\nNo Trailing Zeros in factorial:{facT}")
except:
print("plz enter the integer only") |
9cf4181932fd5b89dae392d73ffc97e29f04e02a | vipnambiar/py_training | /Exercises/grade.py | 672 | 3.578125 | 4 | import sys
d = {}
for score in range(90,101):
d[score] = 'A'
for score in range(80, 90):
d[score] = 'B'
for score in range(70, 80):
d[score] = 'C'
for score in range(60, 70):
d[score] = 'D'
def main():
while True:
score = raw_input("Enter a score: ")
try:
score = int(score)
except Exception:
print "Not a valid score, please enter a number between 1-100"
continue
else:
print "Your score is : %s" % d.get(score, 'F')
if __name__ == '__main__':
try:
main()
except:
print "Exiting..."
sys.exit(0)
|
24bcf8c39f9070469d44d1d9cf2da0b39a3b2cd5 | ralsouza/python_data_structures | /section23_binary_search_tree/241_traverse_bst.py | 2,391 | 4.125 | 4 | # Traversal of Binary Search Tree
# Insert a node to BST
import QueueLinkedList as queue
class BSTNode:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def insert_node(root_node, node_value):
if root_node.data is None:
root_node.data = node_value
elif node_value <= root_node.data:
if root_node.left_child is None:
root_node.left_child = BSTNode(node_value)
else:
insert_node(root_node.left_child, node_value)
else:
if root_node.right_child is None:
root_node.right_child = BSTNode(node_value)
else:
insert_node(root_node.right_child, node_value)
return "The node has been successfully inserted."
def pre_order_traversal(root_node):
if not root_node:
return
print(root_node.data)
pre_order_traversal(root_node.left_child)
pre_order_traversal(root_node.right_child)
def in_order_traversal(root_node):
if not root_node:
return
in_order_traversal(root_node.left_child)
print(root_node.data)
in_order_traversal(root_node.right_child)
def post_order_traversal(root_node):
if not root_node:
return
post_order_traversal(root_node.left_child)
post_order_traversal(root_node.right_child)
print(root_node.data)
def level_order_traversal(root_node):
if not root_node:
return
else:
customQueue = queue.Queue()
customQueue.enqueue(root_node)
while not(customQueue.isEmpty()):
root = customQueue.dequeue()
print(root.value.data)
if root.value.left_child is not None:
customQueue.enqueue(root.value.left_child)
if root.value.right_child is not None:
customQueue.enqueue(root.value.right_child)
new_bst = BSTNode(None)
insert_node(new_bst, 70)
insert_node(new_bst, 50)
insert_node(new_bst, 90)
insert_node(new_bst, 30)
insert_node(new_bst, 60)
insert_node(new_bst, 80)
insert_node(new_bst, 100)
insert_node(new_bst, 20)
insert_node(new_bst, 40)
print("**** Pre Order Traversal ****")
pre_order_traversal(new_bst)
print("**** In Order Traversal ****")
in_order_traversal(new_bst)
print("**** Post Order Traversal ****")
post_order_traversal(new_bst)
print("**** Level Order Traversal ****")
level_order_traversal(new_bst) |
538792c0ac5f4e0073d02367931e0aa1394ebecd | mightykim91/algorithm_and_data_structure | /quicksort.py | 635 | 3.90625 | 4 | def quickSort(array, left, right):
if left >= right:
return
pivot = array[(left+right)//2]
index = partition(array, left, right, pivot)
quickSort(array, left, index-1)
quickSort(array, index, right)
def partition(array, left, right, pivot):
while (left <= right):
while (array[left] < pivot):
left += 1
while (array[right] > pivot):
right -= 1
if left <= right:
array[left], array[right] = array[right], array[left]
left += 1
right -= 1
return left
arr = [9,2,6,4,3,5,1]
quickSort(arr,0,len(arr)-1)
print(arr)
|
274339867a215ebe1644ddf71d89a7a9896820f4 | danieltshibangu/Mini-projects | /PYTHON-CH3-16.py | 544 | 3.90625 | 4 | # program aks users to enter a year and identify a leap year
# set up programming constants for february
LEAP_YEAR = 29
NORM_YEAR = 28
# prompt user for number of years and store
year = int( input( "Enter a year: " ) )
# create conditional statemtents for years entered
if year % 100 == 0:
if year % 400:
print( 'In', year, 'February has', LEAP_YEAR, 'days.' )
else:
if year % 4 == 0:
print( 'In', year, 'February has', LEAP_YEAR, 'days.' )
else:
print( 'In', year, 'February has', NORM_YEAR, 'days.' )
|
f134019655250147d21a8c605226f66fbcaf345a | pauldepalma/CPSC427 | /E-Linear-Regression/iterative/linear-regression1.py | 1,883 | 4.0625 | 4 | '''
Iterative version of gradient descent for linear regression
Code is adapted from and data comes from
: ...github.com/mattnedrich/GradientDescentExample
'''
import numpy
import csv
import matplotlib.pyplot as plt
def gradient(b_current, m_current, points, learningRate):
b_gradient = 0
m_gradient = 0
N = float(len(points))
for i in range(0, len(points)):
x = points[i, 0]
y = points[i, 1]
b_gradient += -(2/N) * (y - ((m_current * x) + b_current))
m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current))
new_b = b_current - (learningRate * b_gradient)
new_m = m_current - (learningRate * m_gradient)
return [new_b, new_m]
def gradient_descent(points, starting_b, starting_m, learning_rate, num_iter):
b = starting_b
m = starting_m
for i in range(num_iter):
b, m = gradient(b, m, points, learning_rate)
return [b, m]
def plot_results(points,m,b):
x_training = [point[0] for point in points]
y_training = [point[1] for point in points]
y_prediction = [m*x + b for x in x_training]
plt.plot(x_training,y_prediction,color='r')
plt.scatter(x_training,y_training,color='g')
plt.title("Iterative Linear Regression")
plt.show()
def init():
#read file into list of x,y coordinates, one set of coords per line
reader = list(csv.reader(open("input.csv", "rb"), delimiter=','))
points = numpy.array(reader).astype('float')
#set the initial parameters
learning_rate = 0.0001 #step size
b = 0 # initial y-intercept guess
m = 0 # initial slope guess
num_iter = 1000 #number of iterations of gradient across all points
return points, learning_rate, b, m, num_iter
def main():
points, learning_rate, b, m, num_iter = init()
[b, m] = gradient_descent(points, b, m, learning_rate, num_iter)
plot_results(points,m,b)
main()
|
e1d263262828bf063828ffffd72a780f9c2c6aa5 | tobielf/DSAP | /Leetcode/Maximum Depth of Binary Tree/maximum_depth_of_binary_tree.py | 769 | 3.875 | 4 | # source:http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
# report:
# Problem Description:
# Given a binary tree, find its maximum depth.
# The maximum depth is the number of nodes along the longest path
# from the root node down to the farthest leaf node.
# @author: tobielf
# @date: 2014/03/16
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
if root == None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
s = Solution()
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(1)
root.left.left = TreeNode(2)
root.left.left.left = TreeNode(3)
root.left.left.left.right = TreeNode(4)
print(s.maxDepth(root)) |
cd54556f06103d62efcf925fb5fe4c6ec6d3e820 | eliasantoniorodrigues1/curso_expressoes_regulares | /aula5_comeca_com_termina_com.py | 655 | 3.84375 | 4 | # Meta Caracteres:
# ^ - No inicio da expressão regular quer dizer COMEÇA COM dentro da lista NEGA o dado da lista.
# $ - TERMINA COM
# [^a-z] - LISTA NEGADA - qualquer coisa que não seja de a-z
import re
cpf = '147.852.963-12'
# Abaixo temos ? no mínimo 1 0-9 três posições com um ponto, esse grupo se repete duas vezes
# 0-9 três posições, 0-9 duas posições
print(re.findall(r'((?:[0-9]{3}\.){2}[0-9]{3}-[0-9]{2})', cpf))
# Expressão que começa com:
cpf2 = 'a 147.852.963-12 qualquer coisa'
# ?: dentro de um grupo estou dizendo para não salvar esse grupo na memória:
print(re.findall(r'^(?:[0-9]{3}\.){2}[0-9]{3}-[0-9]{2}?', cpf2)) |
bedd381b26006411ad7fd8ba803545dc76b7caf2 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 3/PYTHON CHALLENGE/Day95 Task/Task2.py | 307 | 4.1875 | 4 | '''2. Write a Python program to compute the sum of all the multiples of 3 or 5 below 500.
All the natural numbers below 12 that are multiples of 3 or 5, we get 3, 5, 6, 9 and 10. The sum of these multiples is 33. '''
n = 0
for i in range(1,500):
if not i % 5 or not i % 3:
n = n + i
print(n)
|
9103796362e36fc83d81ce84a9ed3154ddeb37db | lvoinescu/python-daily-training | /matrix_word_finder/main.py | 1,406 | 3.890625 | 4 | # Given a matrix of characters, and a input word,
# determine if the word can be found in the matrix,
# by traversing the matrix in any direction (top, bottom, left, right)
def seek_solution(matrix, i, j, word, position):
if position == len(word):
return True
print("Checking [" + str(i) + "," + str(j) + "]=" + matrix[i][j])
if i > 0 and matrix[i - 1][j] == word[position]:
return seek_solution(matrix, i - 1, j, word, position + 1)
if i < len(matrix) - 1 and matrix[i + 1][j] == word[position]:
return seek_solution(matrix, i + 1, j, word, position + 1)
if j > 0 and matrix[i][j - 1] == word[position]:
return seek_solution(matrix, i, j - 1, word, position + 1)
if j < len(matrix[i]) - 1 and matrix[i][j + 1] == word[position]:
return seek_solution(matrix, i, j + 1, word, position + 1)
return False
def word_search(matrix, word):
rows = len(matrix)
columns = len(matrix[0])
for i in range(rows):
for j in range(columns):
if matrix[i][j] == word[0]:
found = seek_solution(matrix, i, j, word, 1)
if found:
return True
return False
input_matrix = [
['4', '3', '2', '1'],
['B', 'S', 'M', 'E'],
['s', 'T', 'E', 'G'],
['M', 'O', 'R', 'A']]
needle = 'STORAGE1234'
print(needle + " found: " + str(word_search(input_matrix, needle)))
|
fbbbb7cf86a729198e48f955a669b5f7644835cf | Tenedra/HW-Shool-Best-Practice | /HW3/HW3_task5.py | 630 | 3.53125 | 4 |
r = int(input()) # число, ближ.знач. в ряде Фиббоначи которого нужно суммировать
count = 0 # счетчик n-значночти числа
x=r
while x!=0:
x//=10
count+=1
# определим сколько эллементов ряда нужно вывести
if count==1:
a=7
else:
a = 6*count
f1 = 0; f2 = 1; A = 0
fibonacci_series = []
for i in range(a+1):
fibonacci_series.append(f1)
f1,f2= f2,f2+f1
for j in range(len(fibonacci_series)):
if fibonacci_series[j]>=r:
print (fibonacci_series[j]+fibonacci_series[j-1])
break |
5a1f9e48b15a36fabbea639408fd42a7a96f0bad | dusty-phillips/pyjaco | /tests/strings/zipstring.py | 132 | 3.96875 | 4 |
s1 = "hello"
s2 = "world"
s3 = "abcd"
s4 = zip(s1,s2,s3)
for item in s4:
print "----"
for val in item:
print val
|
79534cf2f1a315e6b590ce54c6e1e3cf84fb2dfe | thinkerston/curso-em-video-python3 | /mundo-03/exercicio-073.py | 2,404 | 3.78125 | 4 | '''Crie uma tupla preenchida com os 20 primeiros colocados da tabela do campeonato
brasileiro de futebol. na ordem de colocação. Depois mostre?
- Apenas os 5 primeiros colocados;
- os ultimos 4 colocados;
- uma lista de times em ordem alfabetica;
- em que posição esta o time da Chapecoense.'''
tabelaBrasileirao = ('Flamengo', 'Santos', 'Palmeiras', 'Gremio', 'Athletico-PR',
'São Paulo', 'Internacional', 'Corinthias', 'Fortaleza',
'Goias', 'Bahia', 'Vasco', 'Atletico-MG','Fluminense',
'Botafogo','Ceará SC','Cruzeiro','CSA','Chapecoense','Avaí')
while True:
print('Menu Consulta')
print('''
[1] veja os 5 primeiros colocados
[2] veja os 4 ultimos colocados
[3] veja uma lista em ordem alfabetica
[4] veja em que posição está o Chapecoense
[5] insira a posição para ver o time
[0] Sair
''')
escolhaUsuario = int(input(': '))
if escolhaUsuario == 0:
break
elif escolhaUsuario == 1:
for posicao in range(1, 6) :
print(f'{posicao}° {tabelaBrasileirao[posicao -1]}')
print('====='*5)
pass
elif escolhaUsuario == 2:
for posicao in range(16, 20):
print(f'{posicao +1 }° {tabelaBrasileirao[posicao]}')
print('====='*5)
pass
elif escolhaUsuario == 3:
tabelaBrasileiraoPorNome = sorted(tabelaBrasileirao)
for time in (tabelaBrasileiraoPorNome):
print (time)
print('==='*5)
pass
elif escolhaUsuario == 4:
print('Chapecoense está na ', end='')
print((tabelaBrasileirao.index('Chapecoense')+ 1), end='')
print('° Posição')
pass
elif escolhaUsuario == 5:
posicaoConsulta = int(input('Insira a posição que deseja Consultar: '))
while (posicaoConsulta < 0) or (posicaoConsulta > 20):
print(f'A consulta {posicaoConsulta} é invalida')
posicaoConsulta = int(input('insira um numero de 0 a 20: '))
pass
print('====='*15)
print(f'O time que se enconta na posição {posicaoConsulta}° é o {tabelaBrasileirao[posicaoConsulta - 1]}')
print('====='*15)
pass
else:
print('A Escolha é invalida Tente novamente com um numero do menu valido')
pass |
f4af530244c0b8222e80af3d1211f58f9bc293d9 | josephburton06/rio_olympics | /nationality_helpers.py | 1,547 | 3.84375 | 4 | import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
def create_top_medalist():
'''
This function is used to create a dataframe of athletes that received medals for countries that
received more than 90 medals.
'''
df = pd.read_csv('athletes.csv')
df.dropna(inplace=True)
'''
Below will create a column that contains the total number of medals that athlete won.
'''
df['medal_or_nm'] = df['gold'] + df['silver'] + df['bronze']
df = df[df.medal_or_nm >= 1]
country_count = pd.DataFrame(df.groupby('nationality')['medal_or_nm'].agg('sum'))
country_count.columns = ['country_count']
df = df.merge(country_count, on='nationality')
df = df[df.country_count > 90]
athlete_count = pd.DataFrame(df.groupby('sport')['name'].agg('count'))
athlete_count.columns = ['athlete_count']
df = df.merge(athlete_count, on='sport')
df = df[df.athlete_count > 30]
'''
DOB to datetime.
'''
df.dob = pd.to_datetime(df.dob)
# df['sport_enc'] = df['sport']
# encoder = LabelEncoder()
# encoder.fit(df.sport)
# df.sport_enc = encoder.transform(df.sport)
categorical_features = df.dtypes==object
categorical_cols = df.columns[categorical_features].tolist()
le = LabelEncoder()
df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col))
'''
Create columm for approximate age.
'''
df['age'] = 2016-df['dob'].dt.year
return df |
93942bf9f1687ff2b439feb4edd1fb939595077a | guiw07/leetCode | /7_ReverseInteger.py | 671 | 3.96875 | 4 | """
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
reversed = int(str(x)[::-1])
if reversed >= 2147483651:
return 0
else:
return reversed
else:
reversed = (-1 *int(str(x)[::-1][:-1]))
if reversed <= -2147483651:
return 0
else:
return reversed |
b4da301278fa5218a651434257102ce8aaa36572 | PhilanthropistBright/MyPython | /MyExercise/class.py | 296 | 3.78125 | 4 | class MyClass:
i=12345
def f(self):
return "hello world"
x= MyClass()
print(x.i)
print(x.f())
class MyClass1:
sum = 0
def __init__(self,sum1,sum2):
self.sum = sum1+sum2
self.su1=sum1
self.su2=sum2
y = MyClass1(10,20)
print(y.sum,y.su1,y.su2)
|
efe58633da1b46c785f1292f9dff95966ece90df | joerihofman/pythonjoostjoeri | /Week1/opgave8.py | 130 | 3.5 | 4 | T = int(input('Temperatuur:')) #temp
B = int(input('Beaufort:')) #beaufort
G = 13+0.62*T-14*B**0.24+0.47*T*B**0.24
print(G) |
568759e0825e1cf48fd29c2a8b3a0717906cdea1 | alanmmckay/population_protocol_simulator | /scanner.py | 1,850 | 3.78125 | 4 | from general_token import GeneralToken, GeneralTokenType
#--- --- ---#
#A scanner super class that simply iterates through an
#input string and assumes each character is an individual
#token.
#--- --- ---#
class Scanner:
def __init__(self, input_str):
self.input_str = input_str
self.pos = 0
self.maxPos = len(input_str)
self.look_ahead = None
self.line = 1
def peek(self):
if not self.look_ahead:
self.look_ahead = self.nextToken()
return self.look_ahead
def nextToken(self):
if self.look_ahead:
next_token = self.look_ahead
self.look_ahead = None
return next_token
else:
return self.getNextToken()
def getInputString(self):
return self.input_str
if __name__ == "__main__":
def getNextToken(self):
# --- getNextToken invokes produceToken() while
#keeping handling the character position of
#the input string
token = self.produceToken()
if token.isChar():
self.pos += 1
return token
def produceToken(self):
# --- produceToken is used to create tokenType
#objects based on the input string.
if self.pos >= self.maxPos:
return GeneralToken(GeneralTokenType.EOF)
else:
return GeneralToken(GeneralTokenType.CHAR, \
self.input_str[self.pos])
if __name__ == "__main__":
from helper_functions import file_input
input_data = file_input("input: ")
scanner = Scanner(input_data)
while True:
token = scanner.getNextToken()
print(token)
if token.isEOF():
break
|
ebb311ebca6d22138b05841b7e3fb5fadea85fae | MohammedJ94/pdsnd_github | /bikeshare.py | 7,646 | 4.5 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input("\nPlease type one of the folowing cities you want to be filtered 1-Chicago, 2-New York City, 3-Washington: ").lower()
while city not in CITY_DATA.keys():
city = input("\nOops! You haven't choosen a correct city, please check spelling!: ").lower()
# TO DO: get user input for month (all, january, february, ... , june)
MONTH_LIST = ['january', 'february', 'march', 'april', 'may', 'june', 'all']
month = input("\nPlease type a month you want to filter by and choose from January to June or type All: ").lower()
while month not in MONTH_LIST:
month = input("\nSorry! Please try again by choosing a month from January to June!: ").lower()
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'all']
day = input("\nWhat day of week would like to filter by?: ").lower()
while day not in days:
day = input("\nsorry! incorrect day, please try again: " ).lower()
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
days = ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'all']
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
common_month = df['month'].mode()[0]
print('The most common month is:' ,common_month)
# TO DO: display the most common day of week
common_day = df['day_of_week'].mode()[0]
print('The most common day of the week is:' ,common_day)
# TO DO: display the most common start hour
df['start_hour'] = df['Start Time'].dt.hour
common_strt_hr = df['start_hour'].mode()[0]
print('The most common start hour is:' ,common_strt_hr)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
start_station = df['Start Station'].mode()[0]
print('The most common start station is:' ,start_station)
# TO DO: display most commonly used end station
end_station = df['End Station'].mode()[0]
print('The most common end station is:' ,end_station)
# TO DO: display most frequent combination of start station and end station trip
df['start_end_stations'] = df['Start Station'] + " - " + df['End Station']
freq_strt_end_stations = df['start_end_stations'].mode()[0]
print('The most frequent start and end station combination are:' ,freq_strt_end_stations)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
df['travel time'] = pd.to_datetime(df['End Time']) - pd.to_datetime(df['Start Time'])
# TO DO: display total travel time
total_trvl_time = df['travel time'].sum()
print("The total travel time is:" ,total_trvl_time)
# TO DO: display mean travel time
mean_trvl_time = df['travel time'].mean()
print("The mean travel time is:" ,mean_trvl_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types_count = df['User Type'].value_counts()
print('Counts of user types:\n' ,user_types_count)
# TO DO: Display counts of gender
try:
gender_types = df['Gender'].value_counts()
print('\nGender types:\n' ,gender_types)
except:
print('\nThere is no gender data available for this city')
# TO DO: Display earliest, most recent, and most common year of birth
try:
earliest_birth_year = int(df['Birth Year'].min())
print('\nThe earliest birth year is:' ,earliest_birth_year)
recent_birth_year = int(df['Birth Year'].max())
print('\nThe latest birth year is:' ,recent_birth_year)
common_birth_year = int(df['Birth Year'].mode()[0])
print('\nThe most common birth year is:' ,common_birth_year)
except:
print('\nThere is no birth year data available for this city')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def show_data(df):
"""
Raw data is displayed upon request by the user.
"""
see_data = input("Would you like to see the raw data?: ").lower()
start_index = 0
end_index = 5
while end_index in range(df.shape[0]):
if see_data == 'yes':
print(df.iloc[start_index:end_index])
start_index += 5
end_index += 5
no_more = input("Would you like to see more?: ").lower()
if no_more == 'no':
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
show_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
1aa2769833121938ba30fdb8a4eefe52b71861b1 | akimi-yano/algorithm-practice | /lc/review_820.ShortEncodingOfWords.py | 1,727 | 3.8125 | 4 | # 820. Short Encoding of Words
# Medium
# 904
# 350
# Add to List
# Share
# A valid encoding of an array of words is any reference string s and array of indices indices such that:
# words.length == indices.length
# The reference string s ends with the '#' character.
# For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].
# Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.
# Example 1:
# Input: words = ["time", "me", "bell"]
# Output: 10
# Explanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5].
# words[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"
# words[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"
# words[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"
# Example 2:
# Input: words = ["t"]
# Output: 2
# Explanation: A valid encoding would be s = "t#" and indices = [0].
# Constraints:
# 1 <= words.length <= 2000
# 1 <= words[i].length <= 7
# words[i] consists of only lowercase letters.
# This solution works:
class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key = lambda x : len(x), reverse = True)
seen = set([])
ans = []
for word in words:
if word not in seen:
ans.append(word)
for i in range(len(word)):
seen.add(word[i:])
return sum(len(word)+1 for word in ans)
|
8be4394314c32466d122f65a1ce25168560c3b0f | unstory/tutorial | /pandas_tutorial.py | 7,145 | 4 | 4 |
# coding: utf-8
# ### quick start for pandas
# #### 1. preview
# 1. python基础语法
# 2. 面向对象思想
# #### 2. pandas数据结构
# #### 2.1 Series
# Series(序列)与list相似,功能更加强大。series是学习dataframe的基础,一个dataframe是由多个series构成的数据结构。
# ##### series的常用属性
# In[9]:
import pandas as pd
# 构建一个series
s = pd.Series([1,2,"c",5,1],index=range(1,6)) # series在不指定index参数的时候会自动创建索引
print(s) # 打印series
print(s.index) # 打印series的索引
print(s.values) # 打印series的值
print(s.dtype) # object,series的值是object类型(即python的str类型),类比数据库的varchar或者text类型
# index,values,dtype都是索引的属性
# In[5]:
# python的字典的key唯一,使用dict创建series时,默认会把key值作为series的index
d = {"a":1, "b":3, "c":5, "d":7}
s1 = pd.Series(d)
print(s1) # 从打印的结果可以看出s1的索引就是字典的key值
# ##### series的常用方法
# <b>str子类方法</b>
# In[19]:
# str是python的基本数据类型,str类型的变量(实例)都有一系列的方法,比如:
# 从面向对象的角度来看,s是str类的一个实例
s = "AaBbCc"
print(s.endswith("c")) # True, 字符串以c结尾
print(s.upper()) # AABBCC,将小写字母变成大写字母
print(s.startswith("A")) # True,以A开头
# In[20]:
# 对于Series来说,str是series里面的一个子类
ser = pd.Series(["aaa", "bb", "Cc", "DD", "eafV", "1", 1])
print(ser.str.endswith("a"))
print(ser.str.upper())
print(ser.str.startswith("a"))
# <b>常用方法</b>
# In[34]:
ser1 = pd.Series([54,32,56,23,7,1, 1])
# 升序排序
print(ser1.sort_values(ascending=True))
# 计算均值,标准差最大值,最小值,中位数, pd.min(),pd.std(), pd.median()...
# 去重
print(pd.unique(ser1))
# 更多函数参考:http://pandas.pydata.org/pandas-docs/stable/api.html
# <b>自定义函数</b>
# In[29]:
ser2 = pd.Series([34,234,4,23,1])
ser3 = ser2.apply(lambda x: x+10000) # lambda匿名函数,x代表ser2中的每一个值,这里将ser2的每一个元素都加上10000
print("ser3:", ser3)
def test(x):
if x > 5:
return True
return False
ser4 = ser2.apply(test) # apply:应用,即将ser2中的每一个元素都应用到test函数
print(ser4)
# #### 2.2 DataFrame
# dataFrame是类似excel表格的一种数据结构,可以说用pandas包就一定会用dataframe
# <b>创建DataFrame</b>
# In[5]:
import pandas as pd
# 创建一个dataframe,更常见的作法是通过读csv或者excel文件,读进python的数据就是一个dataframe
df = pd.DataFrame({"a":[1,3,5,7,9], "b":[2,4,6,8,10], "c":["a", "b", "c", "d", "e"]},columns=["a", "b", "c"]) # columns参数指定列的顺序(因为字典的key是无序的)
print("df:\n", df)
# <b>DataFrame常用属性</b>
# In[8]:
print(df.index) # df的索引
print(df.values) # 二维列表
print(df.dtypes) # 每一列的数据类型,a列是int64(64位的整数),b列是int64,c列是object类型(类似数据库的varchar或者text)
print(df.shape) # (5, 3),即df是一个5行3列的二维表
print(df.columns) # df的列名
# <b>索引、选择</b>
# In[39]:
import numpy as np
# 取a列
df = pd.DataFrame({"a":[1,2,3,4,5], "b":[2,4,6,8,10], "c":["a", "b", "c", "d", "e"]}, index=range(0, 5))
print("取a列:df['a']\n", df["a"]) # df["a"]是Series
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("取前3行:df[0:3]\n", df[0:3])
print("-------------"*5 + "****" + "------------"*5)# 分割线
print('取索引为1、2, a,b列:df.loc[1:2, ["a", "b"]]\n', df.loc[1:2, ["a", "b"]])
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("取a列大于3的值:df[df.a>3]\n", df[df.a>3])
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("取行索引为1, 列索引为1(第二列)的值:df.iloc[1, 1]\n", df.iloc[1, 1]) # 或者: df.iat[1, 1]
print("-------------"*5 + "****" + "------------"*5)# 分割线
df.iat[1,1] = 111
print("将行索引为1, 列索引为1(第二列)的值设置为111:df.iat[1,1] = 111\n", df) #
print("-------------"*5 + "****" + "------------"*5)# 分割线
df.loc[:,"d"] = ["one", "two", "three", "four", "one"]
print('添加d列:df.loc[:,"d"] = ["one", "two", "three", "four", "one"]\n',df)
print("-------------"*5 + "****" + "------------"*5)# 分割线
# isin,isna,fillna
print('取出d列的值为one,two的值:df[df.d.isin(["one", "two"])]\n', df[df.d.isin(["one", "two"])])
print("-------------"*5 + "****" + "------------"*5)# 分割线
df.iat[1, 2] = np.nan # 将索引为1,c列的值设置为nan
print("取出c列为nan的那一行:df[df.c.isna()]\n", df[df.c.isna()]) # 取出c列为nan的那一行
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("将nan设置为test: df.fillna('test')\n", df.fillna("test"))
# 更多方法参考:http://pandas.pydata.org/pandas-docs/stable/indexing.html, http://pandas.pydata.org/pandas-docs/stable/10min.html
print("-------------"*5 + "****" + "------------"*5)# 分割线
# ##### DataFrame常用方法、函数
# In[7]:
import pandas as pd
# 读excel文件
df1 = pd.read_excel("data/test1.xlsx", encoding="gbk", sheet_name="Sheet1")
df2 = pd.read_excel("data/test1.xlsx", encoding="gbk", sheet_name="Sheet2")
df3 = pd.read_excel("data/test2.xlsx", encoding="gbk", sheet_name="Sheet1")
print("df1: ", df1)
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("df2: ", df2)
print("-------------"*5 + "****" + "------------"*5)# 分割线
print("df3: ", df3)
print("-------------"*5 + "****" + "------------"*5)# 分割线
# In[9]:
# 合并文件
df = pd.concat([df1, df2, df3], axis=0, ignore_index=True) # 忽略索引
print("df: ", df)
# In[11]:
# 按照age升序排序
df.sort_values(by="age", ascending=True, inplace=True) # inplace参数为True,即将原来的df替换(inplace)成排序后的df
print("after sort: \n", df)
# In[27]:
### groupby 聚合函数 (重点)
# groupby的思想: split(按组split) -- > apply(将每一组都apply到函数上)-- >combine(将每一组的结果combine)
age_mean_df = df.groupby(by=["sex"])["age"].mean() # 按性别分组计算年龄的平均值
print("age_mean_df: \n", age_mean_df)
print("-------------"*5 + "****" + "------------"*5)# 分割线
# apply函数
# 将分组后的结果都应用到sum函数
sum_df = df.groupby(by=["sex"])["age"].apply(lambda x: sum(x))
print("first sum: \n", sum_df)
print("-------------"*5 + "****" + "------------"*5)# 分割线
# 等价于
sum_df = df.groupby(by=["sex"])["age"].sum()
print("second sum:\n", sum_df)
print("-------------"*5 + "****" + "------------"*5)# 分割线
# 应用apply函数
def get_grade(x):
return "children" if x <= 14 else "young" # 大于14岁返回young,小于等于14岁返回children
df["grade"] = df["age"].apply(get_grade)
print(df)
# 参考:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html
|
a5bc6fe234953c5a427c52edef0bcfa9174d1bd5 | n1k-n1k/python-algorithms-and-data-structures--GB-interactive-2020 | /unit_03_arrays/hw/hw_03_1.py | 443 | 3.546875 | 4 | """
1. В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
Примечание: 8 разных ответов.
"""
count = {}
for i in range(2, 100):
for j in range(2, 10):
if i % j == 0:
count[j] = count.get(j, 0) + 1
for k, v in count.items():
print(k, '-', v)
|
edc29f492f2004d181f6b0f980ced3f83728e599 | lealex262/RRT-Mobile-Manipulator | /src/scripts/rrt.py | 6,144 | 3.765625 | 4 | #!/usr/bin/env python
"""
Path planning Sample Code with Randomized Rapidly-Exploring Random Trees (RRT)
author: AtsushiSakai(@Atsushi_twi)
edited: Alex Le
"""
import math
import random
import sys
import time
import matplotlib.pyplot as plt
import numpy as np
import cmap
import move
show_animation = True
class RRT:
"""
Class for RRT planning
"""
class Node:
"""
RRT Node
"""
def __init__(self, x, y, theta):
self.x = x
self.y = y
self.theta = theta
self.path_x = []
self.path_y = []
self.parent = None
def __init__(self, start, goal, map,
expand_dis=25.0, path_resolution=0.5, goal_sample_rate=1, max_iter=5000):
"""
Setting Parameter
start:Start Position [x,y,theta]
goal:Goal Position [x,y,theta]
"""
self.map = map
self.start = self.Node(start[0], start[1], start[2])
self.end = self.Node(goal[0], goal[1], goal[2])
self.expand_dis = expand_dis
self.path_resolution = path_resolution
self.goal_sample_rate = goal_sample_rate
self.max_iter = max_iter
self.node_list = []
def planning(self, animation=True):
"""
rrt path planning
animation: flag for animation on or off
"""
self.node_list = [self.start]
for i in range(self.max_iter):
rnd_node = self.get_random_node()
nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)
nearest_node = self.node_list[nearest_ind]
new_node = self.steer(nearest_node, rnd_node, self.expand_dis)
if self.collision_check(new_node):
self.node_list.append(new_node)
if animation and i % 5 == 0:
# self.draw_graph(rnd_node)
pass
if self.calc_dist_to_goal(self.node_list[-1].x, self.node_list[-1].y) <= self.expand_dis:
final_node = self.steer(self.node_list[-1], self.end, self.expand_dis)
if self.collision_check(final_node):
return self.generate_final_course(len(self.node_list) - 1)
if animation and i % 5:
# self.draw_graph(rnd_node)
pass
return None # cannot find path
def steer(self, from_node, to_node, extend_length=float("inf")):
new_node = self.Node(from_node.x, from_node.y, to_node.theta)
d, theta = self.calc_distance_and_angle(new_node, to_node)
new_node.path_x = [new_node.x]
new_node.path_y = [new_node.y]
if extend_length > d:
extend_length = d
n_expand = math.floor(extend_length / self.path_resolution)
for _ in range(int(n_expand)):
new_node.x += self.path_resolution * math.cos(theta)
new_node.y += self.path_resolution * math.sin(theta)
new_node.path_x.append(new_node.x)
new_node.path_y.append(new_node.y)
d, _ = self.calc_distance_and_angle(new_node, to_node)
if d <= self.path_resolution:
new_node.path_x.append(to_node.x)
new_node.path_y.append(to_node.y)
new_node.parent = from_node
return new_node
def collision_check(self, node):
if node is None:
return False
# return self.map.collision_check((node.x, node.y))
for pose in list(zip(node.path_x, node.path_y))[::5]:
if not self.map.collision_check(pose):
return False
return True
def generate_final_course(self, goal_ind):
path = [[self.end.x, self.end.y, self.end.theta]]
node = self.node_list[goal_ind]
while node.parent is not None:
path.append([node.x, node.y, node.theta])
node = node.parent
path.append([node.x, node.y, node.theta])
return path
def calc_dist_to_goal(self, x, y):
dx = x - self.end.x
dy = y - self.end.y
return math.hypot(dx, dy)
def get_random_node(self):
size = self.map.get_map_pixel_size()
if random.randint(0, 100) > self.goal_sample_rate:
rnd = self.Node(random.uniform(0, size[0] - 1),
random.uniform(0, size[1] - 1),
random.uniform(0, math.pi * 2))
else: # goal point sampling
rnd = self.Node(self.end.x, self.end.y, self.end.theta)
return rnd
def draw_graph(self, rnd=None):
self.map.draw_cmap(rnd, self.node_list, self.end, show=False)
def draw_path(self, path):
plt.plot([x for (x, y, theta) in path], [y for (x, y, theta) in path], '-r')
@staticmethod
def get_nearest_node_index(node_list, rnd_node):
dlist = [(node.x - rnd_node.x) ** 2 + (node.y - rnd_node.y)
** 2 for node in node_list]
minind = dlist.index(min(dlist))
return minind
@staticmethod
def calc_distance_and_angle(from_node, to_node):
dx = to_node.x - from_node.x
dy = to_node.y - from_node.y
d = math.hypot(dx, dy)
theta = math.atan2(dy, dx)
return d, theta
def move_robot(path, map):
for ii in range(len(path)):
path[ii] = move.node_2_goal(path[ii][0:2], path[ii][2], cmap=map)
path = path[::-1]
move.move_along_path(path)
def main():
# Test
# Map
map = cmap.Map()
# Set Initial parameters
start = map.position_2_map(np.hstack([map.get_robot_position(), map.get_robot_orientation()]))
goal = map.position_2_map(np.array([5.0, -7.0, 3.14/2]))
rrt = RRT(start, goal, map)
# Search Path with RRT
path = rrt.planning(animation=show_animation)
if path is None:
print("Cannot find path")
rrt.draw_graph()
plt.show()
else:
print("found path!!")
rrt.draw_graph()
rrt.draw_path(path)
plt.pause(0.01) # Need for Mac
plt.show()
# Move Robot
move_robot(path, map)
if __name__ == '__main__':
main()
|
38d5f2737700ee389adb5a0a50f421846114ad81 | Olivia-Zhang-08/Olivia_Files | /CS50/pset6/bleep/bleep.py | 1,129 | 3.796875 | 4 | # Olivia Zhang, P-Set 6, Bleep
import sys
from cs50 import get_string
# in this file, one function main is defined, which is called at the end of the file
def main():
# accept only exactly 2 command-line arguments; if not 2, exit with usage message, which automates return 1
if len(sys.argv) != 2:
sys.exit("Usage: python bleep.py dictionary")
# create set to store banned words
bannedwords = set()
# open imported dictionary and add to set of banned words
txt = open(sys.argv[1], "r")
for line in txt:
bannedwords.add(line.rstrip("\n"))
txt.close()
# prompt user for message to censor and split into individual words in a list
message = get_string("What message would you like to censor?\n")
messagesplit = message.split()
# check each word against the banned words list and censor with * accordingly
for word in messagesplit:
if word.lower() in bannedwords:
print("*" * len(word), end=" ")
else:
print(word, end=" ")
print()
# call main
if __name__ == "__main__":
main()
|
e947f3a07e504f7ed7db540a4d0c886cf2e8a402 | VigneshPeriasami/hackerrank | /permuted_divisibility.py | 1,473 | 3.78125 | 4 | #!/usr/bin/python
def tables():
tables = set()
for x in range(13, 126):
tables.add(x*8)
return tables
class ExtNumber:
def __init__(self, n):
self.number = n
self.number_frequency = { x:0 for x in range(0,10) }
self.number_stack = set(map(self.read_int, str(n)))
def read_int(self, n_i):
n_i = int(n_i)
self.number_frequency[n_i] += 1
return n_i
def compare_two_digit(self, k):
[o,t] = map(int, str(k))
digi1 = o*10 + t
digi2 = t*10 + o
if (digi1 % 8 == 0 or digi2 % 8 == 0):
return True
else:
return False
def compare_with(self, k):
if len(str(self.number)) == 1 and self.number % 8 == 0:
return True
elif len(str(self.number)) == 2:
return self.compare_two_digit(self.number)
stack_frequency = {}
for d in str(k):
d = int(d)
if d in stack_frequency:
stack_frequency[d] += 1
else:
stack_frequency[d] = 1
if all(stack_frequency[key] <= self.number_frequency[key]
for key in stack_frequency.keys()):
return True
else:
return False
if __name__ == "__main__":
t = int(raw_input())
safe_stack = tables()
numbers = [ int(raw_input()) for i in range(t) ]
for n in numbers:
extNumber = ExtNumber(n)
not_found = True
for d in safe_stack:
if extNumber.compare_with(d):
print "YES"
not_found = False
break
if not_found:
print "NO"
|
6188e582b76bb984ca49476a5a7c3c8c597c317d | anschauf/master_thesis | /src/evaluators/evaluator_base.py | 1,171 | 4.125 | 4 | from abc import ABC, abstractmethod
class Evaluator(ABC):
@abstractmethod
def evaluate(self, results: list, targets: list) -> list:
"""
Evalutes the results compared to the target
:param results: NMT results
:param targets: gold results
:return: the evaluated scores in a list
"""
pass
def _check_params(self, results: list, targets: list):
"""
Base checking for correct parameter input, used in all derived classes.
It checks:
- correct type (lists)
- equal length of lists
- no empty lists
:param results:
:param targets:
:return:
"""
if not isinstance(results, list) or not isinstance(targets, list):
raise Exception('Parameters provided are not of type `list`.')
list_length = len(results)
second_length = len(targets)
if list_length == 0 or second_length == 0:
raise Exception('List provided as parameter must not be empty.')
if list_length != second_length:
raise Exception('List provided as parameters are not of the same length.') |
c4c17e420ae764a5f219148a778b81529a4addbc | printfoo/leetcode-python | /problems/0849/maximize_distance_to_closest_person.py | 743 | 3.828125 | 4 | """
Solution for Maximize Distance to Closest Person, Time O(n) Space O(1).
Idea:
Count 0s and divide 2.
"""
# solution
class Solution:
def maxDistToClosest(self, seats: "List[int]") -> "int":
middle, this, begin, end = 0, 0, 0, 0
for s in seats:
if s == 0: this += 1
if s == 1:
middle = max(middle, this)
this = 0
middle = max(middle, this)
for s in seats:
if s == 1: break
begin += 1
for s in seats[::-1]:
if s == 1: break
end += 1
return max(begin, end, int((middle + 1) / 2))
# Main.
if __name__ == "__main__":
seats = [1,0,0,0]
print(Solution().maxDistToClosest(seats))
|
2300188b58ce79821854d887207f91773ab47537 | 31784/Virtual_Pet | /VirtualPet.py | 1,765 | 4.1875 | 4 | class VirtualPet:
"""An implementation of a Virtual pet"""
#contructor method
def __init__(self,name):
#attributes
self.name=name
self.hunger= 50
print("Hi,I've been born and I am called {0}".format(name))
#methods
def talk(self):
print("Hello I am your new pet")
def eat(self,Feed):
if Feed == "1":
self.hunger=self.hunger - 20
elif Feed == "2":
self.hunger=self.hunger - 10
self.hunger=self.hunger + 10
def age(self):
def report(self):
return {"Name":self.name,"Hunger":self.hunger,"Age":self.age}
def DisplayMenu():
print()
print('MENU')
print()
print('1. Feed pet')
rpint('2. Status of pet')
print()
print('Select an option from the menu (or enter q to quit simulation): ', end='')
def GetMenuChoice():
Choice = input()
print()
return Choice.lower()[0]
def Feed():
Feed=input("What would you like to feed? (1 for Bannana, 2 for chocolate, anything else to not feed): ")
if Feed == "1":
print()
print("yummy bannana")
elif Feed == "2":
print()
print("CHOCOLATE I LOVE YOU!!!")
else:
print("But why do you not want to feed me :(")
def main():
name=input("What do you want to call your pet: ")
#instantiation
pet_one=VirtualPet(name)
#call the talk method
pet_one.talk()
Choice = ''
while Choice != 'q':
DisplayMenu()
Choice = GetMenuChoice()
if Choice == '1':
Feed()
elif Choice == '2':
print(pet_one.report())
else:
print("End simulation")
if __name__=="__main__":
main()
|
6cc464b78403dd73161a1be58afdcc9706b3c08c | akniels/Data_Structures | /Project_2/Problem_3.py | 6,842 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 21 15:28:56 2020
@author: parallels
"""
import sys
from heapq import heappush, heappop, heapify
from collections import defaultdict
class Node(object):
def __init__(self,value = None, letter = None):
self.value = value
self.left = None
self.right = None
self.letter = letter
self.binary = None
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self,left):
self.left = left
def set_right_child(self, right):
self.right = right
def set_binary(self, binary):
self.binary = binary
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.right != None
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.value),
if self.right:
self.right.PrintTree()
class Tree():
def __init__(self):
self.root = None
def set_root(self,Node):
self.root = Node
def get_root(self):
return self.root
def get_binary(tree):
binary = {}
root = tree.get_root()
def get_bin(binar, node):
if node.letter is not None:
# if
if not binar:
binary[node.letter] = str(node.binary)
else:
binary[node.letter] = binar
else:
get_bin(binar+str(node.left.binary), node.left)
get_bin(binar+str(node.right.binary), node.right)
get_bin("",root)
return binary
def huffman_encoding(data):
if data == "" :
return '-1', None
Huffman_tree = Tree()
d = defaultdict(int)
for ch in data:
d[ch] += 1
d = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}
heap = [[wt,sym] for sym, wt in d.items()]
if len(heap) == 1:
left = heappop(heap)
node = Node(left[0], left[1])
node.binary = 0
Huffman_tree.set_root(node)
else:
left = heappop(heap)
right = heappop(heap)
l_node = Node(left[0], left[1])
r_node = Node(right[0], right[1])
Parent_node = Node(left[0]+right[0])
Parent_node.set_left_child(l_node)
Parent_node.set_right_child(r_node)
l_node.set_binary(0)
r_node.set_binary(1)
Huffman_tree.set_root(Parent_node)
while len(heap) > 1 :
n = heappop(heap)
left_node = Node(n[0], n[1])
left_node.binary = 0
nn = heappop(heap)
right_node = Node(nn[0], nn[1])
right_node.binary = 1
parent_value = n[0] + nn[0]
pa_node = Node(parent_value)
pa_node.left = left_node
pa_node.right = right_node
grandparent_value = Huffman_tree.get_root().value + pa_node.value
grandparent_node = Node(grandparent_value)
grandparent_node.left = Huffman_tree.get_root()
grandparent_node.right = pa_node
Huffman_tree.get_root().binary = 0
pa_node.binary = 1
Huffman_tree.set_root(grandparent_node)
dictionary = get_binary(Huffman_tree)
return "".join([dictionary[a] for a in data]), Huffman_tree
def huffman_decoding(data,tree):
if data == "-1" :
return '-1'
data = [char for char in data]
decoded = list()
index_tracker = 0
current_node = tree.get_root()
if current_node.left is None and current_node.right is None:
for char in data:
decoded.append(current_node.letter)
else:
while index_tracker <= (len(data)-1):
if current_node.letter is not None:
decoded.append(current_node.letter)
current_node = tree.get_root()
# index_tracker+=1
continue
else:
bin_value = data[index_tracker]
if bin_value == '0':
current_node = current_node.get_left_child()
index_tracker+=1
else:
current_node = current_node.get_right_child()
index_tracker+=1
decoded.append(current_node.letter)
return "".join([ d for d in decoded])
if __name__ == "__main__":
codes = {}
#Test Case 1 #
a_great_sentence = "The bird is the word"
print ("The size of the data is: {}\n".format(sys.getsizeof(a_great_sentence)))
print ("The content of the data is: {}\n".format(a_great_sentence))
encoded_data, tree = huffman_encoding(a_great_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(encoded_data))
decoded_data = huffman_decoding(encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(decoded_data)))
print ("The content of the encoded data is: {}\n".format(decoded_data))
#Test Case 2 #
empty_sentece = ""
print ("The size of the data is: {}\n".format(sys.getsizeof(empty_sentece)))
print ("The content of the data is: {}\n".format(empty_sentece))
empty_encoded_data, empty_tree = huffman_encoding(empty_sentece)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(empty_encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(empty_encoded_data))
empty_decoded_data = huffman_decoding(empty_encoded_data, tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(empty_decoded_data)))
print ("The content of the encoded data is: {}\n".format(empty_decoded_data))
a_sentence = "aaaaaaaaaaaa"
print ("The size of the data is: {}\n".format(sys.getsizeof(a_sentence)))
print ("The content of the data is: {}\n".format(a_sentence))
a_encoded_data, a_tree = huffman_encoding(a_sentence)
print ("The size of the encoded data is: {}\n".format(sys.getsizeof(int(a_encoded_data, base=2))))
print ("The content of the encoded data is: {}\n".format(a_encoded_data))
a_decoded_data = huffman_decoding(a_encoded_data, a_tree)
print ("The size of the decoded data is: {}\n".format(sys.getsizeof(a_decoded_data)))
print ("The content of the encoded data is: {}\n".format(a_decoded_data)) |
6eebf94e3c29de2cbd196e6d61fc19be4153a9b1 | zaghir/python | /python-for-beginner/01-first-python-project/while_exercises.py | 426 | 3.796875 | 4 | # print_squares_upto_limit(30)
# //For limit = 30, output would be 1 4 9 16 25
#
# print_cubes_upto_limit(30)
# //For limit = 30, output would be 1 8 27
def print_squares_upto_limit(limit):
i = 1
while i * i < limit:
print(i*i, end = " ")
i = i + 1
def print_cubes_upto_limit(limit):
i = 1
while i * i * i < limit:
print(i*i*i, end = " ")
i = i + 1
print_cubes_upto_limit(80) |
3659314b5d465615726032db69a210aa7ee5238f | lucaschf/python_exercises | /exercise_7.py | 1,841 | 3.78125 | 4 | # Faça um programa que percorre uma lista com o seguinte formato: [['Brasil', 'Italia', [10, 9]],
# ['Brasil', 'Espanha', [5, 7]], ['Italia', 'Espanha', [7,8]]]. Essa lista indica o número de faltas que cada time fez
# em cada jogo. Na lista acima, no jogo entre Brasil e Itália, o Brasil fez 10 faltas e a Itália fez 9.
# O programa deve imprimir na tela:
# a) o total de faltas do campeonato
# b) o time que fez mais faltas
# c) o time que fez menos faltas
# [
# ['Brasil', 'Italia', [10, 9]],
# ['Brasil', 'Espanha', [5, 7]],
# ['Italia', 'Espanha', [7, 8]]
# ]
def championship_result(result):
total_faults = 0
championship_faults = dict()
more_faults = ""
less_faults = ""
for item in result:
match_faults = item[-1] # last item is the faults list
total_faults += sum(match_faults)
for i in range(2): # the match has only two teams
team = item[i]
team_faults = match_faults[i]
if not bool(championship_faults):
more_faults = team
less_faults = team
if team in championship_faults: # checks if the team already had faults com
team_faults += championship_faults[team]
championship_faults[team] = team_faults
if team_faults > championship_faults[more_faults]:
more_faults = team
elif team_faults < championship_faults[less_faults]:
less_faults = team
yield "total_faults", total_faults
yield "more_faults", more_faults
yield "less_faults", less_faults
yield "championship_faults", championship_faults
if __name__ == "__main__":
matches = [["Brasil", "Italia", [10, 9]], ["Brasil", "Espanha", [5, 7]], ["Italia", "Espanha", [7, 8]]]
print(dict(championship_result(matches)))
|
e933bc3af41dd05e85a6bbff4b4c18e70e1a786c | oskip/IB_Algorithms | /Invert.py | 885 | 4.3125 | 4 | # Given a binary tree, invert the binary tree and return it.
# Look at the example for more details.
#
# Example :
# Given binary tree
#
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# invert and return
#
# 1
# / \
# 3 2
# / \ / \
# 7 6 5 4
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root : root node of tree
# @return the root node in the tree
def invertTree(self, root):
if not root: return None
if not root.right and not root.left: return root
self.invertIter(root)
return root
def invertIter(self, root):
root.left, root.right = root.right, root.left
if root.left: self.invertIter(root.left)
if root.right: self.invertIter(root.right) |
ad0e6ed96cc4ddcecca9f425a0a33c54331ec5b1 | AGiantSquid/advent_of_code | /python/2020/day_3/day_3.py | 1,452 | 3.546875 | 4 | #!/usr/bin/env python3
'''
Solves Advent of Code problem for day 3.
'''
from functools import reduce
from operator import mul
from aoc_utils import get_aoc_data_for_challenge
def prod(list_of_ints):
'''Return the product of list of ints.
This method is built into numpy,
but recreated here to keep imports light.'''
return reduce(mul, list_of_ints)
def get_trees_hit_part_1(data):
'''Calculate trees hit moving right 3 spaces.'''
return calculate_trees_hit(data, 3, 1)
def get_trees_hit_part_2(data):
'''Calculate trees hit with multiple strategies.'''
strategies = (
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
)
return prod([calculate_trees_hit(data, *_) for _ in strategies])
def calculate_trees_hit(data, x, skip=1):
'''Calculate trees hit with variable moves.'''
trees_hit = 0
position = 0
for i, el in enumerate(data):
if i == 0:
continue
if skip > 1 and i % skip != 0:
continue
position += x
while position >= len(el):
el = el + el
coor = el[position]
if coor == '#':
trees_hit += 1
return trees_hit
if __name__ == '__main__':
pattern_data = get_aoc_data_for_challenge(__file__)
result = get_trees_hit_part_1(pattern_data)
print(result) # 276
result = get_trees_hit_part_2(pattern_data)
print(result) # 7812180000
|
fc4f41a06bfdf27a054580943515ff30289b0f08 | w2kzx80/py | /dz6/3.py | 656 | 3.71875 | 4 |
class Worker:
def __init__(self, name, surname, position, wage, bonus):
self.name = name
self.surname = surname
self.position = position
self._income = { "wage":wage, "bonus":bonus }
class Position(Worker):
def __init__(self, name, surname, position, wage, bonus):
super().__init__(name, surname, position, wage, bonus)
def get_full_name(self):
return f"{self.name} {self.surname}"
def get_total_income(self):
return self._income['wage'] + self._income['bonus']
myP = Position("Roman", "Apanovici", "developer", 2000, 500)
print(myP.get_full_name())
print(myP.get_total_income()) |
e3b25d9b357064460a9ceee35240aea43c1de0ba | alexlevine1220/robotcar | /practice/python_program.py | 2,929 | 4.0625 | 4 | # A13528608
# HELPER
# %%
def distance(p1, p2):
"""Calculate distance between p1, p2.
Args:
p1 (float, float): coordinates of p1
p2 (float, float): coordinates of p2
Returns:
float: distance
"""
return ((p2[1] - p1[1]) ** 2 + (p2[0] - p1[0]) ** 2) ** 0.5
def computeLineThroughTwoPoints(p1, p2):
"""
Args:
p1 (float, float): coordinates of p1
p2 (float, float): coordinates of p2
Returns:
(float, float, float): a, b, c that satisfies a x + b y + c = 0 where a ^ 2 + b ^ 2 = 1
"""
a = p1[1] - p2[1]
b = p2[0] - p1[0]
c = (p1[0] - p2[0]) * p1[1] + (p2[1] - p1[1]) * p1[0]
norm = (a ** 2 + b ** 2) ** 0.5
return (a / norm, b / norm, c / norm)
def calculateShortestPoint(q, p1, p2):
"""Calculates shortest Point between point q and segment (p1, p2)
Args:
q (float, float): point coordinate
p1 (float, float): one point coordinate of segment
p2 (float, float): another point coordinate of segment
Returns:
(float, float): shortest distance
"""
x1, y1 = p1
x2, y2 = p2
x3, y3 = q
dx = x2 - x1
dy = y2 - y1
if dx == 0 and dy == 0:
return -1, -1
u = ((x3 - x1) * dx + (y3 - y1) * dy) / (dx * dx + dy * dy)
if u > 1:
u = 1
elif u < 0:
u = 0
return x1 + u * dx, y1 + u * dy
def distance_point_segment(q, p1, p2):
return distance(calculateShortestPoint(q, p1, p2), q)
def computeDistancePointToPolygon(P, q):
""" calculate distance from a point to polygon
Args:
P ([float, float]): list of points consists of polygon
q ([]): [description]
Returns:
[type]: [description]
"""
if len(P) < 3:
raise(Exception("Polygon must have more than 2 vertices"))
minDist = float('inf')
for i in range(len(P)):
minDist = min(minDist, distance_point_segment(
q, P[i], P[(i + 1) % len(P)]))
return minDist
def computeTangentVectorToPolygon(P, q):
"""
Args:
P ([float, float]): list of points consists of polygon
q ([]): [description]
Returns:
"""
minDist = computeDistancePointToPolygon(P, q)
indices = []
for i in range(len(P)):
if minDist == distance_point_segment(q, P[i], P[(i + 1) % len(P)]):
indices.append(i)
if len(indices) == 2:
px, py = P[indices[1]] if distance(q, P[indices[1]]) < distance(
q, P[(indices[1] + 1) % len(P)]) else P[(indices[1] + 1) % len(P)]
qx, qy = q
dx = qx - px
dy = qy - py
x = -dy
y = dx
norm = (x ** 2 + y ** 2) ** 0.5
return x / norm, y / norm
else:
# segment
a, b, c = computeLineThroughTwoPoints(
P[indices[0]], P[(indices[0] + 1) % len(P)])
return b, -a
q = [0, 1.1]
P = [[0, 0], [2, 0], [1, 1]]
|
766bcce96dc83faeaa85f4951176786ff4d6eedb | lukejskim/sba19-seoulit | /Sect-A/source/sect07_class/s742_instance_var.py | 498 | 3.65625 | 4 | # 인스턴스 변수(인스턴스간 공유 안됨)
class Cat:
def __init__(self, name):
self.name = name
self.tricks = [] # 인스턴스 변수 선언
def add_trick(self, trick):
self.tricks.append(trick) # 인스턴스 변수에 값 추가
cat1 = Cat('하늘이')
cat2 = Cat('야옹이')
cat1.add_trick('구르기')
cat2.add_trick('두발로 서기')
cat2.add_trick('죽은척 하기')
print(cat1.name, ':', cat1.tricks)
print(cat2.name, ':', cat2.tricks)
|
2486813bf87962c8c603545711d22a35588e213e | matthieujac/Twitter-Clone-Language-Moderator | /python-ml-service/utils.py | 349 | 3.671875 | 4 | import nltk
from nltk.corpus import stopwords
import string
print("Downloading English Stop words.")
nltk.download('stopwords')
def text_process(mess):
nopunc = [char for char in mess if char not in string.punctuation]
nopunc = ''.join(nopunc)
return [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
|
d6a2b970afc849c972314f82381da300f3affc37 | Abusagit/practise | /Stepik/pycourse/Cipher.py | 908 | 3.875 | 4 | import simplecrypt
"""САЙТ: https://pypi.org/project/simple-crypt/"""
string = ''
with open("encrypted.bin", "rb") as inp:
encrypted = inp.read()
with open("passwords.txt", 'r') as file:
file = file.readlines()
for i in range(len(file)):
file[i] = file[i].strip()
print(encrypted)
print(file)
# for password in file:
# try:
# x = simplecrypt.decrypt(password, encrypted).decode('utf8') ##ОБЯЗАТЕЛЬНО для кодировки из байтов!!!!
# except simplecrypt.DecryptionException: ## Ожидание неправильного пароля и продолжение итерации
# print('%s is Incorrect password' % password)
# else:
# print(x, '%s is correct password' % password, sep='\n\n')
# break
password = 'Asdkh12dasdlhulkra'
y = simplecrypt.encrypt(password, 'Привет')
print(y)
|
d4223d72cf5327e84026272c01914783bb8f8cc0 | tavalenzuelag/Optimizacion | /Tarea1/visualization.py | 299 | 3.828125 | 4 | from matplotlib import pyplot as plt
def visualization(error_list, name = None):
iterations = [x for x in range(len(error_list))]
plt.plot(iterations, error_list, '.')
if name is not None:
plt.title(name)
plt.xlabel('n° Iteración')
plt.ylabel('Error')
plt.show()
|
86d951c83554fb3f51462050065dd9d39de4e06c | BenGH28/neo-runner.nvim | /testfiles/run.py | 92 | 3.71875 | 4 | print("Hello world from python")
name = input("enter in you name: ")
print("thanks", name)
|
efaea333c58e31283bfa3f70c6bc16e79c8ad159 | BoswellBao/PyLearn | /shiyanlou/IteratorsExp.py | 820 | 3.75 | 4 | '''
Python 迭代器(Iterators)对象在遵守迭代器协议时需要支持如下两种方法:
__iter__(),返回迭代器对象自身。这用在 for 和 in 语句中。
__next__(),返回迭代器的下一个值。如果没有下一个值可以返回,那么应该抛出 StopIteration 异常。
'''
class Counter(object):
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self): # 如果没有这个方法,就会报类型错误-->TypeError: 'Counter' object is not iterable
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
a = Counter(5, 10)
for i in a:
print(i, end=' ')
print()
print(type(a))
|
ab7c6a65655ba4336f245992203186a045f787f5 | JasmineRain/Algorithm | /Python/Tree/113_Medium_路径总和II.py | 929 | 3.765625 | 4 | from collections import deque
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
ans = []
def backtrack(root, value, trace):
value += root.val
if value == sum and not root.left and not root.right:
ans.append(trace + [root.val])
return
if root.left:
backtrack(root.left, value, trace + [root.val])
if root.right:
backtrack(root.right, value, trace + [root.val])
if not root:
return []
backtrack(root, 0, [])
return ans
# if __name__ == "__main__":
# S = Solution()
# print(S.isSameTree(nums1=[2], nums2=[]))
|
9fde2c404e2bc2eccfedf496f76413593e92c0b8 | iorzt/leetcode-algorithms | /add_two_numbers.py | 1,774 | 3.828125 | 4 | # coding=utf-8
"""
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
128ms
>64.36
https://leetcode.com/submissions/detail/148243044/
"""
def addTwoNumbers_v1(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0)
carry = 0
l3_pointer = l3
l3.next = l3_pointer
while l1 or l2:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
temp = ListNode(l1_val + l2_val + carry)
if temp.val > 9:
carry = 1
temp.val = temp.val - 10
else:
carry = 0
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
l3_pointer.next = temp
l3_pointer = l3_pointer.next
if carry == 1:
l3_pointer.next = ListNode(1)
return l3.next
if "__main__" == __name__:
solution = Solution()
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
l3 = solution.addTwoNumbers_v1(l1, l2)
while l3:
print(l3.val, " -> ")
l3 = l3.next
|
e8bcadbb1d14c5372d495c85e7c7dfb53b93a688 | serapred/academy | /ffi/tcpauto.py | 1,800 | 3.65625 | 4 | """
Create a finite automaton that has three states. Finite automatons are the same as finite state machines for our purposes.
Our simple automaton, accepts the language of A, defined as {0, 1} and should have three states: q1, q2, and q3. Here is the description of the states:
q1 is our start state, we begin reading commands from here
q2 is our accept state, we return true if this is our last state
And the transitions:
q1 moves to q2 when given a 1, and stays at q1 when given a 0
q2 moves to q3 when given a 0, and stays at q2 when given a 1
q3 moves to q2 when given a 0 or 1
The automaton should return whether we end in our accepted state (q2), or not (true/false).
Your task
You will have to design your state objects, and how your Automaton handles transitions. Also make sure you set up the three states, q1, q2, and q3 for the myAutomaton instance. The test fixtures will be calling against myAutomaton.
As an aside, the automaton accepts an array of strings, rather than just numbers, or a number represented.
new map:
CLOSED: APP_PASSIVE_OPEN -> LISTEN
CLOSED: APP_ACTIVE_OPEN -> SYN_SENT
LISTEN: RCV_SYN -> SYN_RCVD
LISTEN: APP_SEND -> SYN_SENT
LISTEN: APP_CLOSE -> CLOSED
SYN_RCVD: APP_CLOSE -> FIN_WAIT_1
SYN_RCVD: RCV_ACK -> ESTABLISHED
SYN_SENT: RCV_SYN -> SYN_RCVD
SYN_SENT: RCV_SYN_ACK -> ESTABLISHED
SYN_SENT: APP_CLOSE -> CLOSED
ESTABLISHED: APP_CLOSE -> FIN_WAIT_1
ESTABLISHED: RCV_FIN -> CLOSE_WAIT
FIN_WAIT_1: RCV_FIN -> CLOSING
FIN_WAIT_1: RCV_FIN_ACK -> TIME_WAIT
FIN_WAIT_1: RCV_ACK -> FIN_WAIT_2
CLOSING: RCV_ACK -> TIME_WAIT
FIN_WAIT_2: RCV_FIN -> TIME_WAIT
TIME_WAIT: APP_TIMEOUT -> CLOSED
CLOSE_WAIT: APP_CLOSE -> LAST_ACK
LAST_ACK: RCV_ACK -> CLOSED
"""
# TODO
|
fb7d49c47e182d60ab75f57cb452ba1837182561 | saransh-khobragade/Python | /syntax/dictionary.py | 1,193 | 4.09375 | 4 | #blank dicktionary
dic={}
dic["a"]=5
dic["b"]=10
#how to loop over dictionary
for x, y in dic.items():
print(x, y)
for x in dic.keys():
print(x)
for y in dic.values():
print(y)
#how to check key exists in dictionary
if 'x' in dic:
dic['x']+=1
else:
dic['x']=1
# Set unique but no unordered
set_itmes = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
print(set_itmes)
# Dictionary key value pairs can use immutable keys mutabale values
dictionary = {
'A': 12,
'B': 122,
'C': 45,
'D': 76,
'E': 23,
'F': 2323
}
print(dictionary)
print(dictionary.keys())
print(dictionary.values())
#add item or update to dictionary
dictionary['G'] = 31
dictionary.update({'G': 32})
#loop in dict
for x, y in dictionary.items():
print(x, y)
#sorting dictionary by its values and converting to list to tuple
print(sorted(dictionary.items(), key=lambda x:x[1] ,reverse=False))
#sorting dictionary by its keys and converting to list to tuple
print(sorted(dictionary.items(), key=lambda x:x[0] ,reverse=False))
|
9d8b06d95eb152e6e22f358a6517a1ee8cf9d9c8 | MichalxPZ/PUT-HackerRank-Python | /Medium/CheckTheCoprimes.py | 357 | 3.75 | 4 | import math
def checkthecoprimes(liczba):
ogranicznik = liczba // 2
for i in range(ogranicznik, 1, -1):
if math.gcd(liczba, i) == 1:
return (i)
return (1)
def main():
N = int(input())
for i in range(N):
liczba = int(input())
print(checkthecoprimes(liczba))
if __name__ == '__main__':
main()
|
ed0f91ae83b72ff0fef24d5fce18b7ab2817b5fb | rafaelperazzo/programacao-web | /moodledata/vpl_data/173/usersdata/273/82248/submittedfiles/moedas.py | 360 | 3.984375 | 4 | # -*- coding: utf-8 -*-
a=int(input('Digite o valor de a: '))
b=int(input('Digite o valor de b: '))
c=int(input('Digite o valor de c: '))
if c%a==0 and c%b!=0:
print(c/a)
print('0')
elif c%a!=0 and c%b==0:
print('0')
print(c/b)
d=c/b
elif c==(c//a)+(c/b) and c==d:
print (c//a)
print (c/b)
|
7ebf6572effb4532a4fbc9ae27696b7517fb046f | PranavAnand587/Hangman-Game | /story.py | 1,740 | 3.859375 | 4 | storyText = '''You open your eyes and realize that you are not in the safety of your house. Your hands are tied, and you
cannot move.You look around you , hoping to find some way to escape. There are no windows, just a single
lightbulb hanging above you in the darkroom and a chalkboard in front of you.The rest of the room was pitch black.
Suddenly, you hear the footsteps approaching you. You can't see anything more than a man with a
white mask standing in front of the chalkboard. The man in the mask takes out a pistol and points it at you.
The Masked Man said : "Here's what's going to happen...we're going to play a game of hangman. If you don't follow the rules,
then I will shoot you on the spot.
Now, to start the game, I will need you to put your head through that rope you see in front of you,"
"Good. Now here's how the game works; I have a nice game of hangman on this chalkboard you see here.
Now obviously you've played hangman before, but this time it has more stakes, which makes it all the
more fun! You are going to have to guess the letters of a word here.
If you get a letter or letters correct, I will add it to the word. However, if you guess a letter
incorrectly, then I will add a body part to the stick figure. Six incorrect guesses later I'll draw
an entire stick figure and then you will be hung. If you win, I will free you. Do you understand the
rules?"'''
playText = '''You nodded your head, too terrified to say any word
Pulling the slide of the gun he said : "Perfect, Let's begin!" '''
exitText = '''The masked man kicks the chair from underneath him, hanging you. You start to choke
desperately for air, as the rope swung back and forth. You start to limp and eventually stop moving. ''' |
a23776fd2e0855f3f4bb36bd9e50159d2cc0263a | davisonWang/Python_test | /city_functions.py | 296 | 3.765625 | 4 | ### 动手试一试
def get_formatted_name(city, country, population=''):
if population:
city_full_name = city + ' ' + country + ' ' + population
return city_full_name.title()
else:
city_full_name = city + ' ' + country
return city_full_name.title()
|
35fbf359ea587c9f61a555112ad44c56f54269d0 | AFatWolf/cs_exercise | /8.3. Implementing sorting/ssort.py | 344 | 3.671875 | 4 | def ssort(xs):
for i in range(0, len(xs) - 1):
maxval = xs[i]
maxpos = i
for j in range(i + 1, len(xs)):
if xs[j] > maxval:
maxval = xs[j]
maxpos = j
if i != maxpos:
tmp = xs[i]
xs[i] = maxval
xs[maxpos] = tmp
b = [5,2,3,1,4]
print("Before sort:", b)
ssort(b)
print("After sort:", b)
|
e601b70a9b0c90e26a254b61247373305f95ceb4 | somecallmetim/csc_849_hw1 | /InvertedIndexConstructor.py | 2,910 | 3.515625 | 4 | from nltk.stem import PorterStemmer
import string
# class to help track data for each term in our document list vocabulary
class InvertedIndexTerm:
# constructor
def __init__(self, name, docId):
# fields
self.__name = name
self.__frequency = 1
self.__postingList = []
#start with the first docId the term is associated with in its postingList
self.__postingList.append(docId)
# add new occurance of term and increment frequency in which it appears
def addPosting(self, docId):
# only add the docId if it's not already in the postingList
if docId not in self.__postingList:
self.__postingList.append(docId)
self.__frequency += 1
def getPostingList(self):
return self.__postingList
def getFrequency(self):
return self.__frequency
def getName(self):
return self.__name
# from https://www.dotnetperls.com/punctuation-python
def remove_punctuation(value):
result = ""
for c in value:
# If char is not punctuation, add it to the result.
if c not in string.punctuation:
result += c
return result
def createInvertedIndex():
stemmer = PorterStemmer()
# this is the document (or hypothetical set of documents) we're scanning from
file = open("documents.txt", "r")
currentDocId = 0
invertedIndex = {}
# parse document line by line and add words to inverted index
for line in file:
# scane each line word for word
for word in line.split():
# individual documents in this toy example are delineated by tags ie <DOC 1> ~~~ </DOC 1>
# this part of the if block detects document tags and sets the docId accordingly
if "<" in word and "</" not in word:
word = line.strip('<DOC ')
word = word.split('>')
currentDocId = word[0]
elif ">" in word:
pass
# if the word/line isn't a document tag
else:
# makes the term all lower case
key = str(word).lower()
# attempts to remove all punctuation
key = remove_punctuation(key)
# if a word is all punctuation, ie ..., skips the word completely
if key == "":
break
# stems the now lower case and punctuation free word
key = stemmer.stem(key)
# if key isn't in the inverted index, it creates a new object and adds it to inverted index
if key not in invertedIndex:
invertedIndex[key] = InvertedIndexTerm(key, currentDocId)
# if key is in inverted index, program attempts to add new posting
else:
invertedIndex[key].addPosting(currentDocId)
return invertedIndex
|
ca15c6e888d17156884615ebcb31bbd980f44b8c | PLUSLINKID/petri-net | /petri_net.py | 4,321 | 3.609375 | 4 | """
Modeling approach:
* define Petri nets in terms of their transactions
* define transactions in terms of the actions of their arcs
* define arcs in terms with their action on their in- or outgoing place
* define places as basic containers
Run with python 2 or 3, for the example coded up in in __main__, via
python petri_net.py --firings 10 --marking 1 2 3 2
References:
* https://en.wikipedia.org/wiki/Petri_net
* https://www.amazon.com/Understanding-Petri-Nets-Modeling-Techniques/dp/3642332773
"""
class Place:
def __init__(self, holding):
"""
Place vertex in the petri net.
:holding: Numer of token the place is initialized with.
"""
self.holding = holding
class ArcBase:
def __init__(self, place, amount=1):
"""
Arc in the petri net.
:place: The one place acting as source/target of the arc as arc in the net
:amount: The amount of token removed/added from/to the place.
"""
self.place = place
self.amount = amount
class Out(ArcBase):
def trigger(self):
"""
Remove token.
"""
self.place.holding -= self.amount
def non_blocking(self):
"""
Validate action of outgoing arc is possible.
"""
return self.place.holding >= self.amount
class In(ArcBase):
def trigger(self):
"""
Add tokens.
"""
self.place.holding += self.amount
class Transition:
def __init__(self, out_arcs, in_arcs):
"""
Transition vertex in the petri net.
:out_arcs: Collection of ingoing arcs, to the transition vertex.
:in_arcs: Collection of outgoing arcs, to the transition vertex.
"""
self.out_arcs = set(out_arcs)
self.arcs = self.out_arcs.union(in_arcs)
def fire(self):
"""
Fire!
"""
not_blocked = all(arc.non_blocking() for arc in self.out_arcs)
# Note: This would have to be checked differently for variants of
# petri nets that take more than once from a place, per transition.
if not_blocked:
for arc in self.arcs:
arc.trigger()
return not_blocked # return if fired, just for the sake of debuging
class PetriNet:
def __init__(self, transitions):
"""
The petri net runner.
:transitions: The transitions encoding the net.
"""
self.transitions = transitions
def run(self, firing_sequence, ps):
"""
Run the petri net.
Details: This is a loop over the transactions firing and then some printing.
:firing_sequence: Sequence of transition names use for run.
:ps: Place holdings to print during the run (debugging).
"""
print("Using firing sequence:\n" + " => ".join(firing_sequence))
print("start {}\n".format([p.holding for p in ps]))
for name in firing_sequence:
t = self.transitions[name]
if t.fire():
print("{} fired!".format(name))
print(" => {}".format([p.holding for p in ps]))
else:
print("{} ...fizzled.".format(name))
print("\nfinal {}".format([p.holding for p in ps]))
def make_parser():
"""
:return: A parser reading in some of our simulation paramaters.
"""
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--firings', type=int)
parser.add_argument('--marking', type=int, nargs='+')
return parser
if __name__ == "__main__":
args = make_parser().parse_args()
ps = [Place(m) for m in args.marking]
ts = dict(
t1=Transition(
[Out(ps[0])],
[In(ps[1]), In(ps[2])]
),
t2=Transition(
[Out(ps[1]), Out(ps[2])],
[In(ps[3]), In(ps[0])]
),
)
from random import choice
firing_sequence = [choice(list(ts.keys())) for _ in range(args.firings)] # stochastic execution
#firing_sequence = ["t1", "t1", "t2", "t1"] # alternative deterministic example
petri_net = PetriNet(ts)
petri_net.run(firing_sequence, ps)
|
8aeaa404bed3714e1bd9126ce2149baf7d5053b0 | maxiumalong/m_c_problem | /search_initial.py | 2,317 | 3.65625 | 4 | def heap_adjust(lists, pos, length): # 堆排序(升序排列,构建大根堆):
max_ = pos
lchild = 2 * pos + 1 # 由于lists下表从0开始,所以左右孩子下标为2*pos+1,2*pos+2
rchild = 2 * pos + 2
if max_ < length // 2: # 注意符号是<,堆调整时,必定是从(length//2)-1开始
if lchild < length and lists[lchild][3] > lists[max_][3]:
max_ = lchild
if rchild < length and lists[rchild][3] > lists[max_][3]:
max_ = rchild
if max_ != pos: # 如果max_未发生改变,说明不需要调整
lists[max_], lists[pos] = lists[pos], lists[max_]
heap_adjust(lists, max_, length) # 递归调整
def heap_create(lists, length):
for i in range(length // 2)[::-1]:
heap_adjust(lists, i, length)
def heap_sort(lists):
length = len(lists)
heap_create(lists, length)
for i in range(length)[::-1]:
lists[0], lists[i] = lists[i], lists[0] # 首尾元素互换,将最大的元素放在列表末尾
heap_adjust(lists, 0, i) # 从头再调整,列表长度-1(尾元素已经完成排序,所以列表长度-1)
def move(vertex, edge, init_missionary=3, init_cannibal=3):
if vertex[2] == 0:
missionary = vertex[0] + edge[0]
cannibal = vertex[1] + edge[1]
state_of_boat = 1 - vertex[2]
else:
missionary = vertex[0] - edge[0]
cannibal = vertex[1] - edge[1]
state_of_boat = 1 - vertex[2]
if missionary != 0 and missionary < cannibal:
return False
elif (init_missionary - missionary) != 0 and ((init_missionary - missionary) < (init_cannibal - cannibal)):
return False
elif missionary < 0 or cannibal < 0 or (init_missionary - missionary) < 0 or (init_cannibal - cannibal) < 0:
return False
else:
return [missionary, cannibal, state_of_boat]
def whether_expandable(vertex, set_of_operation, pre_vertex): # 判断当前节点是否可扩展
sons = []
for operation in set_of_operation:
m = move(vertex, operation)
if m:
if m != pre_vertex: # 扩展得到的子节点不应该是当前节点的父节点,即应当避免重复
sons.append(m)
if not sons:
return False
else:
return sons
|
85c12851e6c61c42c6d4bec176714475dd4c387c | kazu74/hangman | /hangman.py | 1,361 | 3.8125 | 4 | def hangman(word):
life=10
rletters = list(word)
board = ["_"] * len(word)
#win=False
print("ハングマンへようこそ!")
while life > 0 :
print("\n")
msg = "1文字を予想すべし"
char =input(msg)
if char in rletters:
cind = rletters.index(char)
board[cind] = char
rletters[cind] = "$"
else:
life -= 1
print(",".join(board))
print("\n","LIFE=",life)
if "_" not in board:
print("あなたの勝ち!!")
print(" ".join(board))
break
if life==0:
print("残念!あなたの負け")
import random
wordlist=["hokkaido","aomori","iwate","akita","yamagata","miyagi","fukusima", \
"niigata","ibaraki","chiba","gunma","tochigi","yamanashi","saitama", \
"tokyo","kanagawa","shizuoka","nagano","aichi","gifu","mie","fukui","ishikawa","toyama", \
"shiga","kyoto","nara","wakayama","osaka","hyogo","okayama","hiroshima" ,\
"yamaguchi","shimane","tottori","kagawa","ehime","kochi","tokushima", \
"fukuoka","saga","nagasaki","kumamoto","oita","miyazaki","kagoshima","okinawa"]
num=random.randint(0,len(wordlist))
answer=wordlist[num]
hangman(answer)
|
822d03054dde6bda0adf1057bb6690ec23d90ddf | kdonthi/Leetcode | /LinkedList/remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.py | 640 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode()
dummy.val = head.val
dummy.next = head.next
head.next = dummy
ptr1 = head
ptr2 = head
for i in range(n + 1):
ptr2 = ptr2.next
while (ptr2):
ptr1 = ptr1.next
ptr2 = ptr2.next
temp = ptr1.next.next
ptr1.next.next = None
ptr1.next = temp
return (head.next)
|
84bfbd1b1425382bf1610da2c80c6cc6c3b2a660 | gschen/where2go-python-test | /1906101059王曦/12月/day20191203/15.1.py | 1,026 | 3.59375 | 4 | #找出井字棋的获胜者
class Solution:
def tictactoe(self, moves: list[list[int]]) -> str:
set1 = {0,1,2}
list3 = []
list4 = []
list5 = []
list6 = []
for i in range(0,len(moves),2):
if i<len(moves):
list3.append(moves[i][0])
list4.append(moves[i][1])
for n in range(1, len(moves), 2):
if n<len(moves):
list5.append(moves[n][0])
list6.append(moves[n][1])
if set(list3)==set1 or set(list4) == set1 and set(list5)!=set1 and set(list6)!= set1:
return('A')
if set(list5)==set1 or set(list6)== set1 and set(list3)!=set1 and set(list4) != set1:
return('B')
if len(moves)<9 and set(list3)!=set1 and set(list4) != set1 and set(list5)!=set1 and set(list6)!= set1:
return('Draw')
if len(moves)==9 and set(list3)!=set1 and set(list4) != set1 and set(list5)!=set1 and set(list6)!= set1 :
return('Pending') |
5e31e00bc9a8d9973d76f9ed94fc3750d4f21cd9 | ema-rose/wordnik-repl | /practice/lists_and_dictionaries/ex9-7.py | 212 | 3.5 | 4 | n = [1, 3, 5, 6, 9, 17]
# Remove the first item in the list here
n.remove(1)
# removes the item
print n
n.pop(2)
# removes by place number
print n
del(n[2])
# will act like pop, but won't return answer
print n
|
ba260d894df4e4466f34e82d29b98cf41a32106a | cyg2695249540/WorkWeiXin | /leetcode/demo.py | 399 | 3.8125 | 4 | # !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @FILE : demo.py
# @Author : Pluto.
# @Time : 2020/11/2 19:15
class Test:
listA = ['python', '是', '一', '门', '动', '态', '语', '言', '言', '语']
def test_demo(self):
resultList = []
for i in self.listA:
if i not in resultList:
resultList.append(i)
print(resultList)
|
d0b7736138b7034e0e5a489894d8836e874ed06b | alpablo11/Python---V1 | /27.Geometri Örnek Fonksiyon.py | 1,404 | 3.875 | 4 | # AAI Company - Python
# Fonksiyonlar konumuzu pekiştirmek için örnekle devam edelim;
# Üçgen ve dörtgenleri bulacağımız bir geometri fonksiyonu yazalım:
def geometri(sekil):
if len(sekil)==3:
a=sekil[0]
b=sekil[1]
c=sekil[2]
if(a+b)>c and(a+c)>b and (b+c)>a:
if(a==b)and(a==c)and(b==c):
print("Eşkenar Üçgen")
elif(a==b)and(a==c):
print("İkizkenar Üçgen")
else:
print("Çeşitkenar Üçgen")
else:
print("Üçgen Belirtmiyor")
elif len(sekil)==4:
a=sekil[0]
b=sekil[1]
c=sekil[2]
d=sekil[3]
if(a==b)and(a==c)and(a==d):
print("Kare")
elif(a==c)and(b==d):
print("Dikdörtgen")
else:
print("Normal Dörtgen")
else:
print("Herhangi bir şekil değil")
while (True):
eleman_sayisi=int(input("Eleman Sayısı Girin:"))
if(eleman_sayisi==3):
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
geometri([a,b,c])
elif(eleman_sayisi==4):
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
d=int(input("d:"))
geometri([a, b, c,d])
else:
print("Lütfen Tekrar Giriniz") |
2efb5584d67507e9fabee5be6aac65d6af9cecdb | gauriindalkar/list | /count length mississipi.py | 481 | 3.671875 | 4 | ########count length of word#### how many letters reaming in word
# user="mississipi"
# list1=list(user)
# print(list1)
# i=0
# a=[]
# b=[]
# while i<len(list1):
# count=0
# j=0
# while j<len(list1):
# if list1[i]==list1[j]:
# b.append(list1[j])
# count+=1
# j+=1
# k=0
# while k<1:
# if list1[i] not in a:
# a.append (list1[i])
# print(list1[i],"times",count)
# k+=1
# i+=1
|
52439e7ad404c98c2fb18ae9443845a58393b0b0 | Luna-Moonode/Moonode | /Studio-TaskNo.1/venv/lib/ToolBox/main.py | 1,347 | 3.96875 | 4 | # coding=utf-8
print("Welcome to the earth!\nThere're three functions:")
print("1---Base64")
print("2---Dictionary_Reverse")
print("3---QRcode_Transfer")
while True:
try:
choice=input("Please input the number before a function(q to quit):")
except:
print("Invalid input! Try again!")
else:
if choice=='1':
from Base64.Base64 import*
while True:
try:
cho=eval(input("1.加密\n2.解密\n"))
except:
print("Invalid input! Try again!")
continue
else:
if cho==1:
base64encode()
break
elif cho==2:
base64decode()
break
else:
print("Invalid input! Try again!")
continue
elif choice=='2':
from Dict_Reverse.Dict_Reverse import*
dict_reverse()
continue
elif choice=='3':
from Qrcode.QRcode import*
QRcode()
continue
elif choice=='q':
break
elif choice not in [1,2,3,q]:
print("Invalid input! Try again!")
continue
print ("Program terminated.") |
8d26b1de602f884d23994da76465c2f8734d081a | Aditya-A-Pardeshi/Coding-Hands-On | /4 Python_Programs/3 Problems on range/1_DisplayNumbersInRange/Demo.py | 566 | 4.125 | 4 | '''
Write a program which accept range from user and display all numbers in between
that range.
Input : 23 35
Output : 23 24 25 26 27 28 29 30 31 32 33 34 35
Input : -10 2
Output : -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2
'''
def Display(iStart,iEnd):
if(iStart>iEnd):
print("Invalid range");
return;
for i in range(iStart,iEnd+1):
print("{} ".format(i),end = " ");
def main():
iStart = int(input("Enter start range:"));
iEnd = int(input("Enter end range:"));
Display(iStart,iEnd);
if __name__ == "__main__":
main(); |
7050cbd48ea8f9c8193295b0b7f51c8c3ef82982 | ericsolis8/curso_Python | /calculadora.py | 342 | 3.921875 | 4 | salir=0
resultado=0
while salir==0:
num1=input("Escribe un numero: ")
num2=input("Escribe un segundo numero: ")
calcular=input("Escribe que operacion deseas realizar: ")
if calcular == "suma":
suma = num1 + num2
print (suma)
terminar = input("Salir S/N")
if terminar == "s":
salir=1
else:
salir=0
|
7915c35ec9bf23dd7c5116706f239fe34685cc4a | Yuandjom/Automate-the-Boring-stuff-with-Python | /Chapter 5 Dictionaries/Fantasy Game Inventory.py | 291 | 4 | 4 | Inventory = {'rope':1, 'torch':6,'gold coin': 42,'dagger': 1 , 'arrow':12}
def displayInventory(inventory):
print("Inventory")
total = 0
for k,v in Inventory.items():
print(v, k)
total += v
print("Total number of items:",total)
displayInventory(Inventory)
|
56c4915c267d17d2cad368b1b9b08f6157312aa6 | diogogarbin/curso_python | /funcao.py | 644 | 3.78125 | 4 | #!/usr/bin/python3
def soma(x, y):
return x + y
print(soma('daniel' , 'prata'))
#__________________________________________________________
def boas_vindas(nome):
return 'Seja bem vindo {}'.format(nome.title())
print(boas_vindas('daniel'))
#_________________________________________________________
def ler_arquivo(nome):
with open(nome, 'r') as arquivo:
conteudo = arquivo.read()
return conteudo
print(ler_arquivo('frutas.txt'))
#___________________________________________________
def troca(nome)
nome = nome.replace('a' , '@')
return 'Seja bem vindo {}'.format(nome.title())
print(troca(nomes)) |
9aea97f6fc75434717e92b416e1cf0719b4904ce | ayesh99747/Python-Programming-Udemy-Course-Theory-and-Hands-on | /src/Tutorial1/Q5a.py | 707 | 4.125 | 4 | # Arithmetic Operators
# a) Create, save and run the following program. Check the output is as expected.
# #01-09.py
# print(2 + 4)
# print(2.5 + 4.2)
# print(6 - 4)
# print(6.0 - 4.5)
# print(6 * 3)
# print(6 / 3)
# print(6 % 3)
# print(6 // 3) # floor division: always truncates fractional remainders
# print(-5)
# print(3**2) # three to the power of 2
print(2+4) #6
print(2.5+4.2) #6.7
print(6-4) #2
print(6.0-4.5) #1.5
print(6*3) #18
print(6/3) #2.0
print(8%3) #2
print(8//3) #2
print(-5) #-5
print(3**2) #9 |
6839b16e17a881155b6fcc92f1f0a345bf167d92 | Vokaunt/lesson1 | /answers.py | 207 | 3.796875 | 4 | def get_answers(question):
answers={"hello":"Hey, dude!", "what's up?":"thee best", "bye":"see u"}
return answers[question.lower()]
question=input("Ask yuor question?")
print(get_answers(question))
|
1d92935b0927970611fbeb595acab327fb15de2f | mannerslee/leetcode | /146.py | 1,983 | 3.78125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.lru_dict = {}
self.point_dict = {}
self.q_head = Node(-1)
self.q_tail = self.q_head
self.capacity = capacity
self.size = 0
def get(self, key: int) -> int:
if key in self.lru_dict:
self._move_to_end(key)
return self.lru_dict[key]
else:
return -1
def put(self, key: int, value: int) -> None:
# update
if key in self.lru_dict:
self._move_to_end(key)
# insert
else:
# LRU are not full
if self.capacity > self.size:
self.size = self.size + 1
else:
top_key = self._pop_top()
del self.lru_dict[top_key]
del self.point_dict[top_key]
point = self._insert_at_end(key)
self.point_dict[key] = point
self.lru_dict[key] = value
def _pop_top(self):
top = self.q_head.next
self.q_head.next = top.next
if self.q_head.next is not None:
self.q_head.next.previous = self.q_head
#print('pop: ', top.data)
return top.data
def _insert_at_end(self, key):
node = Node(key)
node.previous = self.q_tail
self.q_tail.next = node
self.q_tail = node
return node
def _move_to_end(self, key):
point = self.point_dict[key]
if point == self.q_tail:
return
point.previous.next = point.next
point.next.previous = point.previous
point.previous = self.q_tail
self.q_tail.next = point
self.q_tail = point
# Your LRUCache object will be instantiated and called as such:
cache = LRUCache(capacity=1)
cache.put(2, 1)
print(cache.get(2))
cache.put(3, 2)
print(cache.get(3))
|
a791f30f26442e3eae66ebdd8fe07a4ffcfd3aaa | wang264/JiuZhangLintcode | /Algorithm/L6/optional/652_factorization.py | 1,898 | 3.75 | 4 | # 652. 因式分解
# 中文English
# 一个非负数可以被视为其因数的乘积。编写一个函数来返回整数 n 的因数所有可能组合。#
# 样例1
# 输入:8
# 输出: [[2,2,2],[2,4]]
# 解释: 8 = 2 x 2 x 2 = 2 x 4
# 样例2
# 输入:1
# 输出: []
# 注意事项
# 组合中的元素(a1,a2,...,ak)必须是非降序。(即,a1≤a2≤...≤ak)。
# 结果集中不能包含重复的组合。
class Solution:
# @param {int} n an integer
# @return {int[][]} a list of combination
def getFactors(self, n):
# write your code here
result = []
self.helper(result, [], n, 2)
return result
# 用 n=8作爲例子。
def helper(self, result, item, n, start):
# if len(item)>1 是爲了不要 【8】
# n=1 代表拆分完畢
if n == 1 and len(item) > 1:
result.append(item[:])
return
import math
for i in range(start, int(math.sqrt(n)) + 1):
if n % i == 0:
item.append(i)
self.helper(result, item, n // i, i)
item.pop()
# 爲了在【2,2,2】的同時拿到【2,4】
if n >= start:
item.append(n)
self.helper(result, item, 1, n)
item.pop()
import math
class Solution2:
"""
@param n: An integer
@return: a list of combination
"""
def getFactors(self, n):
# write your code here
result = []
self.dfs(2, n, [], result)
return result
def dfs(self,start, n, path, result):
if path:
result.append(path + [n])
for i in range(start, int(math.sqrt(n)) + 1):
if n % i == 0:
path.append(i)
self.dfs(i, n // i, path, result)
path.pop()
sol = Solution2()
sol.getFactors(n=8)
sol.getFactors(n=32)
|
1e3b9aad629ce86d7bf3b6cbbad3352c96f11c6e | whenhecry/Rokken | /myFilters.py | 955 | 3.6875 | 4 | # assuming the input is a list of articles sorted by date
# return a list of article list divided by month
# eg. [..., [article1 of 2015/7, article2 of 2015/7, ...], [article1 of 2015/6, ...], ...]
def listOfMonth(articlesList):
myList = []
year = None
month = None
for article in articlesList:
tempYear = article.locale_date.split('/')[0]
tempMonth = article.locale_date.split('/')[1]
if tempYear == year and tempMonth == month:
myList[len(myList) - 1].append(article)
else:
myList.append([article])
year = tempYear
month = tempMonth
return myList
# input is 2-dim list
# return element count before gifen index of dim 1
# eg. [[2,3], [5,4,7], [1], ...] will return 2 when index is 1, or 5 when 2
def sumByIndex(myList, index):
# ignore input control
sum = 0
for subListIndex in range(index):
sum += len(myList[subListIndex])
return sum
|
e1fb7b4c6d10810cdd07167104f6c08b7e064ea7 | Dhanushu99005005/PythonAssignment | /PythonAssignment/Q6_DiffLowest.py | 133 | 3.640625 | 4 | """Find the difference between two lowest numbers in the list"""
list1=sorted(list(map(int,input().split())))
print(list[1]-list[0]) |
7be8552b9c0d3c9ba6797fe90ff7737cf213ffff | chaudhary1337/Flappy-Bird | /Game/Birds.py | 2,177 | 3.890625 | 4 | import pygame
import config as cfg
import time
import random
class Bird():
def __init__(self):
# Design
self.color = cfg.BIRD_COLOR
# PHYSICS
# As given in the config file
## Positions
self.x = cfg.BIRD_X_INIT
self.y = random.randint( \
cfg.BIRD_SIZE + cfg.SKY_HEIGHT + cfg.BIRD_SPACER_INIT, \
cfg.SCREEN_HEIGHT - cfg.GROUND_HEIGHT - cfg.BIRD_SIZE - cfg.BIRD_SPACER_INIT)
## Time
self.t = 0
## Velocities
self.v = cfg.BIRD_INITIAL_VELOCITY
self.tv = cfg.BIRD_TERMINAL_VELOCITY
## Accleration
self.g = cfg.GRAVITY
def jump(self):
"""
Makes the bird Jump
"""
# reset time for falling
self.t = 1
# point velocity vector upwards
self.v = cfg.BIRD_UPWARD_VELOCITY
# move the bird upwards (technically not required.)
self.y += cfg.BIRD_JUMP_HEIGHT
def move(self):
"""
- Makes the bird fall due to the action of gravity.
- Checks whether the bird is too high or too low.
Returns False as in 'don't move the bird (its ded :()'
else True as in 'keep the bird alive'
"""
# time
self.t += 1
# velocity
self.v = self.v + self.g * self.t
if self.v >= self.tv:
self.v = self.tv
# displacement
self.y = self.y + self.v * self.t + 0.5 * self.g * self.t**2
# # Top Stop
# if self.y <= cfg.BIRD_SIZE + cfg.SKY_HEIGHT:
# self.y = cfg.BIRD_SIZE + cfg.SKY_HEIGHT
# Top also death
if self.y <= cfg.BIRD_SIZE + cfg.SKY_HEIGHT:
self.y = cfg.BIRD_SIZE + cfg.SKY_HEIGHT
return False
# Bottom DEATH
if self.y >= (cfg.SCREEN_HEIGHT - cfg.GROUND_HEIGHT - cfg.BIRD_SIZE):
self.y = cfg.SCREEN_HEIGHT - cfg.GROUND_HEIGHT - cfg.BIRD_SIZE
return False
# Birb still alive!
return True
def draw(self):
# self explanatory ;)
pygame.draw.circle(cfg.SCREEN, self.color, (int(self.x), int(self.y)), cfg.BIRD_SIZE) |
10bd21d19b4e2e3681e7ad3a90054a9e9237758f | G-itch/Projetos | /Ignorância Zero/017Exercício1.py | 147 | 4.0625 | 4 | n = int(input("Digite um número que eu direi seu fatorial: "))
m=1
for i in range(1, n+1):
m*=i
print("O fatorial de",n,"é igual a",m)
|
93551a004e6181f28dc95cffe5b3819c3ebd20d3 | sagarambalam/fsdse-python-assignment-59 | /build.py | 156 | 3.515625 | 4 | def solution(num1, num2, end_num):
li= []
for i in range(1,end_num):
if (i%num1)==0 and (i%num2)==0:
li.append(i)
return li
|
aa8718dcd8596f752d857e6819edb4f5372e16f9 | chetandg143/Module | /cccc.py | 586 | 3.984375 | 4 | class Student:
def __init__(self, name, rollno, gender, age):
self.name = name
self.rollno = rollno
self.gender = gender
self.age = age
def display(ob):
dict = {"sname": ob.name, "sno ": ob.rollno, "gender": ob.gender, "sage": ob.age }
for x, y in dict.items():
print(x, " : ", y)
name = str(input("enter name of student :"))
rollno = int(input("enter the roll number :"))
gender = (str(input("enter gender (M\F) :")))
age = (int(input("enter the age :")))
s1 = Student(name, rollno, gender, age)
s1.display()
|
3ebbc93fb965521b2e3bed7d87cdab211da83f08 | elizabethejs/practicasPython | /main.py | 595 | 3.625 | 4 |
import argparse,sys
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--x', type=float, default=1.0, help='Elije el primer numero para copiar')
parser.add_argument('--y', type=float, default=1.0, help='Elije el segundo numero para copiar')
parser.add_argument('--operation', type=str, default='add', help='Elije el primer numero para copiar')
args = parser.parse_args()
sys.stdout.write(str(calcular(args)))
def calcular(args):
if args.operation == 'add':
resultado=args.x + args.y
return resultado
if __name__=='__main__':
main() |
5b9ec9f0462df0454ecc46f2763138b08a2260f5 | Nicko72/Harvard-Course | /Python/Loops.py | 147 | 3.671875 | 4 | # Nick May - Harvard Course - May 2021
for i in [0, 1, 2, 3, 4, 5]:
print(i)
# or do this for the same result
for i in range(6):
print(i) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.