blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
15b9b98d0c615adf0cc131c2156882e39e525f62 | RenegaDe1288/pythonProject | /lesson15/mission08.py | 571 | 3.84375 | 4 | new_list = list(input('Введите строку: '))
position_number = 3
n_list = []
count = 0
print('Символ слева: ', new_list[position_number-2])
print('Символ слева: ', new_list[position_number])
for index in range(position_number-2, position_number+1):
if new_list[index] == new_list[position_number-1]:
count += 1
if count == 1:
print('Таких же символов нет')
elif count == 2:
print('Есть 1 такойже символ ')
elif count == 3:
print('Есть 2 одинаковых соседа')
|
957d878d95ff23ca96e8fded5d1d8f38a0e3ee35 | maiorani/CacoStudies | /AC_05.py | 3,630 | 3.71875 | 4 | from abc import ABC, abstractmethod
class Funcionario (ABC):
def __init__ (self, nome, cpf, data_nasc, salario):
self.__nome = nome
self.__cpf = cpf
self.__data_nasc = data_nasc
self.__salario = salario
def get_nome(self):
return self.__nome
def get_cpf(self):
return self.__cpf
def get_dia_nasc(self):
return self.__data_nasc [0] + self.__data_nasc [1]
def get_mes_nasc(self):
return self.__data_nasc [3] + self.__data_nasc [4]
def get_ano_nasc(self):
return self.__data_nasc [6] + self.__data_nasc [7] + self.__data_nasc [8] + self.__data_nasc [9]
def get_salario(self):
return self.__salario
def set_nome(self, novo_nome):
self.__nome = novo_nome
def set_cpf(self, novo_cpf):
self.__cpf = novo_cpf
def set_data_nasc(self, nova_data_nasc):
self.__data_nasc = nova_data_nasc
def set_salario(self, novo_salario):
self.__salario = novo_salario
@abstractmethod
def calcular_salario_final():
pass
@abstractmethod
def converter_para_string():
pass
class Vendedor (Funcionario):
def __init__ (self, nome, cpf, data_nasc, salario, quantidade_vendas):
super().__init__(nome, cpf, data_nasc, salario)
self.__quantidade_vendas = quantidade_vendas
def get_salario(self):
return self.__salario
def set_salario(self, novo_salario):
self.__salario = novo_salario
def get_quantidade_vendas(self):
return self.__quantidade_vendas
def set_quantidade_vendas(self, nova_quantidade_vendas):
self.__quantidade_vendas = nova_quantidade_vendas
def calcular_salario_final(self):
x = self.get_salario
self.salario = self.get_salario + (x * 0.005) * self.get_quantidade_vendas
return self.salario
def converter_para_string(self):
return self.__nome+";"+self.__cpf+";"+self.__data_nasc [6] + self.__data_nasc [7] + self.__data_nasc [8] + self.__data_nasc [9]+"-"+self.__data_nasc [3] + self.__data_nasc [4]+ "-" +self.__data_nasc [0] + self.__data_nasc [1] + ";" + f'{self.get_salario:.2f}' + ";" + self.__quantidade_vendas
class Gerente (Funcionario):
def __init__ (self, nome, cpf, data_nasc, salario, vendedores):
super().__init__(nome, cpf, data_nasc, salario)
self.__vendedores = vendedores
def get_salario(self):
return self.__salario
def set_salario(self, novo_salario):
self.__salario = novo_salario
def get_cpf(self):
return self.__cpf
def set_cpf(self, novo_cpf):
self.__cpf = novo_cpf
def get_vendedores(self):
return self.__vendedores
def set_vendedores(self, vendedores):
self.__vendedores = vendedores
def adicionar_vendedor(vendedores, novo_vendedor):
vendedores = vendedores + novo_vendedor
def calcular_salario_final(self, salario):
salario = salario + (salario * 0.001) * self.get_quantidade_vendas
return salario
def converter_para_string(self, listacpf):
listacpf = []
listacpf = listacpf + self.get_cpf
return self.__nome+";"+self.__cpf+";"+self.__data_nasc [6] + self.__data_nasc [7] + self.__data_nasc [8] + self.__data_nasc [9]+"-"+self.__data_nasc [3] + self.__data_nasc [4]+ "-" +self.__data_nasc [0] + self.__data_nasc [1] + ";" + f'{self.get_salario:.2f}' + ";" + listacpf
|
1a0084b4dd929f32cfac01a9b0b36cded658feb3 | fegoad/Codewars | /VowelCount.py | 365 | 3.8125 | 4 | def get_count(input_str):
num_vowels = 0
i = 0
vowels = ["a","e","i","o","u"]
len_input_str = len(input_str)
while i < len_input_str:
validation = input_str[i] in vowels
if validation == True:
num_vowels = num_vowels + 1
i = i + 1
else:
i = i + 1
return num_vowels
|
2d4a4cd5b38efc3d991d1748b0b1d5ed147b385a | Environmental-Informatics/building-more-complex-programs-with-python-kquijano | /kquijano_program_7.1.py | 1,388 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Karoll Quijano - kquijano
ABE 651 - Environmental Informatics
Think Python - Chapter 4-7
Exercise 7.1
"""
import math
def mysqrt(a):
''' Compute square roots of 'a' using Newton's method '''
x = 2
a=int(a)
while True:
y = (x+a/x)/2 # Newton's method
if x == y:
break
x=y
return(y)
def test_square_root():
''' Tests Newton's method comparing it with math.sqrt() function.
Printa a table with 'a' from 1- 9 '''
header = ['a', 'mysqrt(a)', 'math.sqtr(a)', 'diff'] # Creates a header
print ('{:<6s}{:<20s}{:<20s}{:<20s}'.format(header[0], header[1], header[2], header[3]))
print ('{:<6s}{:<20s}{:<20s}{:<20s}'.format('-','--------','------------','----'))
for a in range (1,10):
my_sqrt = mysqrt(a) # Newton's method
math_sqrt = math.sqrt(a) # built in function
diff = abs(my_sqrt - math_sqrt) # difference
lst = [a, math_sqrt, math_sqrt, diff] # built a list to print
print ('{:<6.1f}{:<20s}{:<20s}{:<20s}'.format(lst[0], str(lst[1]), str(lst[2]), str(lst[3])))
test_square_root()
|
29ca78e80a0d3a14e5cb5f6d29b784d82caa2a5c | dyrnfmxm/codeit | /0309_random_number.py | 604 | 3.6875 | 4 | import random
random_number = random.randint(1,20)
# 코드를 작성하세요.
count = 1
while count <= 4:
n = int(input(f"기회가 {5-count}번 남았습니다. 1-20 사이의 숫자를 맞혀보세요: "))
if count == 4:
print(f"아쉽습니다. 정답은 {random_number}입니다.")
count += 1
elif n == random_number:
print(f"축하합니다. {count}번만에 숫자를 맞히셨습니다.")
break
elif n < random_number:
print("Up")
count += 1
elif n > random_number:
print("Down")
count += 1
|
ab429f9902fd73063762dd9088674c8057d18794 | SaltyPineapple/blackjack | /Game.py | 4,370 | 3.734375 | 4 | import random
import math
from time import sleep
"""
===========================================
TO DO
1. Print face cards correctly
2. Correct Aces Functionality
===========================================
"""
deck = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K",
"A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K",
"A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K",
"A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
deckActive = []
playerHand = []
dealerHand = []
def resetDeck():
global deckActive
deckActive = deck.copy()
random.shuffle(deckActive)
def dealPrint(string):
for letter in string:
print(letter, end=" ")
sleep(.6)
def Sum(inside):
count = -1
for x in inside:
count += 1
if (x == "J") or (x == "Q") or (x == "K"):
inside[count] = 10
if x == "A":
inside[count] = 1
return sum(inside)
def dealer():
while Sum(dealerHand) < 17:
dealerHand.append(deckActive.pop())
def choice():
choose = input("\nHit? [Y / N]")
if choose == "y":
playerHand.append(deckActive.pop())
print("\nPlayer:", end="")
dealPrint(playerHand)
if Sum(playerHand) < 21:
choice()
else:
if choose == "n":
return "n"
else:
print("This was a yes or no question...")
choice()
def hand():
resetDeck()
playerHand.append(deckActive.pop())
dealerHand.append(deckActive.pop())
playerHand.append(deckActive.pop())
dealerHand.append(deckActive.pop())
print("\nPlayer: ", end="")
dealPrint(playerHand)
print("\nDealer: ", end="")
dealPrint(dealerHand)
if choice() == "n":
return
def game():
print("Hello welcome to blackjack! Starting cash is $20")
cash = 20
play = True
while play:
isvalid = True
while isvalid:
try:
wager = int(input("You have $" + str(cash) + ". How much would you like to wager?"))
if wager > cash:
print("You don't have that much money try again..")
else:
isvalid = False
except:
print("We don't mess around with fake currency...")
hand()
dealer()
print("\nDealer:", end="")
dealPrint(dealerHand)
print("\nPlayer:", end="")
dealPrint(playerHand)
if (Sum(playerHand) == 21) & (Sum(dealerHand) != 21):
print("\nBLACKJACK!")
print("You got $" + str(wager))
cash = wager + cash
elif (Sum(dealerHand) == 21) & (Sum(playerHand) != 21):
print("\nDEALER BLACKJACK!")
print("You lost $" + str(wager))
cash = cash - wager
elif (Sum(playerHand) > 21) & (Sum(dealerHand) > 21):
print("DOUBLE BUST!")
print("You get your wager back")
cash = cash
elif Sum(playerHand) > 21:
print("\nBUST!")
print("You lost $" + str(wager))
cash = cash - wager
elif (Sum(dealerHand) > 21) & (Sum(playerHand) < 21):
print("\nDEALER BUST!")
print("You got $" + str(wager))
cash = cash + wager
elif (Sum(playerHand) > Sum(dealerHand)) & (Sum(playerHand) < 21):
print("\nYOU WON!")
print("You got $" + str(wager))
cash = cash + wager
elif (Sum(playerHand) < Sum(dealerHand)) & (Sum(dealerHand) < 21):
print("\nYOU LOST!")
print("You lost $" + str(wager))
cash = cash - wager
elif Sum(playerHand) == Sum(dealerHand):
print("\nTIE! You get your wager back")
cash = cash
check = True
while check:
again = input("Want to play another hand or run with your money? [y / n]")
if again == "n":
play = False
check = False
else:
if again == "y":
playerHand.clear()
dealerHand.clear()
resetDeck()
check = False
else:
print("Sorry I didn't catch that")
print("Thanks for playing! You left with $" + str(cash))
game()
|
b8346f9e11c073ff5606986672d70da3144ed5cd | ksanter1987/Python-test-repo-phase-1 | /phonebook_func.py | 2,806 | 3.984375 | 4 |
def add_contact(some_dict, some_list):
first_name = input('Print first name: ')
last_name = input('Print last name: ')
full_name = first_name + ' ' + last_name
phone = input('Print phone: ')
city = input('Print city: ')
new_entry = some_dict.copy()
new_entry['first_name'] = first_name
new_entry['last_name'] = last_name
new_entry['full_name'] = full_name
new_entry['phone'] = phone
new_entry['city'] = city
return some_list.append(new_entry)
def first_name_search(some_list):
query = input('First name: ')
for item in some_list:
if item['first_name'] == query:
print('Found person:')
print(item)
action = input("""What to do next:
next - search next record
menu - return to menu
: """).strip().lower()
if action == 'next':
continue
elif action == 'menu':
break
def last_name_search(some_list):
query = input('Last name: ')
for item in some_list:
if item['last_name'] == query:
print('Found person:')
print(item)
action = input("""What to do next:
next - search next record
menu - return to menu
: """).strip().lower()
if action == 'next':
continue
elif action == 'menu':
break
def full_name_search(some_list):
query = input('Full name: ')
for item in some_list:
if item['full_name'] == query:
print('Found person:')
print(item)
action = input("""What to do next:
next - search next record
menu - return to menu
: """).strip().lower()
if action == 'next':
continue
elif action == 'menu':
break
def phone_search(some_dict, some_list):
query = input('Phone number: ')
for item in some_list:
if item['phone'] == query:
print('Found person:')
print(item)
action = input("""What to do next:
next - search next record
update - update a record
delete - delete a record
menu - return to menu
: """).strip().lower()
if action == 'next':
continue
elif action == 'update':
new_first_name = input('Enter new first name: ')
new_last_name = input('Enter new last name: ')
new_full_name = new_first_name + ' ' + new_last_name
new_phone = input('Enter new phone number: ')
new_city = input('Enter new city: ')
item['first_name'] = new_first_name
item['last_name'] = new_last_name
item['full_name'] = new_full_name
item['phone'] = new_phone
item['city'] = new_city
break
elif action == 'delete':
some_list.remove(item)
break
elif action == 'menu':
break
def city_search(some_list):
query = input('City: ')
for item in some_list:
if item['city'] == query:
print('Found person:')
print(item)
action = input("""What to do next:
next - search next record
menu - return to menu
: """).strip().lower()
if action == 'next':
continue
elif action == 'menu':
break
|
0ea13c96841fa081f47f1aa5f08421c0aaa54df9 | z21mwKYq/Learning | /2_5_3.py | 209 | 3.5625 | 4 | ls = [int(i) for i in input().split()]
ls2 = []
# print(ls.count(3))
for i in ls:
if ls.count(i) > 1 and i not in ls2 :
ls2.append(i)
else:
continue
ls2 = sorted(ls2)
print(*ls2)
|
8ebb4986ea77d57a71316d90652cf51d40dd4422 | jungsiwoo0310/python_study | /20210428/turtle02.py | 209 | 3.90625 | 4 | import turtle as t
t.shape('turtle')
n = int(input('숫자를 입력 해주세요.:'))
t.color('#ADF7BE')
t.begin_fill()
for i in range(n) :
t.forward(1)
t.right(360/n)
t.end_fill()
t.mainloop() |
4d0d7a281402e2968b7387a4f9d68913a11a8389 | vk536/MiniProject-Calculator | /Calculator/Calculator.py | 866 | 3.59375 | 4 | from Calculator.Addition import addition
from Calculator.Subtraction import subtract
from Calculator.Multiplication import multipli
from Calculator.Division import division
from Calculator.Square import square
from Calculator.SquareRoot import root
class Calculator:
result = 0
def __init__(self):
pass
def add(self, a, b):
self.result = addition(a, b)
return self.result
def subtract(self, a, b):
self.result = subtract(a, b)
return self.result
def multiply(self, a, b):
self.result = multipli(a, b)
return self.result
def divide(self, a, b):
self.result = division(a, b)
return self.result
def square(self, a):
self.result = square(a)
return self.result
def squareroot(self, a):
self.result = root(a)
return self.result |
40884bc5b3c4c2edc05381d9f661d7c5f29780a0 | cwong2k16/SBML | /hw1/q4.py | 394 | 4.21875 | 4 | import datetime
import calendar
variable = input("Enter a date in the format MM/DD/YYYY: ")
date_arr = variable.split("/")
month = int(date_arr[0])
day = int(date_arr[1])
year = int(date_arr[2])
date = datetime.date(year, month, day)
day_name = calendar.day_name[date.weekday()]
month_name = calendar.month_name[month]
print(day_name + ", " + month_name + " " + str(day) + ", " + str(year)) |
3e2c4ff23856adbb9942b5e86d695c67740601d5 | yashodeepchikte/CP | /5-Recursion/MaxAndMin.py | 632 | 3.828125 | 4 | """
finding maximum value using recursion
"""
def findMax(arr, n):
if n == 1:
return arr[0]
else:
x = findMax(arr, n-1)
if arr[n-1] < x:
return x
else:
return arr[n-1]
arr = [110000,5,2,3,6,7,2,8,10,1,-9, 100]
findMax(arr, len(arr))
def findMin(arr, n=len(arr)):
if n == 1:
return arr[0]
else:
x = findMin(arr, n-1) # this if else block will return the first element
if x < arr[n-1]:
return x
else:
return arr[n-1] # this if else blockk copairs the max element with each element left to right
findMin(arr) |
c0bd40629dcc69fa77a6eebee96970716e05ddf3 | Hydebutterfy/learn-python | /message/Count(Text, Pattern)函数加强.py | 1,260 | 3.9375 | 4 | __author__ = 'chenhaide'
def reverse_string(seq):
return seq[::-1]
def complement(seq):
#return the complementary sequence string.
basecomplement={"A":"T","C":"G","G":"C","T":"A","N":"N"}
letters=list(seq)
letters=[basecomplement[base] for base in letters]
return ''.join(letters)
def reversecomplement(seq):
#return the reverse complement of the dna string.
seq=reverse_string(seq)
seq=complement(seq)
return seq
def PatternCount(Text, Pattern):
try:
print(Text)
print(Pattern)
text_len = len(Text)
pattern_len = len(Pattern)
count = 0
for i in range(text_len - pattern_len + 1):
a = Text[i:pattern_len + i]
if Pattern == a or Pattern == reversecomplement(a):
count = count + 1
return count
except:
print("Something wrong in the input")
filename1 = input("Enter file1 name: ")
filename2 = input("Enter file2 name: ")
fileread1 = open(filename1,"r")
fileread2 = open(filename2,"r")
dna=fileread1.read().upper()
pattern=fileread2.read().upper()
number=PatternCount(dna, pattern)
print(number) #用于计算基因组组中特定片段的数量,统一大小写,反向互补,序列来自文件
|
8756666d312ea1c19c3a4a0a3cafb69f15f12d08 | gnsalok/Python-Basic-to-Advance | /PyConcepts/app.py | 107 | 3.8125 | 4 |
num1=1
num2=2
result = addNumber(1,2)
print(result)
def addNumber(val1, val2):
return val1+val2 |
c0bef6a6cc6a83c61394b4c7a797222e76478b38 | marielitonmb/Curso-Python3 | /Desafios/desafio-09.py | 1,103 | 4.25 | 4 | # Aula 07 - Desafio 09: Tabuada
# Digite um valor e informe a tabuada dele
n = int(input('Digite um numero: '))
print('='*10, 'Tabuada de adiçao de', n, '='*10)
print(f'{n}+1 = {n+1} | {n}+2 = {n+2} | {n}+3 = {n+3} | {n}+4 = {n+4} | {n}+5 = {n+5}')
print(f'{n}+6 = {n+6} | {n}+7 = {n+7} | {n}+8 = {n+8} | {n}+9 = {n+9} | {n}+10 = {n+10}')
print()
print('='*10, 'Tabuada de subtraçao de', n, '='*10)
print(f'{n}-1 = {n-1} | {n}-2 = {n-2} | {n}-3 = {n-3} | {n}-4 = {n-4} | {n}-5 = {n-5}')
print(f'{n}-6 = {n-6} | {n}-7 = {n-7} | {n}-8 = {n-8} | {n}-9 = {n-9} | {n}-10 = {n-10}')
print()
print('='*10, 'Tabuada de multiplicaçao de', n, '='*10)
print(f'{n}*1 = {n*1} | {n}*2 = {n*2} | {n}*3 = {n*3} | {n}*4 = {n*4} | {n}*5 = {n*5}')
print(f'{n}*6 = {n*6} | {n}*7 = {n*7} | {n}*8 = {n*8} | {n}*9 = {n*9} | {n}*10 = {n*10}')
print()
print('='*10, 'Tabuada de divisao de', n, '='*10)
print(f'{n}/1 = {n/1:.2f} | {n}/2 = {n/2:.2f} | {n}/3 = {n/3:.2f} | {n}/4 = {n/4:.2f} | {n}/5 = {n/5:.2f}')
print(f'{n}/6 = {n/6:.2f} | {n}/7 = {n/7:.2f} | {n}/8 = {n/8:.2f} | {n}/9 = {n/9:.2f} | {n}/10 = {n/10:.2f}')
|
26e06f194ada6a9e744359030396f3695578af4e | Tocsmats/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 619 | 3.828125 | 4 | #!/usr/bin/python3
"""
validUTF8
"""
def validUTF8(data):
"""Determines if a given data set represents a valid UTF-8 encoding"""
count = 0
for x in data:
if 191 >= x >= 128:
if not count:
return False
count -= 1
else:
if count:
return False
if x < 128:
continue
elif x < 224:
count = 1
elif x < 240:
count = 2
elif x < 248:
count = 3
else:
return False
return count == 0
|
3af5b6c9b6521101863e2eea31642096a45c45ad | r0bse/python_VL_snippets | /vl2/functions/functions_2.py | 341 | 3.703125 | 4 |
def age_verification(age: int, age_to_be_allowed_to_drink: int) -> bool:
return age >= age_to_be_allowed_to_drink
if __name__ == "__main__":
print("With age 18 and threshold 21: {0}".format(age_verification(18, 21)))
print("With named parameters: {0}".format(age_verification(age_to_be_allowed_to_drink=18, age=21)))
|
a45e2202edc7b2d599e6d296812fe51481ae2748 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/648 Div 2/B.py | 1,629 | 3.828125 | 4 | # def bubbleSort(n, arr, blist):
# tags = list(range(n))
# tagtype = dict()
# for ind, elem in enumerate(tags):
# tagtype[elem] = blist[ind]
# for i in range(n-1):
# for j in range(0, n-i-1):
# if arr[j] > arr[j+1]:
# if tagtype[tags[j]]==tagtype[tags[j+1]]:
# flag = 0
# for k in range(j+2, n-i-1):
# if arr[j] > arr[k] and tagtype[tags[j]]!=tagtype[tags[k]]:
# arr[j], arr[k] = arr[k], arr[j]
# tags[j], tags[k] = tags[k], tags[j]
# flag = 1
# break
# if flag:
# continue
# else:
# return ('No', arr, tags, tagtype)
# else:
# arr[j], arr[j+1] = arr[j+1], arr[j]
# tags[j], tags[j+1] = tags[j+1], tags[j]
# return ('Yes', arr, tags, tagtype)
from sys import stdin, stdout
t = int(input())
for _ in range(t):
n = int(input())
alist = list(map(int, stdin.readline().strip().split()))
blist = list(map(int, stdin.readline().strip().split()))
if alist == sorted(alist):
print('Yes')
else:
if 1 in blist and 0 in blist:
print('Yes')
else:
print('No')
# ans = bubbleSort(n, alist, blist)
# if ans[0] == 'Yes':
# print(ans[0])
# else:
# print(ans[0])
# # _, arr, tags, tagype = ans
|
aa4630021147f5bd5efa6c0f7fefed8ca941a9ba | Shnobs/PythonOzonNS | /les_1_task_2.py | 648 | 4.21875 | 4 | # Сбор пользовательских зарплат
salary_1 = float(input('Введите зарплату первого члена семьи: '))
salary_2 = float(input('Введите зарплату второго члена семьи: '))
salary_3 = float(input('Введите зарплату третьего члена семьи: '))
# Расчет средней зарплат
average_salary = (salary_1 + salary_2 + salary_3)/3
# Использование f-строки для вывода результата
print(f'Средняя зрплата в семье составляет {average_salary} рублей') |
364dd41443b067eaccefaefd7de4731b68fb74cd | skshamagarwal/EmailBot | /EmailBot.py | 5,529 | 3.59375 | 4 | import smtplib # Simple Mail Transfer Protocol
import speech_recognition as sr
from email.message import EmailMessage
import pyttsx3 # Python Text to Speech version 3
import getpass # Take Hidden Password Input
import pyperclip # Copy text to clipboard
# Talk function which uses pyttsx3
def talk(text):
engine.say(text)
engine.runAndWait()
# Speech to text which uses Speech Recognition with google api
def getSpeech():
with sr.Microphone() as source:
print("listening...")
voice = listener.listen(source, phrase_time_limit=3)
try:
info = listener.recognize_google(voice)
return info
except:
return None
# Get email subject info
def subject():
talk("What is Subject of your Email?")
em_subject = getSpeech()
while em_subject == None:
talk("Can't understand, Speak Again!")
em_subject = getSpeech()
return em_subject
# Get email body info
def body():
talk("What is body of your Email?")
em_body = getSpeech()
while em_body == None:
talk("Can't understand, Speak Again!")
em_body = getSpeech()
return em_body
# Get sender's info
def sender():
talk("What is the name of sender?")
em_sender = getSpeech()
while em_sender == None:
talk("Can't understand, Speak Again!")
em_sender = getSpeech()
if em_sender.lower() in email_dict:
emailid = email_dict[em_sender.lower()]
else:
emailid = "Email ID Not Available"
return em_sender.title(), emailid
# Get receiver's info
def reciever():
talk("What is the name of reciever?")
em_reciever = getSpeech()
while em_reciever == None:
talk("Can't understand, Speak Again")
em_reciever = getSpeech()
if em_reciever.lower() in email_dict:
emailid = email_dict[em_reciever.lower()]
else:
emailid = "Email ID Not Available"
return em_reciever.title(), emailid
# Send Email using smtplib
def sendEmail(reciever, sender, subject, password, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, password)
email = EmailMessage()
email['From'] = sender
email['To'] = reciever
email['Subject'] = subject
email.set_content(message)
server.send_message(email)
# Reading usernames and emails from text file
def readFile():
f = open("userEmails.txt", "r")
data = (f.read())
ls = []
x = ''
for i in data:
if i == '\n':
ls.append(x)
x = ''
else:
x = x+i
ls.append(x)
for i in ls:
name, email = i.split()
email_dict[name] = email
# Adding more usernames and emails to text file
def writeFile(name, email):
f = open("userEmails.txt", "a")
f.write(f"\n{name.lower()} {email.lower()}")
if __name__ == '__main__':
print("Email Sender launched\n")
email_dict = {}
readFile()
engine = pyttsx3.init()
listener = sr.Recognizer()
ans = 'yes'
while 'yes' in ans:
subject = subject()
body = body()
sender, s_email = sender()
reciever, r_email = reciever()
if s_email == "Email ID Not Available":
talk("Unable to fetch Email I D for the given sender, please type down sender's email")
s_email = input('>>')
writeFile(sender, s_email)
if r_email == "Email ID Not Available":
talk("Unable to fetch Email I D for the given reciever, please type down reciever's email")
r_email = input('>>')
writeFile(reciever, r_email)
print(f"\nTo: {reciever}({r_email})")
print("\nSubject:", subject)
print("\nBody:", body)
print("\nBest Regards,")
print(sender, "\n")
talk("Preview your Email, Do you want to send it?")
send = getSpeech()
while send == None:
talk("Can't understand, Speak Again")
send = getSpeech()
if 'yes' in send:
talk("Type down sender's password to send email.")
# password = getpass.getpass(prompt="Password: ")
password = input(">>")
try:
sendEmail(r_email, s_email, subject, password, body)
except:
talk("Invalid Credentials, your email have been copied to clipboard.")
pyperclip.copy(f"To: {reciever}({r_email})\nSubject: {subject}\nBody: {body}\n\nBest Regards,\n{sender}")
else:
talk("Do you want to copy this email to clipboard?")
copy = getSpeech()
while copy == None:
talk("Can't understand, Speak Again")
copy = getSpeech()
if 'yes' in copy:
pyperclip.copy(f"To: {reciever}({r_email})\nSubject: {subject}\nBody: {body}\n\nBest Regards,\n{sender}")
talk("Your Email have been successfully copied to clipboard")
talk("Do you want to send another Email?")
ans = getSpeech()
while ans == None:
talk("Can't understand, Speak Again")
ans = getSpeech()
ans = ans.lower()
|
31e7d9189c461263bc0e719eef16e6798755603e | vrlls/Traspuesta-de-una-matriz | /main.py | 328 | 3.703125 | 4 | def traspuesta(M,n):
B = []
for i in range(n):
B.append([])
for j in range(n):
B[i].append(0)
for i in range(n):
for j in range(n):
B[j][i]=M[i][j]
return B
n=int(input())
M=[]
for i in range(n):
M.append([])
for j in range(n):
M[i].append(int(input()))
print(traspuesta(M,n))
|
f6c90c0df7816a210125fb8c46243671306ce39b | BenC0/python_training--ddl | /Code/7. Conditions/example.py | 2,459 | 4.625 | 5 | # ------------------------------------------------------------------------------
# Explanation
# Conditions
# Python uses boolean variables to evaluate conditions. The boolean values True
# and False are returned when an expression is compared or evaluated
# ------------------------------------------------------------------------------
# When comparing values we use either the double equals operator, "==", or the
# "not equals" operator, "!=". We are also able to make use of the other
# comparison operators. These are:
# "==" - Equals
# "!=" - Not Equals
# "<>" - Not Equals
# ">" - Greater Than
# "<" - Less Than
# ">=" - Greater Than or Equal to
# "<=" - Less Than or Equal to
# Note: Unlike JavaScript, there is no triple equals operator "==="
x = 2
# prints out True
print(x == 2)
# prints out False
print(x == 3)
# prints out True
print(x < 3)
# prints out False
print(x > 3)
# If Statements
# If statements in python generally follow the same syntax as other languages
# with some minor differences. Please see the example below.
if 1 == 2:
print("1 is equal to 2?")
elif 1 != 2:
print("1 is not equal to 2!")
else:
print("I have no idea how numbers work :'(")
# You'll notice in the above example that we don't use any brackets in our IF
# statement. This is because Python relies on indentation to separate blocks
# of code.
# Boolean operators
# In Python, you can use the "and" and "or" boolean operators to build complex
# expressions. See the IF statement example below.
name = "John"
age = 23
if name == "John" and age == 23:
print("You're name is John and you're 23 years old")
if age == 23 or age == 24:
print("You're 23 or 24 years old")
# The "in" operator
# You can also use the "in" operator to check if a value is in a list
name = "John"
if name in ["John", "Bob"]:
print("You're name is either John or Bob")
# You can also do this with strings.
name = "John"
if "J" in name:
print("J is in %s!" % name)
# The "is" operator
# Unlike the double equals operator "==", the "is" operator does not match
# the values of the variables, but the instances themselves.
x = [1,2,3]
y = [1,2,3]
z = x
# Prints out True
print(x == y)
# Prints out False
print(x is y)
# Prints out True
print(z is x)
# The "not" operator
# You can use the "not" operator before a boolean expression to invert it
# prints (True)
print(not False)
myList = [1,2,3]
# prints ("4 is not in myList")
if 4 not in myList:
print("4 is not in myList") |
072baa354b8bcfd844d7f0cac6dc5fcadf327d8f | techdragon/historia | /historia/culture/culture.py | 1,681 | 3.84375 | 4 | from uuid import uuid4
class Culture(object):
"""
Culture.
Considerations that go into making up a Culture:
- language
- history
- food
- shelter
- education
- security
- relationships
- political and social organizations
- religions
- art
e.g. Chinese
"""
def __init__(self, manager, name, parent=None):
self.manager = manager
self.id = uuid4().hex
self.name = name
# regional variations of this culture
self.variants = []
# descendant cultures
self.children = []
# which culture this culture branched off of
# if None, this culture existed at simulation start
self.parent = parent
# a measure of how successful this culture is
# a higher prestige means Pops are more likely to assimilate to this culture
self.prestige = 0
def recalculate_prestige(self):
"""
Calculate the prestige of this culture
1 for each pop of this culture
100 for each country where this culture is dominant
1/10th of each country's score where this culture is dominant
"""
self.prestige = 0
def split(self):
"""
Create a new culture descended from this one
"""
new_culture = Culture(self.manager, )
self.children.append(new_culture)
return new_culture
def __repr__(self):
raise "<Culture id={}>".format(self.system_name, self.id)
def __eq__(self, other):
return self.id == other.id
def __key__(self):
return self.id
def __hash__(self):
return hash(self.__key__())
|
bc22fab0576294338a9a54f160086d92b67270c9 | MNandaNH/MNandaNH | /For_s/arguments.py | 229 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 09:26:51 2021
@author: franc
"""
def suma(*args):
print("", type(args))
sum=0
for n in args:
sum +=n
print("Suma:", sum)
suma(3) |
5660f3b21c62c0a19e10ee21769c2c30aa43dce0 | hurricaney/PythonStart | /PythonApplication1/Data/wordcount.py | 338 | 3.84375 | 4 | def wordcount(readtxt):
dict={}
readlist=readtxt.split()
for every_word in readlist:
if every_word in dict:
dict[every_word]+=1
else:
dict[every_word]=1
return dict
readtext="""
this is a test txt!
can you see this ?
"""
dict1={}
dict1=wordcount(readtext)
print(dict1) |
44468eba064ad8820541903d346cde7840f7d19a | vanch1n1/SoftUni-programming-projects-and-exercises | /Python-programming-fundamentals/data_types_and_variables_lecture/centuries_to_minutes.py | 213 | 3.75 | 4 | century = int(input())
years = 100 * century
days = int(365.2422 * years)
hours = days * 24
minutes = hours * 60
print(f'{century} centuries = {years} years = {days} days = {hours} hours = {minutes} minutes') |
9bfdeb4b762a418dabd0ea6b38f47e9baae29352 | ClodaghMurphy/dataRepresentation | /Week6/jsonPackage0.py | 374 | 3.5 | 4 | #run this script to WRITE a new file containing your data{} in a json stylee called simple.json
import json
data = {
'name':'joe',
'age':21,
"student": True#different types of quotes, python doesn't mind.
}
#print(data)
file = open("simple.json",'w')
json.dump(data,file, indent=4)#indent makes it look nicer (new lines) handy when using large quantities
|
59ae4311539d27c33b9f988bd58572045ee74de2 | Davidxswang/leetcode | /medium/324-Wiggle Sort II.py | 3,938 | 3.890625 | 4 | """
https://leetcode.com/problems/wiggle-sort-ii/
Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....
Example 1:
Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].
Example 2:
Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?
"""
# time complexity: O(nlogn), space complexity: O(1)
# the solution is inspired by @StefanPochmann and @huoshankou in the discussion area.
# the key here is actually the process of rewiring the index.
# by (2*i+1) % (n | 1), we can rewire the index from 0,1,2,3,4,5 to 1,3,5,0,2,4 and from 0,1,2,3,4 to 1,3,0,2,4
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) <= 1:
return
def newIndex(i):
# if len(nums) is odd, then 2i+1 % n, e.g. n=5, 0,1,2,3,4 ==2i+1==> 1,3,5,7,9 ==%n==> 1,3,0,2,4 ==> so the first two will be mapped to the even positions where large(>median) numbers are
# if len(nums) is even, then 2i+1 % (n+1), e.g. n=6, 0,1,2,3,4,5 ==2i+1==> 1,3,5,7,9,11 ==%(n+1)==> 1,3,5,0,2,4 ==> so the first three will be mapped to the even positions where large(>median) numbers are
return (2*i+1) % (len(nums) | 1)
# cannot use this method, because in theory, the time complexity of finding the k-th largest element in an array using quick sort is O(n) on average, but the last test case, it's an extreme case where using quick sort will not shrink the search range into half. Instead, it will shrink only 1 or 2 or 10 every time, which is very small compared with the size of the input, which is around 60000.
# using quick sort in this case will approach n^2, while sorting it completely only takes O(nlogn) time complexity using built-in sort method.
# median = self.findKthLargest(nums, (len(nums)+1)//2)
# print(nums, median, nums[(len(nums)+1)//2-1])
nums.sort(reverse=True)
median = nums[len(nums) // 2]
left, i, right = 0, 0, len(nums)-1
while i <= right:
left_index = newIndex(left)
i_index = newIndex(i)
right_index = newIndex(right)
if nums[i_index] < median:
nums[i_index], nums[right_index] = nums[right_index], nums[i_index]
right -= 1
elif nums[i_index] > median:
nums[i_index], nums[left_index] = nums[left_index], nums[i_index]
i += 1
left += 1
else:
i += 1
def findKthLargest(self, nums: List[int], k: int) -> int:
# I have changed the code here, it's not quick sort but still it cannot deal with the last test case
def helper(arr, startIdx, endIdx, n):
while True:
#print(startIdx, endIdx)
pivot = startIdx
leftIdx = startIdx + 1
rightIdx = endIdx
while leftIdx <= rightIdx:
if arr[pivot] < arr[leftIdx] and arr[pivot] > arr[rightIdx]:
arr[leftIdx], arr[rightIdx] = arr[rightIdx], arr[leftIdx]
if arr[pivot] >= arr[leftIdx]:
leftIdx += 1
if arr[pivot] <= arr[rightIdx]:
rightIdx -= 1
arr[pivot], arr[rightIdx] = arr[rightIdx], arr[pivot]
if rightIdx == n:
return arr[rightIdx]
elif n > rightIdx:
startIdx = rightIdx + 1
else:
endIdx = rightIdx - 1
n = len(nums) - k
return helper(nums, 0, len(nums)-1, n)
|
b6253b426a5b2d4087edb7c89cf93c9423569852 | halfrice/pht | /app/c2/2.3.py | 1,761 | 4.15625 | 4 | # Delete Middle Node
# Implement an algorithm to delete a node in the middle (i.e., any node but
# the first and last node, not necessarily the exact middle) of a singly
# linked list, give only access to that node.
# EXAMPLE
# Input: the node c from the linked list a -> b -> c -> d -> e -> f
# Result: nothing is returned, but the new linked list looks like a -> b -> d -> e -> f
class Node:
def __init__(self,data=None,next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self,head=None):
self.head = head
def add(self,data):
node = Node(data)
node.next = self.head
self.head = node
def remove(self,data):
node = self.head
prev = None
while node:
if node.data == data and prev:
prev.next = node.next
elif node.data == data and not prev:
self.head = node.next
prev = node
node = node.next
def print(self):
node = self.head
while node:
print(node.data,end=' ')
node = node.next
print(' ')
def print_backwards(self):
stack = ''
node = self.head
while node:
stack = node.data+' '+stack
node = node.next
print(stack)
def merge(self,l2):
node = self.head
node2 = l2.head
while node:
print(node,node2)
target = node.next
target2 = node2.next
node2.next = node.next
node.next = node2
node = target
node2 = target2
l1 = LinkedList()
l1.add('w')
l1.add('t')
l1.add('f')
l1.add('x')
# l2 = LinkedList()
# l2.add('l')
# l2.add('m')
# l2.add('a')
# l2.add('o')
l1.print()
l1.remove('w')
l1.print()
l1.remove('x')
l1.print()
# l2.print()
# l1.merge(l2)
# l1.print()
# l1.print_backwards()
|
7335c04020638bab89e7394d7f6cb6aa6758541f | mqcah/python_lesson | /AI_academy/class.py | 216 | 3.65625 | 4 | class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def output(self):
print('Point(%d, %d)' % (self._x, self._y))
p1 = Point(1, 2)
p2 = Point(3, 4)
p1.output()
p2.output() |
7859b8575c6892a8001f185837c121cde9a872dd | Kunalpod/codewars | /triple_trouble.py | 232 | 3.65625 | 4 | #Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Triple trouble
#Problem level: 6 kyu
def triple_double(num1, num2):
for i in range(10):
if str(i)*3 in str(num1) and str(i)*2 in str(num2):
return 1
return 0
|
f6feb37046c6b81c92e41c0d361f188fa79dd8a9 | Kopkins/refactored-telegram | /Datetime.py | 1,464 | 3.59375 | 4 |
import re
class Datetime():
def __init__(self, mon, day, year, hour, minute):
self.month = mon
self.day = day
self.year = year
self.hour = hour
self.minute = minute
def __str__(self):
time_of_day = 'PM' if self.hour > 12 else 'AM'
hour = self.hour if time_of_day == 'AM' else self.hour - 12
minute = self.minute if self.minute >= 10 else "0{}".format(self.minute)
return '{}:{} {}'.format(hour, minute, time_of_day)
def from_api_string(string):
pattern = re.compile("([A-Za-z]{3,}) (\d{,2}) (\d{,4}) (\d{,2}):(\d{,2}):.*([AP]M)\Z")
match = pattern.match(string)
if not match:
return Datetime.new_match(string)
else:
return Datetime.old_match(match)
def old_match(match):
mon, day, year, hour, minute, time_of_day = match.group(1, 2, 3, 4, 5, 6)
day, year, hour, minute = map(int, [day, year, hour, minute])
if time_of_day == 'PM':
hour += 12
return Datetime(mon, day, year, hour, minute)
def new_match(string):
pattern = re.compile("(\d{,4})-(\d{,2})-(\d{,2}) (\d{,2}):(\d{,2}).*")
match = pattern.match(string)
year, month, day, hour, minute = match.group(1, 2, 3, 4, 5)
month, day, year, hour, minute = map(int, [month, day, year, hour, minute])
return Datetime(month, day, year, hour, minute)
|
45cab84fd18372bc0f7176644bf3b97cb8ce68b4 | qznc/dot | /bin/git-randomline | 1,488 | 3.75 | 4 | #!/usr/bin/env python3
"""
Randomly choose a file and a line in it from the repo files.
Inspired by http://www.templeos.org/Wb/Accts/TS/Wb2/WalkThru.html
Basic idea:
1. Let this script give you some point in the repo.
2. Explain the line in 5 minutes
Could be great for impromptu presentations to
* get team members familiar with project code
* lightning talks in a conference
* test knowledge breadth of a programmer
Possible use:
$ vi $(git randomline)
"""
from subprocess import check_output
from random import choice, randint
import linecache
def get_file():
"""Return a random file path tracked in git repo"""
_CMD_FILELIST='git ls-files'
raw = check_output(_CMD_FILELIST, shell=True, universal_newlines=True)
return choice(raw.split("\n"))
def get_linenum(path):
"""Return a random existing line number"""
num_lines = sum(1 for line in open(path))
return randint(0, num_lines)
def interesting_line(line):
"""Determine if the line is interesting.
Empty lines or stuff like '}' is not interesting."""
count = 0
for c in line:
if 'a' <= c <= 'z':
count += 1
elif 'A' <= c <= 'Z':
count += 1
if count > 10:
return True
return False
while True:
try:
path = get_file()
linenum = get_linenum(path)
line = linecache.getline(path, linenum)
except UnicodeDecodeError:
continue
if interesting_line(line):
break
print("%s +%d" % (path,linenum))
|
5f8e762877c02c03e242f34f460289c563211929 | Gaurav-Pande/DataStructures | /leetcode/binary-tree/max_average_subtree.py | 957 | 3.75 | 4 | #link: https://leetcode.com/problems/maximum-average-subtree/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maximumAverageSubtree(self, root):
"""
:type root: TreeNode
:rtype: float
"""
def dfs(root, sum, num):
if not root:
return [0,0]
sum = root.val
num = 1
ls, ln = dfs(root.left, sum, num)
rs, rn = dfs(root.right, sum, num)
sum += ls+rs
num += ln+rn
# print(sum,num)
self.res = max(self.res, float(sum)/float(num))
# print(self.res)
return [sum, num]
self.res = 0
sum = 0
num = 0
dfs(root, sum, num)
return self.res
|
d8ebd4153558082b92f90da4c0d02d85605980f5 | heyutao117/pythonPractice | /Python/6.python平方根.py | 317 | 3.875 | 4 | # -*- coding: UTF-8 -*-
import cmath
num = float(input("请输入一个数字"))
num_sqrt = num ** 0.5
print ('%0.3f的平方根为%0.3f'%(num,num_sqrt))
num1 = int(input('请输入一个数字:'))
num_sqrt1 = cmath.sqrt(num)
print('{0} 的平方根为 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
|
eec5493c9d5cce6d8c5b77436517ade17d128984 | DivyaMaddipudi/Infosyscc | /week3/1.py | 849 | 3.796875 | 4 | '''#2
dic = { "name" : "Divya",
"Dept" : "CSE",
"Year" : 3
}
print(dic)
dic.pop("Year")
print("Dictionary values after removing is", dic)
#3
count = 0
str = input("enter string:")
v = set("aeiouAEIOU")
for i in str:
if i in v :
count = count + 1
print(count)
#5
import re
str = "abbbabcbabbb"
val = re.match("abbb",str,re.I)
print(val.group())
#1
def cs(a,b):
c = 0
for i in range(a,b+1):
j =1
while j*j<=i:
if j*j == i:
c = c + 1
j = j+1
i = i+1
return c
print(cs(9,25))'''
#4
try:
n = 10
a = []
while n>0:
dig = n%2
a.append(dig)
n= n//2
a.reverse()
print("binary equivalent")
for i in a:
print(i,end = "")
except IOError:
print("error")
else:
print("\nsuccessfull")
|
e6a852a3d8e4e604f3431ed871a5cf52dbb2b3c4 | AdamShechter9/project_euler_solutions | /32.py | 1,992 | 3.703125 | 4 | """
Project Euler
Problem 32
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254,
containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity
can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
Solution
--------
One way would be to multiply x * xxx = xxxxx from 1 * 234 = 56789 to 9 * 876 = 54321
and increase digits to 12 * 345 = 6789 and 98 * 765 = 4321
By generating permutations of string '123456789' we can minimize operations to smallest number.
author: Adam Shechter
"""
from itertools import permutations
def main():
pandigital_products1 = pandigital_products('123456789')
print(sum(pandigital_products1))
def pandigital_products(sequence):
seq_perms = permutations(sequence)
win_seqs = []
while 1:
try:
test_perm = next(seq_perms)
# print(test_perm)
# 1 digit * 4 digit = 4 digit
# 2 digit * 3 digit = 4 digit
# 3 digit * 2 digit = 4 digit
# 4 digit * 1 digit = 4 digit
product3 = int("".join(test_perm[-4:]))
mults = test_perm[:-4]
for i in range(1, 5):
mult1 = int("".join(mults[:i]))
mult2 = int("".join(mults[i:]))
# print("testing: {} * {} = {}".format(mult1, mult2, product3))
if mult1 * mult2 == product3:
print("*********************** FOUND **************", product3)
if product3 not in win_seqs:
win_seqs.append(product3)
except StopIteration:
break
return win_seqs
if __name__ == '__main__':
main() |
a3b922224b5269a9b8ff4424500b68376b288b01 | xhwupup/xhw_project | /105_Construct Binary Tree from Preorder and Inorder Traversal.py | 2,366 | 4.09375 | 4 | # 时间:20190520
# Example1:
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
#
# Return the following binary tree:
#
# 3
# / \
# 9 20
# / \
# 15 7
# 难度:Medium(0.5)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
#先序遍历的列表为[根,左,右],中序遍历的列表为[左,根,右],则中序遍历中根的下标为先序遍历中左的边界
if not preorder:
return None
root = TreeNode(preorder[0])
#找到根节点在中序遍历中的下标
n = inorder.index(root.val)
root.left = self.buildTree(preorder[1:n+1],inorder[:n])
root.right = self.buildTree(preorder[n+1:],inorder[n+1:])
return root
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def dfs(self, l1, r1, l2, r2, preorder, inorder, dict):
"""
"""
if r1 >= l1 and r2 >= l2: # 递归的边界
root = TreeNode(preorder[l1])
mid = dict[root.val] # 找到根节点在中序里的位置
# print(mid)
lsize = mid - l2
rsize = r2 - mid # 找到两个子树的范围
root.left = self.dfs(l1 + 1, l1 + lsize, l2, l2 + lsize - 1, preorder, inorder, dict)
root.right = self.dfs(l1 + lsize + 1, l1 + lsize + rsize, mid + 1, mid + rsize, preorder, inorder,
dict) # 对左右子树做同样的操作
return root
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
dict = {} # 定义一个字典
n = len(preorder)
if n == 0:
return None
for i in range(n):
dict[inorder[i]] = i # Inorder里的值和索引互换
root = self.dfs(0, n - 1, 0, n - 1, preorder, inorder, dict)
return root |
ebf181ffb7a6cbc18b941eb466fba4b704a80cde | carlesm/SITWLabs | /BasicWeb/getweather.py | 3,023 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf8 :
'''
Get weather from weather underground
Created on 11/22/2014
@author: carlesm
'''
import sys
import urllib2
import bs4
api_key = None # If assigned won't read argv[1]
location = 'Lleida'
response_format = 'xml'
class WeatherClient(object):
"""Will access wunderground to gather weather information
Provides access to wunderground API
(http://www.wunderground.com/weather/api)
Provides methods:
almanac
"""
url_base = 'http://api.wunderground.com/api/'
url_services = {
"almanac": "/almanac/q/CA/"
}
def __init__(self, apikey):
super(WeatherClient, self).__init__()
self.api_key = api_key
def almanac(self, location):
"""
Accesses wunderground almanac information for the given location
"""
resp_format = "xml"
url = WeatherClient.url_base + api_key + \
WeatherClient.url_services[
"almanac"] + location + "." + resp_format
f = urllib2.urlopen(url)
response = f.read()
f.close()
return_response = {}
soup = bs4.BeautifulSoup(response)
# We use find (not find_all) as there is only one, if
# we used find_all the response would be iterable
temp_high = soup.find("temp_high")
th_normal = temp_high.find("normal")
thnc = th_normal.find("c").text
th_record = temp_high.find("record")
thrc = th_record.find("c").text
thry = temp_high.find("recordyear").text
return_response["high"] = {}
return_response["high"]["normal"] = thnc
return_response["high"]["record"] = thrc
return_response["high"]["year"] = thry
temp_low = soup.find("temp_low")
tl_normal = temp_low.find("normal")
tlnc = tl_normal.find("c").text
tl_record = temp_low.find("record")
tlrc = tl_record.find("c").text
tlry = temp_low.find("recordyear").text
return_response["low"] = {}
return_response["low"]["normal"] = tlnc
return_response["low"]["record"] = tlrc
return_response["low"]["year"] = tlry
return return_response
def print_almanac(almanac):
"""
Prints an almanac received as a dict
"""
print "High Temperatures:"
print "Average on this date", almanac["high"]["normal"]
print "Record on this date %s (%s) " % \
(almanac["high"]["record"],
almanac["high"]["year"])
print "Low Temperatures:"
print "Average on this date", almanac["low"]["normal"]
print "Record on this date %s (%s) " % \
(almanac["low"]["record"],
almanac["low"]["year"])
if __name__ == "__main__":
if not api_key:
try:
api_key = sys.argv[1]
except IndexError:
print "Must provide api key in code or cmdline arg"
weatherclient = WeatherClient(api_key)
print_almanac(weatherclient.almanac("Lleida"))
|
0882bdf7a4f6701d91a10716727b199e8a59b58f | DMeyer/AdventOfCode | /2020/day5/day5.py | 1,165 | 3.6875 | 4 |
def row(boarding_pass):
lower = 0
upper = 127
for c in boarding_pass[:-3]:
if c == 'F':
upper = int((lower + upper) / 2)
else:
lower = int((lower + upper + 1) / 2)
return lower
def col(boarding_pass):
lower = 0
upper = 7
for c in boarding_pass[-3:]:
if c == 'L':
upper = int((lower + upper) / 2)
else:
lower = int((lower + upper + 1) / 2)
return lower
def seatId(boarding_pass):
return (row(boarding_pass) * 8) + col(boarding_pass)
def buildOccupiedSeats():
occupied_seats = set()
for line in open("input"):
boarding_pass = line.strip()
occupied_seats.add(seatId(boarding_pass))
return occupied_seats
def part1(occupied_seats):
return max(occupied_seats)
def part2(occupied_seats):
minimum = min(occupied_seats)
maximum = max(occupied_seats)
for i in range(minimum, maximum):
if i not in occupied_seats:
return i
return -1
occupied_seats = buildOccupiedSeats()
print(f'Day 5 Part 1 Answer: {part1(occupied_seats)}')
print(f'Day 5 Part 2 Answer: {part2(occupied_seats)}')
|
f487750a2916acbc761c7dacd6a735d56f97118f | gao51/TPython | /learn/ler1.py | 475 | 3.5 | 4 | import urllib.request as urllib
from urllib import request
import requests as requests
import time
import urllib3
def linkbaidu():
url = 'http://www.baidu.com'
try:
response = urllib.urlopen(url,timeout=3)
print(response.info())
except urllib.URLError:
print("地址错误")
exit()
with open('./baidu.txt','w') as fp:
fp.write(str(response.read()))
if __name__ == '__main__':
for i in range(3):
print(i) |
925d0114d006b1401a63fd1a4fbe03dab5a2fce7 | mridulrb/Basic-Python-Examples-for-Beginners | /Programs/attachments/natnos.py | 84 | 3.84375 | 4 | n=input("enter range")
x=1
while(x<=n):
print "The number is", x
x=x+1
|
2fd18672f2fa90cdea860012debbef620a06739d | mericar/pyPlay | /pyex/forks_and_threads/forkintro.py | 1,395 | 4.09375 | 4 | """
#Process introduction, forks processes and exits children processes
import os
def child_process():
print('this is the child : ', os.getpid())
os._exit(0)
def parent_process():
while True:
newprocessid = os.fork()
if newprocessid == 0:
child_process()
else:
print('This is the parent process, ', os.getpid(), ' of ', newprocessid)
if input() == 'T': break
parent_process()
"""
#Maintains a specified number of processes for a given time period
import os, time
N = 1000000
NUM = 1000000
# defines a function that produces the square of the input
def squarer(i):
return i*i
# defines a counter function
def count_keeper(count):
for i in range(count):
time.sleep(1)
print('[%s] is on iteration %s of %s ...' % (os.getpid(), i, count))
# defines a function which takes a function and executes the function n times.
def do_n_times(func, n, *args):
for i in range(n):
func(*args)
# defines a process generator and executes a computation inside func
def process_generator(times):
for i in range(times):
pid = os.fork()
if pid == 0:
print('The process %d has been generated. ' % pid)
else:
count_keeper(5)
do_n_times(squarer, NUM, N)
os._exit(0)
# defines a localized running context for process generation
def forker(pcount):
process_generator(pcount)
print('The primary process has completed.')
forker(100)
|
08e634a8ec9fc870ab80332884e110a7135cc20e | larhrib-Dev/eulerProject | /problem1.py | 539 | 4.21875 | 4 | # mathematical problem
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
number_limit = int(input('enter the limit:'))
multiple_three = int(input('enter the first multiple:'))
multiple_five = int(input('enter second multiple :'))
sum =0
cpt =1
while cpt < number_limit:
if cpt%multiple_three == 0 or cpt%multiple_five == 0:
sum += cpt
cpt += 1
print(sum)
|
7c8eb2bbef1d1533396e68f612842527a8817848 | nanmanat/GPA_estimator | /GPA.py | 643 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
#import your file
df = pd.read_csv('/GPA.csv')
train , test = train_test_split(df,test_size=0.2,random_state=0)
x = train['SAT'].to_frame()
y = train['GPA'].to_frame()
x_test = test['SAT'].to_frame()
y_test = test['GPA'].to_frame()
model = LinearRegression()
model.fit(x,y)
score = model.score(x_test,y_test)
score
SAT_input = float(input("input SAT score :"))
sat = [[SAT_input]]
result = model.predict(sat)
print("GPA : ",result)
|
b4ab873041bc8060bf8a8bd8ebeddd379abd9496 | ludimus/AOC2015 | /day02/d2.py | 415 | 3.609375 | 4 | import sys
def wrap(l,w,h):
return((l*w*2) + (w*h*2) + (l*h*2))
def extra_wrap(l,w,h):
nlist=[0,0,0]
nlist[0]=l
nlist[1]=w
nlist[2]=h
nlist.sort()
return(nlist[0]*nlist[1])
numline=0
totwrap=0
for line in sys.stdin:
l,w,h=line.split('x')
totwrap+=wrap(int(l),int(w),int(h))
totwrap+=extra_wrap(int(l),int(w),int(h))
print totwrap
|
486f919201cb5ef1330bec0b54a94168a9e2c315 | simplyluke/austinlp | /8-27/code_examples/5.py | 181 | 3.734375 | 4 | # Lists
a = [1, 3.93, 'hello world']
a.append(2)
print a
# Tuples
b = (10, 20, 83)
print b
# Dictionaries
c = {'a': 3,
(10, 182, 18): 42,
}
print c[(10, 182, 18)]
|
db32bcf4929e83ec22ca2d3431944bd6fe2efff3 | meet-projects/YL1201819team2 | /player.py | 1,745 | 3.953125 | 4 | import turtle
from turtle import*
import random
import math
import time
UP=0
DOWN=1
LEFT=2
RIGHT=3
direction= UP
# func = partial(up, running)
# turtle.onkeypress(up, UP_ARROW)
# turtle.onkeypress(left,"Left")
# turtle.onkeypress(up, "Up")
# turtle.onkeypress(right,"Right")
# turtle.listen()
turtle.register_shape("kidjumping(1).gif")
class Player(Turtle):
def __init__(self, x, y, dx, dy):
Turtle.__init__(self)
self.pu()
turtle.ht()
self.goto(x,y)
self.dx = dx
self.dy = dy
#self.shape("square")#players shape
self.shapesize(50/10)
self.height = 60
self.width= 40
self.shape("kidjumping(1).gif")
def up(self):
# print("going up")
direction = UP
self.goto(self.xcor() , self.ycor() + 250*self.dy)
def left(self):
direction = LEFT
self.goto(self.xcor() - self.dx , self.ycor())
def right(self):
direction = RIGHT
self.goto(self.xcor() + self.dx , self.ycor())
# def move(self):
# old_x = self.xcor()
# old_y = self.ycor()
# global direction
# if direction==RIGHT:
# self.goto(old_x + self.dx , old_y)
# #print("You moved right!")
# elif direction==LEFT:
# self.goto(old_x - self.dx , old_y)
# #print("You moved left!")
# elif direction==UP :
# self.goto(old_x , old_y + self.dy)
def falling_down(self, screen_width, screen_height):
old_x = self.xcor()
old_y = self.ycor()
new_y = old_y - self.dy
self.goto(old_x,new_y)
if self.xcor() > screen_width:
self.goto(-screen_width, self.ycor())
if old_x < -screen_width:
self.goto(-screen_width, self.ycor())
if new_y <= -screen_height:
running=False
self.dy =self.dy + 0.001
print(self.dy)
'''
pl= Player(0,0, 1, 2)
while True:
pl.move()
turtle.listen()
turtle.mainloop()
''' |
8e9e0a55c1ac7987bbe5e28fda6c6f2542a1e3e3 | n800sau/roborep | /fchassis_test/lib/pids.py | 7,493 | 3.734375 | 4 | #!/usr/bin/env python
# pids - Generic proportional-integral-derivative controllers.
'''
Generic proportional-integral-derivative controllers.
ABSTRACT
A proportional-integral-derivative controller (PID controller) is a
generic control loop feedback mechanism widely used in industrial
control systems. A PID controller calculates an "error" value as the
difference between a measured process variable and a desired
setpoint. The controller attempts to minimize the error by adjusting
the process control inputs.
For instance, a sensor may return a voltage representing a
thermocouple reading for an oven temperature, and an actuator may
be sent a signal using completely different voltage scale to describe
the amount of fuel to burn in the oven. A PID controller can link
the two systems as a thermostat: add more fuel when the oven cools,
reduce fuel when the oven is overly hot, closing in on a desired
temperature.
SYNOPSIS
>>> import pids
>>> p = pids.Pid( Kproportional, Kintegral, Kderivative )
>>> p.range( get_my_actuator_minimum(), get_my_actuator_maximum() )
>>> while True:
... output = p.step( my_clock.get_dt(), get_my_sensor_value() )
... set_my_actuator_value( output )
The tuning of the PID parameters is complicated, and depends
on the design of the devices involved. Experimentation is
key.
The meaning of the input, output and limit parameters are explained
through a couple of simple example applications.
EXAMPLE APPLICATIONS
A PID Controller is often selected to control a servomotor.
Many common servomotors swing an arm through an arc, from a
minimum position (e.g., -80 degrees) to a maximum (+80 degrees).
The angle of the arm may be measured by eye in degrees, but
electrically, this is sensed by an electrical resistance value
(e.g., 100 Ohms to 1000 Ohms).
The input signal is a pulse width modulated signal, with pulses
between a minimum width (e.g., 1ms high out of every 20ms) and a
maximum width (2ms high out of every 20ms).
For the PID, this describes the units required for ranges and the
set point.
* the input is the measured angle (say, in ohms)
* the set point is the desired angle (also in ohms)
* the output is the pwm rate applied to motor (in milliseconds)
Another purpose for a PID controller is as an oven thermostat.
A measuring thermocouple is used to detect the current temperature
in the oven. It has a reading in electrical resistance (e.g., 10
K Ohms at 300 degrees Celsius, and +100 Ohms per 10 degrees
Celsius below that level). Sensors may have a non-linear
relationship but the curve is generally sufficiently smooth to
work here.
A heating coil is used to produce heat in the oven. It is rated
to produce heat with a known level of electrical current (e.g.,
anywhere from 0 to 3 Amperes). An actual coil may simply be "on"
or "off," but by alternating the state, heat can be regulated more
smoothly. The output of the controller should decide the level of
alternation requested (e.g., from 0 or always off, to 1 or always
on).
* The input is measured temperature (in ohms)
* The set point is desired temperature (in ohms)
* The output is the heating coil activation (from zero to one)
SEE ALSO
http://en.wikipedia.org/wiki/PID_controller
'''
class Pid (object):
'''A discrete PID (Proportional-Integral-Derivative) controller.'''
def __init__(self, P=1.0, I=1.0, D=1.0, point=0.0, below=-1.0, above=1.0):
'''Sets up basic operational parameters for the controller.
Three constants for the "tuning" of the controller can be given.
* P (proportional gain) scales acceleration to new setpoints
* I (integral gain) scales correction of error buildup
* D (derivative gain) scales bounded rate of output change
The initial desired ouput value or "point" can be given.
The overall output range ("below" and "above") can be given.
'''
self.tune(P, I, D)
self.range(below, above)
self.output = below
self.set(point)
self.input = self.measure()
def reset(self):
self._integral = 0.0
self._previous = 0.0
def step(self, dt=1.0, input=None):
'''Update the controller with a new input, to get new output.
The time step "dt" can be given, or is assumed as an arbitrary 1.0.
If a new "input" value a callable object, it is called for a value.
If a new "input" value is not given here, measure() is called.
'''
if input is None:
self.input = self.measure()
elif callable(input):
self.input = input()
else:
self.input = input
err = self.setpoint - self.input
self._integral += err * dt
I = self._integral
D = (err - self._previous) / dt
output = self.Kp*err + self.Ki*I + self.Kd*D
self._previous = err
self.output = self.bound(output)
def bound(self, output):
'''Ensure the output falls within the current output range.
May be overridden with a new method if overshoot is allowed.
'''
return max(min(output, self.maxout), self.minout)
def range(self, below, above):
'''Set the overall output range.
Outputs are bounded to remain within this range with the bound()
overridable method.
'''
if below > above:
(above, below) = (below, above)
self.minout = below
self.maxout = above
self.reset()
def tune(self, P, I, D):
'''Sets the three constant tuning parameters, P, I, and D.'''
self.Kp = P
self.Ki = I
self.Kd = D
self.reset()
def set(self, point):
'''Sets the desired output value to which the controller seeks.'''
self.setpoint = point
def get(self):
'''Returns the current output value at any time.'''
return self.output
def measure(self):
'''May be overridden to calculate a new input value.'''
return 0.0
#----------------------------------------------------------------------------
if __name__ == '__main__':
import interpolations
def worm(terms, width=120):
line = ' '*width
for term in terms:
left, x, right, sym = term
h = int( interpolations.linear(left, right, x, 0, width-2) )
line = line[:h] + sym + line[h+1:]
print "|" + line + "|"
class ServoPid (Pid):
def __init__(self, **config):
super(ServoPid, self).__init__(**config)
self.speed = 1
self.where = 0
self.maxwhere = 90
self.minwhere = -90
def measure(self):
self.where += self.output / 3.0
self.where = max(min(self.where, self.maxwhere), self.minwhere)
return self.where
import math
import random
pid = ServoPid()
pid.range(-10.0, 10.0)
pid.tune(.8,.1,.1)
pid.set(10)
for i in range(70):
pid.step()
#worm(pid.minout, pid.get(), pid.maxout)
worm( [ (pid.minwhere, pid.setpoint, pid.maxwhere, '+'),
(pid.minwhere, pid.where, pid.maxwhere, '*') ] )
if random.random() < 0.10:
pid.set(random.random() * 25 - 12)
|
1bf12b87587c464a85f6637fd45ed77fd2fe990f | christianns/Curso-Python | /02_Operadores y expresiones/11_Ejercicio.py | 653 | 4.25 | 4 | # Ejercicio 3 - Realiza un programa que cumpla el siguiente algoritmo utilizando siempre que sea posible operadores en asignación:
# * Guarda en una variable numero_magico el valor 12345679 (sin el 8)
# * Lee por pantalla otro numero_usuario, especifica que sea entre 1 y 9
# * Multiplica el numero_usuario por 9 en sí mismo
# * Multiplica el numero_magico por el numero_usuario en sí mismo
# * Finalmente muestra el valor final del numero_magico por pantalla
numero_magico = 12345679
numero_usuario = int(input("Introduce un número del 1 al 9: "))
numero_usuario *= 9
numero_magico *= numero_usuario
print("El número mágico es:", numero_magico)
|
33b8a1e005e5234e3a8dc715d881720254e116ad | nickmwangemi/CodeVillage | /Day9-Python/accountOOP.py | 797 | 4.125 | 4 | """
User inputs their details
Account:
- balance
- customer name
- account number
- currency
"""
class Account:
myAccount = ""
def __init__(self, accNo, name, balance, currency):
self.accNo = accNo
self.name = name
self.balance = balance
self.currency = currency
def showAccount(self):
print("Account Number : ", self.accNo)
print("Account Holder Name : ", self.name)
print("Balance : ", self.balance)
print("Currency: ", self.currency)
accNo = int(input("Enter the account no : "))
name = input("Enter the account holder name : ")
balance = int(input("Enter the balance: "))
currency = input("What's the currency type? ")
print("*"*50)
myAccount = Account(accNo, name, balance, currency)
myAccount.showAccount()
|
bd3b35e4b0646694bca58595f0d886e29f059c24 | league-python-student/level0-module1-teashopp | /_04_int/_1_riddler/riddler.py | 2,014 | 4.28125 | 4 | '''
* Write a python program that asks the user a minimum of 3 riddles.
* You can look at riddles.com if you don't already know any riddles.
* Collect the response of each riddle from the user and compare their
answers to the correct answer.
* Use a variable to keep track of the correctly answered riddles
* After all the riddles have been asked, tell the user how many they got correct
'''
from tkinter import messagebox, simpledialog, Tk
if __name__ == '__main__':
window = Tk
window.withdraw()
correct = 0
guess0 = simpledialog.askstring(None, 'Mr and Mrs. Smith have six daughters. Each daughter has one brother. How many children to Mr and Mrs. Smith have?')
if guess0 = 'seven' or '7':
messagebox.showinfo(None, 'Correct!')
correct += 1
else:
messagebox.showinfo(None, 'Incorrect; they have seven, six daughters and one son.')
guess2 = simpledialog.askstring(None, 'I have one color but infinite sizes. I stay stuck to the floor, but fly so easily. I do you no harm and I feel no pain. What am I?')
if guess2 = 'a shadow' or 'shadow':
messagebox.showinfo(None, 'Correct!')
correct += 1
else:
messagebox.showinfo(None, 'Incorrect; I am a shadow.')
guess3 = simpledialog.askstring(None, 'If eleven plus two equals one, what does nine plus five equal?')
if guess3 = 'two' or '2':
messagebox.showinfo(None, 'Correct!')
correct += 1
else:
messagebox.showinfo(None, 'Incorrect; nine plus five would equal two (on a clock).')
if correct >= 2:
messagebox.showinfo(None, 'Congratulations, you,ve scored ' + correct + ' points!')
elif correct = 1:
messagebox.showinfo(None, 'Ooh, you only scored one point. Better luck next time!')
else:
messagebox.showinfo(None, 'You didn,t get any right. Try harder.')
window.mainloop() |
6489dc0df7d290d75171974f314a56d65e134429 | Ragnhied/H20-IN1910 | /calculator.py | 540 | 3.8125 | 4 | def add(x,y): #Exercise 1,2,3
return x + y
#Her kommer fem funksjoner med utgangspunkt i metoden "Test driven development", exercise 4:
def factorial(x):
f = 1
while x > 0:
f = x*f
x -= 1
return f
def sin(x, N):
s = 0
for i in range(N+1):
s += (((-1)**i)*(x**(2*i+1)))/(factorial((2*i)+1))
return s
def divide(x,y):
return x / y
def sqrt(x):
return ((x)**(1/2))
def cos(x,N):
c = 0
for i in range(N+1):
c+= (((-1)**i)*x**(2*i))/(factorial(2*i))
return c
|
6808bf70eaa901133c52a7c3088a59cfa7d0440c | grigor-stoyanov/PythonAdvanced | /workshop/tic_tac_toe/core/logic.py | 1,244 | 3.578125 | 4 | from tic_tac_toe.core.validators import is_position_in_range, is_place_available, is_winner,is_board_full
from tic_tac_toe.core.helpers import get_row_col, print_current_board_state
def play(players, board, turns):
turn_count = 0
while True:
current_player_name = turns[turn_count % 2]
current_player_sign = players[current_player_name]
# read position
try:
position = int(input(f"{current_player_name} choose a free position:"))
except ValueError:
position = 10
# check if it is in range and position is available
if is_position_in_range(position) and is_place_available(board, position):
row, col = get_row_col(position)
# place sign
board[row][col] = current_player_sign
print_current_board_state(board)
# check if there is a winner
if is_winner(board, current_player_sign):
print(f'{current_player_name} won!')
exit(0)
if is_board_full(board):
print('Game over! No winner!')
exit(0)
else:
# read new position for the same player
turn_count -= 1
turn_count += 1
|
bd0a7f12029be4efce14ed730a86cf9e56c9cd04 | le314u/Academico | /IFMG/TeoriaDaComputação/MP/MP.py | 6,063 | 3.71875 | 4 | class Fila:
def __init__(self, string):
self.dados = []
for char in string:
self.dados.append(char)
def __str__(self):
return str(self.dados)
def insere(self, elemento):
self.dados.append(elemento)
def retira(self):
return self.dados.pop(0)
def vazia(self):
return len(self.dados) == 0
class MaquinaPost:
def __init__(self, pathFile, stringFila):
self.fim = False
self.estados = None
self.alfabeto = None
self.fila = Fila(stringFila)
self.estado = None
self.registrador = None
self.comandos = None
self.carregaFonte(pathFile)
self.executar()
def _edComando(self, tipo, origem, destino, argumento):
"""Cria uma estrutura que representa um programa"""
return {
"tipo": tipo,
"origem": origem,
"destino": destino,
"argumento": argumento
}
# origem argumento destino
def _criaComando(self, linha):
"""Dado uma linha do codigo fonte retorna uma estrutura que representa o comando"""
# Comentario
if linha[0] == "#":
return None
# Atribuição
elif linha[1].lower() == 'atrib':
return self._edComando('atribuicao', linha[0], linha[3], linha[2])
# Verificação
elif linha[1].lower() == 'if':
return self._edComando('verificacao', linha[0], linha[3], linha[2])
# Leitura
elif linha[1].lower() == 'ler':
return self._edComando('ler', linha[0], linha[2], '')
# Aceita
elif linha[1].lower() == 'aceita':
return self._edComando('aceita', linha[0], '', '')
# Rejeita
elif linha[1].lower() == 'rejeita':
return self._edComando('rejeita', linha[0], '', '')
# Erro
else:
return None
def carregaFonte(self, caminhoArquivo):
"""Dado um arquivo Fonte seta as configurações da Maquina"""
self.estados = []
self.alfabeto = []
self.comandos = {}
# Carrega o Arquivo
arquivo = open(caminhoArquivo, "r")
diagrama = []
for i in arquivo:
linha = i.split()
diagrama.append(linha)
# Percorre o arquivo fonte e extrai os comandos
for numeroLinha in range(0, len(diagrama)):
comando = self._criaComando(diagrama[numeroLinha])
if (comando != None):
if comando['origem'] not in self.estados:
self.comandos.update({comando['origem']: []}) # Cria a entrada para o estado na Hash
self.estados.append(comando['origem'])
if comando['destino'] not in self.estados and (comando['tipo'] != 'aceita' and comando['tipo'] != 'rejeita'):
self.comandos.update({comando['destino']: []}) # Cria a entrada para o estado na Hash
self.estados.append(comando['destino'])
if comando['argumento'] not in self.alfabeto and comando['argumento'] != '':
#self.comandos.update({comando['origem']: []}) # Cria a entrada para o estado na Hash
self.alfabeto.append(comando['argumento'])
self.comandos[comando['origem']].append(comando)
def aceita(self):
self.fim = True
print("Aceita")
print(self.fila)
def rejeita(self):
self.fim = True
print("Rejeita")
print(self.fila)
def verifica(self, comando):
executado = False
if (self.registrador == comando['argumento']):
self.estado = comando['destino']
executado = True
return executado
def le(self, comando):
executado = False
if (not self.fila.vazia()):
self.registrador = self.fila.retira()
self.estado = comando['destino']
executado = True
return executado
def atribui(self, comando):
executado = False
self.fila.insere(comando['argumento'])
self.estado = comando['destino']
executado = True
return executado
def executar(self):
# Variaveis de controle
indiceUltimoComandoEstado = -1
# Verifica se há estado 0 na maquina
if not '0' in self.estados:
print("Codigo Fonte Invalido")
self.fim = True
# Seta o estado inicial, a maquian sempre inicia pelo estado 0
self.estado = '0'
comandoAtual = self.comandos['0'][0]
# Inicia o Loop para executar o codigo Fonte
while (not self.fim):
executado = False # Define se a maquina esta funcionando
# Executa a ação conforme o tipo de comando
if (comandoAtual['tipo'] == 'atribuicao'):
executado = self.atribui(comandoAtual)
elif (comandoAtual['tipo'] == 'verificacao'):
executado = self.verifica(comandoAtual)
elif (comandoAtual['tipo'] == 'ler'):
executado = self.le(comandoAtual)
elif (comandoAtual['tipo'] == 'aceita'):
executado = self.aceita()
elif (comandoAtual['tipo'] == 'rejeita'):
executado = self.rejeita()
# Verifica qual o proximo Comando
if (not executado):
if ( indiceUltimoComandoEstado + 1 < len(self.comandos[self.estado]) ):
comandoAtual = self.comandos[self.estado][indiceUltimoComandoEstado + 1]
indiceUltimoComandoEstado = indiceUltimoComandoEstado + 1
else:
self.fim = True
else:
comandoAtual = self.comandos[self.estado][0]
indiceUltimoComandoEstado = 0
# Vazia ou numeros par de 1's
MaquinaPost("./teste.mp", "1010")
|
6ed073f80973d04a78cc4231536b24752fbb5082 | rbabaci1/CS-Module-Algorithms | /eating_cookies/eating_cookies.py | 1,350 | 4 | 4 | """
Input: an integer
Returns: an integer
"""
import time
def eating_cookies(n):
# Brute force solution
if n == 0 or n == 1:
return 1
if n == 2:
return 2
else:
return eating_cookies(n - 1) + eating_cookies(n - 2) + eating_cookies(n - 3)
# Memoization Bottom - Up approach
# if n == 0 or n == 1:
# return 1
# if n == 2:
# return 2
# result = [0 for _ in range(n + 1)]
# result[0], result[1], result[2] = 1, 1, 2
# for i in range(3, n + 1):
# result[i] = result[i - 1] + result[i - 2] + result[i - 3]
# return result[-1]
# Memoization Top - Down approach
# def memo_cookies(n, cache={}):
# if n == 0 or n == 1:
# return 1
# if n == 2:
# return 2
# else:
# if n not in cache:
# cache[n] = (
# memo_cookies(n - 1) + memo_cookies(n - 2) + memo_cookies(n - 3)
# )
# return cache[n]
# return memo_cookies(n)
if __name__ == "__main__":
# Use the main function here to test out your implementation
num_cookies = 5
start = time.time()
print(
f"There are {eating_cookies(num_cookies)} ways for Cookie Monster to each {num_cookies} cookies"
)
print(f"it took: {time.time() - start} seconds.")
|
1b6d658567a4f65b7933152e44b7cc65de2497c3 | jugorcz/PolygonsSumAndProduct | /LinkedList.py | 6,683 | 3.75 | 4 | class Node:
def __init__(self, key, value, next=None):
self.key = key # line
self.value = value # pos y = f(x) -> (x,y)
self.next = next
class LinkedList:
def __init__(self, linesDictionary):
self.start = None
self.size = 0
self.dictionary = linesDictionary
def put(self, key, value):
# print("put " + str(key) + ":" + str(value))
if self.start:
self._put(key, value)
else:
self.start = Node(key, value)
self.size += 1
# self.display()
def calculateNewValue(self, x, function):
a = function[0]
b = function[1]
y = a * x + b
y = round(y, 4)
return (x, y)
# 1 left > right, 0 equal, -1 left < right
# node: line -> (x,y)
# dictionary: line -> function(a,b)
def compareNodes(self, leftNode, rightNode):
function1 = self.dictionary[leftNode.key]
function2 = self.dictionary[rightNode.key]
if function1 == function2:
if leftNode.key[1][1] > rightNode.key[1][1]:
return 1
else:
return -1
leftX = leftNode.value[0]
rightX = rightNode.value[0]
if leftX != rightX:
# print("change base")
if rightX > leftX:
function = self.dictionary[leftNode.key]
leftNode.value = self.calculateNewValue(rightX, function)
else:
function = self.dictionary[rightNode.key]
rightNode.value = self.calculateNewValue(leftX, function)
leftY = leftNode.value[1]
rightY = rightNode.value[1]
if leftY > rightY:
return 1
elif rightY > leftY:
return -1
else:
function = self.dictionary[leftNode.key]
leftNode.value = self.calculateNewValue(leftNode.value[0]+0.5, function)
return self.compareNodes(leftNode, rightNode)
def _put(self, key, value):
# new node goes to the beginning of list
nodeToInsert = Node(key, value)
currentNode = self.start
if self.compareNodes(nodeToInsert, currentNode) == 1:
self.start = nodeToInsert
self.start.next = currentNode
return
# new node goes inside the list
beforeCurrentNode = self.start
currentNode = self.start.next
while currentNode is not None:
if self.compareNodes(nodeToInsert, currentNode) == 1:
beforeCurrentNode.next = nodeToInsert
nodeToInsert.next = currentNode
return
beforeCurrentNode = currentNode
currentNode = currentNode.next
# end of list
beforeCurrentNode.next = nodeToInsert
# key -> line
def get(self, key):
if self.start:
result = self._get(key)
if result:
return result.value
return None
def _get(self, key):
currentNode = self.start
while currentNode:
if currentNode.key == key:
return currentNode
currentNode = currentNode.next
def delete(self, key):
#print("delete " + str(key))
if self.start:
if self._delete(key):
self.size -= 1
else:
print("No node to delete with key: " + str(key))
# self.display()
def _delete(self, key):
# delete from beginning
if self.start.key == key:
self.start = self.start.next
return True
# delete from the middle
beforeCurrentNode = self.start
currentNode = self.start.next
while currentNode:
if currentNode.key == key:
beforeCurrentNode.next = currentNode.next
return True
beforeCurrentNode = currentNode
currentNode = currentNode.next
return False
def display(self):
currentNode = self.start
while currentNode is not None:
print(str(currentNode.key[0]) + "-" + str(currentNode.key[1]) + " -> ", end="")
currentNode = currentNode.next
print("None")
def getLeftNaighbour(self, key):
if self.start.key == key:
return None
beforeCurrentNode = self.start
currentNode = self.start.next
while currentNode:
if currentNode.key == key:
return beforeCurrentNode.key
beforeCurrentNode = currentNode
currentNode = currentNode.next
return None
def getRightNaighbour(self, key):
currentNode = self.start
afterCurrentNode = self.start.next
while afterCurrentNode:
if currentNode.key == key:
return afterCurrentNode.key
currentNode = afterCurrentNode
afterCurrentNode = afterCurrentNode.next
return None
def swapPlaces(self, key1, key2):
#print("swap " + str(key1[0]) + " with " + str(key2[0]))
# swap beginning
if self.get(key1) is None or self.get(key2) is None:
return
node1 = self._get(key1)
node2 = self._get(key2)
if self.compareNodes(node1, node2) == 0:
function = self.dictionary[node1.key]
node1.value = self.calculateNewValue(node1.value[0]+1, function)
if self.compareNodes(node1, node2) == 1:
if node1.next == node2:
return
else:
if node2.next == node1:
return
curr = self.start
after = curr.next
if (curr.key == key1 and after.key == key2) or (curr.key == key2 and after.key == key1):
curr.next = after.next
after.next = curr
self.start = after
else:
before = curr
curr = after
after = after.next
while after:
if (curr.key == key1 and after.key == key2) or (curr.key == key2 and after.key == key1):
curr.next = after.next
after.next = curr
before.next = after
break
before = curr
curr = after
after = after.next
# self.display()
def generatePairs(self):
if self.size < 2:
return None, None
currentNode = self.start
afterCurrentNode = currentNode.next
while afterCurrentNode:
yield currentNode.key, afterCurrentNode.key
currentNode = afterCurrentNode
afterCurrentNode = afterCurrentNode.next |
222ebf7bd73e29fbd9a5124cf851e29c287fc363 | Adasumizox/ProgrammingChallenges | /codewars/Python/8 kyu/AlanPartridgeIIAppleTurnover/apple_test.py | 1,441 | 3.515625 | 4 | from apple import apple
import unittest
class TestAlanPartridgeIIAppleTurnover(unittest.TestCase):
def test(self):
self.assertEqual(apple('50'), "It's hotter than the sun!!")
self.assertEqual(apple(4), "Help yourself to a honeycomb Yorkie for the glovebox.")
self.assertEqual(apple("12"), "Help yourself to a honeycomb Yorkie for the glovebox.")
self.assertEqual(apple(60), "It's hotter than the sun!!")
def test_rand(self):
def myapple(x):
return "It's hotter than the sun!!" if int(x) ** 2 > 1000 else "Help yourself to a honeycomb Yorkie for the glovebox."
import random
names=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60",1, 2, 3,4, 5, 6, 7,8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 24, 25, 26, 27, 28, 29, 30,31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,57, 58, 59, 60];
for _ in range(300):
x = random.sample(names,1)[0]
res = myapple(x)
self.assertEqual(apple(x), res)
if __name__ == '__main__':
unittest.main() |
480fba202c1fac7a972d684e57f851dbd475193f | shivansh-max/Algos | /Arrays/Medium/FindSumWithGoalNumber.py | 643 | 3.546875 | 4 | class FindSumWithGoalNumber:
def __init__(self):
pass
def findSumWithGoalNumber(self, goalNumber, array):
found_numbers = []
print(f"Array : {array}")
found_numbers = []
for i in array:
diff = goalNumber - i
if i != diff:
if diff in array:
found_numbers.append(i)
found_numbers.append(diff)
array.pop(array.index(i))
array.remove(diff)
return found_numbers
print(f"Goal Number : {goalNumber}")
print(f"Found Numbers {found_numbers}")
|
aabd32c9358aa2954f3a6fd5d7eedab23f4710b8 | olutayodurodola/problems | /draw_flower.py | 768 | 3.734375 | 4 | import turtle
def draw_flower():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(10)
for i in range(0,20):
brad.forward(60)
brad.left(45)
brad.forward(30)
brad.left(90)
brad.forward(30)
brad.left(45)
brad.forward(60)
brad.left(30)
brad.right(10)
brad.forward(10)
brad.right(90)
brad.forward(200)
brad.right(90)
brad.forward(10)
brad.right(90)
brad.forward(200)
window.exitonclick()
draw_flower()
def draw_object(m,n=None):
no_of_polygon = m
no_of_sides = n
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed(10)
for i in range():
|
9ab153ba6cce49131906fd5b1b3c95e527187e7b | GitFiras/CodingNomads-Python | /15_generators/15_02_divisible.py | 222 | 4 | 4 | '''
Create a Generator that loops over the given list and prints out only
the items that are divisible by 1111.
'''
my_list = range(1,100000)
generator = (num for num in my_list if num % 1111 == 0)
print(list(generator))
|
b74f65e976e94ef75507948fc55727368afd8643 | ilmiraS/jobeasy-python-course | /lesson_1/homework_1_6.py | 456 | 4.21875 | 4 | # Write your first proger the temperature right now in Fahrenheit in temperature_fahrenheit variable as
# # a string (e.g. '75') and convert it to Celsius.
# # !important you should save only number to result_temperature. Formula (32°F − 32) × 5/9 = 0°C
#
# # type your code here
#temperature_fahrenheit = input("Enter temp in F: ")
temperature_fahrenheit = 75
result_temperature = (temperature_fahrenheit - 32) * 5/9
print(int(result_temperature))
|
701e6f6390c3bffcbbeb4e1626094f3aaaa7b2c6 | baysalbektas0/CyberKey_Method_and_MergeList_Method | /Result2.py | 1,539 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 14:15:29 2021
@author: BektasBaysal
"""
def sortList(array):
""" listedeki elemanları büyükten küçüğe sıralama methodu"""
print("sort içinde")
for i in range(len(array)):
IlkDeger = i
for j in range(i+1, len(array)):
if array[j] < array[IlkDeger]:
IlkDeger = j
array[i], array[IlkDeger] = array[IlkDeger], array[i]
return array
def CypherKey(numbers, key):
""" Şifre oluşturma"""
NumberList = []
"""string haldeki sayıları bir listeye dönüştürme"""
for i in numbers:
NumberList.append(i)
key = [int(x) for x in str(key)]
"""listedi sayıları integer hale dönüştürme"""
for i in range(len(NumberList)):
NumberList[i] = int(NumberList[i])
NewList = sortList(NumberList.copy())
# print(NewList)
"""şifredeki ilk sayının, sayı listesindeki indeksini sayının sonuna ekleme """
for i in range(len(NewList)):
if NewList[i] == key[0]:
NewList.append(i)
break
# print("org:"+ str(NumberList))
# print("Result:"+ str(NewList) )
"""şifreyi string formatına çevirme işlemi"""
StrList = ''.join([str(i) for i in NewList])
print(StrList)
StrListV2 = '"' + StrList +'"'
print(StrListV2)
return NewList,key
firstNumbers = str(input("key: "))
Key = input("number: ")
Result, key = CypherKey(firstNumbers, Key)
|
f4fd96ea6138af1666de6470f5c729e347bef127 | DUanalytics/pyAnalytics | /01C-IIM/PD00_main.py | 11,300 | 3.53125 | 4 | #Topic:Pandas DF
#-----------------------------
#libraries
import numpy as np
import pandas as pd
#pandas DF are combination of panda Series..
#one column data is a Series of one datatype, DF can have multiple data types
from pydataset import data
mtcars = data('mtcars')
mtcarsDF = mtcars
mtcarsDF
#%%describing
mtcarsDF.shape #row, col
mtcarsDF.head(3)
mtcarsDF.tail(4)
mtcarsDF.describe()
mtcarsDF.mpg.describe()
mtcarsDF.columns
mtcarsDF.dtypes #float- decimals, int-discreete
mtcarsDF.head(2)
mtcarsDF.index #here index by rownames
type(mtcarsDF)
mtcarsDF.select_dtypes(include=['int64'])
mtcarsDF.select_dtypes(exclude=['int64'])
mtcarsDF.isna()
mtcarsDF.notna()
id(mtcarsDF)
mtcars.empty
mtcars.size
mtcars.ndim
mtcars.shape
32*11
mtcars.axes
mtcars.values
#%%% access DF
#https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
#Series : s.loc[indexer]
#DataFrame : df.loc[row_indexer,column_indexer]
mtcarsDF[0:5]
mtcarsDF[0:32:5]
mtcarsDF.head(5)
mtcarsDF.loc[:,'mpg']
mtcarsDF.loc['Fiat 128','mpg']
mtcars.axes
mtcarsDF.loc['Fiat 128':,'wt':]
mtcarsDF.loc[:'Fiat 128',:'wt']
#single value: at
mtcarsDF.at['Mazda RX4', 'mpg']
#single values : iat : integer
mtcarsDF.iat[0,0]
mtcarsDF.iat[0,0:5] #error
#set of values : loc : label value
#purely label based indexing. This is a strict inclusion based protocol. Every label asked for must be in the index, or a KeyError will be raised. When slicing, both the start bound AND the stop bound are included, if present in the index. Integers are valid labels, but they refer to the label and not the position.
mtcarsDF.index
mtcarsDF.loc[['Mazda 4X4']]
mtcarsDF.loc['Mazda 4X4', ['mpg']]
mtcarsDF.loc[7:9]
#loc : purely label based indexing
mtcarsDF
mtcarsDF.loc['Mazda RX4']
mtcarsDF.loc['Mazda RX4', 'mpg']
mtcarsDF.loc['Mazda RX4', ['mpg', 'wt']]
mtcarsDF.loc['Merc 280', ['mpg', 'wt']]
mtcarsDF.loc['Mazda RX4':'Datsun 710'] #difficult to implement
#iloc uses index labels, iloc considers position in the index
mtcars.axes
#mtcarsDF.loc[1:7,[['mpg','wt']]
mtcars.columns
mtcarsDF.iloc[0:10, 0:5] #from 1 to 10 rows, from 1 to 5 col
mtcarsDF.iloc[1:10:2, 1:5:2]## from 1 to 10 rows, select every alternate row, from 1 to 5 cols, select every alterante cols
mtcarsDF.iloc[1::2, 1::2]
mtcarsDF.iloc[0]
mtcarsDF.iloc[1:5]
mtcarsDF.iloc[1,5] #2nd row, 6th column
mtcarsDF.iloc[1:5, 0:2] #2nd to 5th row, 0 to 2nd column
mtcarsDF.iloc[:5, :3] #0-4 rows, 0-3 columns
mtcarsDF.iloc[::2] #alternate rows : start, end, step
mtcarsDF.iloc[::-1] #reverse order
mtcarsDF.iloc[::2].iloc[::2] #first alternate, again alternate
mtcarsDF.iloc[:-2:-2] #which rows is this
mtcarsDF.iloc[1::5,:] #5th row start from 1(2nd row)
mtcarsDF.iloc[0:3]
#filter
mtcarsDF.filter(['gear', 'am'])
mtcarsDF.filter(regex = '[gGa]') #small or big G or a in the column name
mtcarsDF.filter(items=['gear','am'])
mtcarsDF.filter(regex='Toyota', axis=0) #rownames axis=0
mtcarsDF.filter(regex='am', axis=1) #colnames axis=1
#%%statistics 0- column, 1-row
mtcarsDF.mean(axis=0)
mtcarsDF.mean(axis=1)
mtcarsDF.kurt(axis=0) #peakendness
mtcarsDF.kurt(axis=1)
mtcarsDF.max(axis=0)
mtcarsDF.max(axis=1)
mtcarsDF.rank(axis=0)
mtcarsDF.skew(axis=0) #shift
mtcarsDF.skew(axis=1)
#%%filter
#condition
mtcarsDF['gear'] == 3 #T&F
mtcars[mtcarsDF['gear'] == 3] #rows with T for gear=3
mtcars[mtcarsDF['gear'] != 3, ['gear','am']]
mtcars[mtcarsDF['gear'] != 3, [['gear','am']]] #error
mtcars[mtcarsDF['gear'] != 3, ['gear']] #TF
#another way
mtcarsDF[mtcarsDF.gear.eq(3)] #chaining method
mtcarsDF[mtcarsDF['gear'] == 3]
mtcarsDF[mtcarsDF['am'] == 0]
mtcarsDF[(mtcarsDF['gear'] == 3) & (mtcarsDF['am']== 0)]
mtcarsDF.gear.unique()
mtcarsDF.carb.unique()
gears=[4,5]
mtcarsDF[mtcarsDF.gear.isin(gears)]
#rows NOT condition
mtcarsDF[~ mtcarsDF.gear.isin(gears)] #cars of not gear(4,5)
#multiple conditions
carbs = [1,3]
mtcarsDF[mtcarsDF.gear.isin(gears) & mtcarsDF.carb.isin(carbs) ]
mtcarsDF[~ mtcarsDF.gear.isin(gears) & mtcarsDF.carb.isin(carbs) ]
#query function
mtcarsDF.query('gear==4')
#if a string
mtcarsDF.query('gear=="4"')
mtcarsDF.query('gear==4 & am==0')
mtcarsDF.query('gear in [3,7]')
#%% summaries - group, sort
mtcarsDF
#stats
mtcarsDF['gear'].count()
mtcarsDF['wt'].max()
mtcarsDF['wt'][mtcarsDF['gear'] == 4]
mtcarsDF['wt'][mtcarsDF['gear'] == 4].sum() #sum of wt of 4 gear cars
mtcarsDF['gear'].value_counts()
mtcarsDF[mtcars['hp'] > 150].gear.value_counts()
mtcarsDF['mpg'].unique()
mtcarsDF['mpg'].nunique()# how many non-null unique values
mtcarsDF['mpg'].count()
#other stats functions - count, sum, mean, mad, median, min, max, mode, abs, prod, std, var, sem, skew, kurt, quantile, cumsum, cumprod, cummax, cummin, describe
mtcarsDF.describe() # default only numeric
#%% sort
mtcarsDF.sort_values(by='gear', axis=0)
mtcarsDF.sort_values(by=['gear', 'mpg']).head(n=10)
mtcarsDF.sort_values(by=['cyl','mpg'], ascending=[True, False]).head(n=20)
#%%% groupby
mtcarsDF.describe()
mtcarsDF.groupby('gear')
mtcarsDF.groupby(['gear'])
mtcarsDF.groupby(['gear']).groups.keys()
mtcarsDF.groupby(['gear']).groups[3] #cars of group with gear 3
mtcarsDF.groupby('carb').first() #first item of each group
mtcarsDF.groupby('carb').last()
mtcarsDF.groupby('gear')['mpg'].mean()
mtcarsDF.groupby('gear').count()
mtcarsDF.groupby('gear')['mpg'].count() #not useful
mtcarsDF.groupby('gear')['mpg'].mean() #useful
mtcarsDF.groupby('cyl')['mpg','wt'].mean()
mtcarsDF.groupby(['cyl','gear'])['mpg','wt'].mean()
#with aggregate
mtcarsDF.groupby('gear').agg('mean')
mtcarsDF.groupby('gear').size()
mtcarsDF.groupby(['gear','cyl']).size()
mtcarsDF.groupby(['gear','cyl']).count() #size better
mtcarsDF.groupby('gear').mpg.agg('mean')
mtcarsDF.groupby('gear')['mpg'].agg('mean')
mtcarsDF.groupby('gear')['mpg','wt'].agg('mean')
mtcarsDF.groupby('gear')['mpg','wt'].agg(['mean','max'])
mtcarsDF.groupby('gear').agg([np.mean, np.sum]) #all columns, np is faster, numeric values
mtcarsDF.groupby('gear')['mpg','wt'].agg([np.mean, np.sum, 'count'])
mtcarsDF.groupby('gear')['mpg'].agg([np.mean, np.sum, 'count'])
#.rename(columns={'meanMPG','sumMPG','countMPG'})
mtcarsDF.groupby('gear').agg(meanMPG = pd.NamedAgg(column='mpg', aggfunc='mean'))
mtcarsDF.groupby(['gear','am']).agg(meanMPG = pd.NamedAgg(column='mpg', aggfunc='max'))
mtcarsDF.groupby('gear').agg(meanMPG = pd.NamedAgg(column='mpg', aggfunc='mean'), maxMPG = pd.NamedAgg(column='wt', aggfunc='max'))
mtcarsDF['gear'].count()
mtcarsDF['gear'].max()
mtcarsDF.groupby('gear').mean()
mtcarsDF.groupby('gear').mean().add_prefix('MEAN_')
gearGp = mtcarsDF.groupby('gear')
gearGp.mean()
gearGp.nth(1) #nth row in each gp
gearGp.nth([1,3]) # 1st and 3rd row in each gp
gearGp.first() #1st row in each gp
gearGp.last() #last row in each gp
gearGp.max() #max value for each gp : max mpg for 3,4,5 gears is..
gearGp.min()
gearGp.size() #size or count per gp
gearGp.count()
gearGp.mean()
gearGp.describe() #standard summary for each gp and variable
#crosstab
import pandas as pd
pd.crosstab(mtcarsDF.cyl, mtcarsDF.gear)
#pivot
pd.crosstab(mtcarsDF.cyl, mtcarsDF.gear, margins=True, margins_name='Total')
pd.crosstab(mtcarsDF.cyl, [mtcarsDF.gear, mtcarsDF.am])
pd.crosstab([mtcarsDF.cyl, mtcarsDF.vs], [mtcarsDF.gear, mtcarsDF.am], rownames=['Cylinder','EngineShape'], colnames=['Gear', 'TxType'], dropna=False)
#pivottable
mtcarsDF.pivot_table('cyl','am', columns='gear') #mean by default
mtcarsDF.pivot_table(values=['mpg','hp'], index=['gear'], columns=['am','vs'])
#index on left, values on columns, columns on left top
#dfply
#pip install dfply #install this library first from anaconda
from dfply import *
mtcarsDF2 = mtcarsDF.copy()
id(mtcarsDF)
id(mtcarsDF2)
mtcarsDF2['carname'] = mtcarsDF2.index
mtcarsDF2.head() #column with carnames
catcol = ['cyl', 'vs', 'am', 'gear' , 'carb']
mtcarsDF2[catcol] = mtcarsDF2[catcol].astype('category')
mtcarsDF2.dtypes
#chaining with >>
mtcarsDF2 >> head(10) >> tail(3)
mtcarsDF2 >> select(X.mpg) #X is current DF
mtcarsDF2 >> select(~X.mpg, ~X.wt). # exclude
mtcarsDF2 >> select(X.mpg, X.wt, X.am) >> head()
mtcarsDF2 >> select(X.mpg, X.wt) >> arrange(X.mpg, ascending = False)
mtcarsDF2 >> select(X.mpg, X.gear, X.wt) >> arrange(-X.gear, X.mpg)
mtcarsDF2 >> mutate(newMPG = 1.2 * X.mpg) >> select(X.mpg, X.newMPG)
mtcarsDF2 >> group_by(X.cyl) #nothing
mtcarsDF2 >> group_by(X.cyl, X.am) >> summarise(meanMPG = X.mpg.mean())
mtcarsDF2 >> group_by(X.cyl, X.am) >> summarise(meanMPG = X.mpg.mean()) >> arrange(X.cyl, X.meanMPG)
#%% graphs
%matplotlib inline
#from pandas: some graphs may not come correct. This is just syntax demo
mtcarsDF.plot(x='wt', y='mpg')
mtcarsDF.plot.area(x='wt', y='mpg')
mtcarsDF.plot.bar(x='gear', y='am')
mtcarsDF.plot.barh(x='gear', y='am')
mtcarsDF.plot.density()
mtcarsDF.mpg.plot.density()
mtcarsDF.plot.hist()
mtcarsDF.mpg.plot.hist()
mtcarsDF.plot.line()
mtcarsDF.mpg.plot.line()
mtcarsDF.plot.pie(y='gear')
mtcarsDF.gear.plot.pie() #not correct
mtcarsDF.boxplot()
mtcarsDF.plot.scatter(x='mpg',y='hp')
#seaborn
import seaborn as sns
xt1 = pd.crosstab(mtcarsDF.cyl, mtcarsDF.gear)
xt1
sns.heatmap(xt1, cmap='YlGnBu', annot=True, cbar=False)
xt2 = pd.crosstab(index=mtcarsDF.gear, columns=[mtcarsDF.am, mtcarsDF.vs], rownames=['Gear'] , colnames =['AM','VS'])
xt2
sns.heatmap(xt2)
sns.heatmap(xt2, cmap='YlGnBu', annot=True, cbar=False)
#ggplot #https://pypi.org/project/ggplot/
#$ pip install -U ggplot
from pandas import Timestamp
import datetime
import pandas as pd
date_types = ( pd.Timestamp, pd.DatetimeIndex, pd.Period, pd.PeriodIndex, datetime.datetime, datetime.time)
#error module 'pandas' has no attribute 'tslib'
from ggplot import *
help(ggplot)
p = ggplot(aes(x='carat', y='price'), data=diamonds)
print(p + geom_point())
ggplot(aesthetics= aes(x='wt', y='mpg'), data=mtcarsDF) + geom_point(color='red')
help(ggplot(aesthetics, data))
ggplot(aesthetics=aes(x='gear'), data=mtcarsDF2) + geom_bar(stat='count', fill='green')
#error tslib https://github.com/yhat/ggpy/issues/662
#C:\ProgramData\Anaconda3\Lib\site-packages\ggplot
#C:\ProgramData\Anaconda3\Lib\site-packages\ggplot\stats
#pip list -v #c:\programdata\anaconda3\lib\site-packages
#%%plotnine
pip install plotnine
from plotnine.data import economics
from plotnine import ggplot, aes, geom_line
( ggplot(economics) # What data to use
+ aes(x="date", y="pop") # What variable to use
+ geom_line() # Geometric object to use for drawing
)
#%% save to/from excel
mtcarsDF.to_csv('mtcars.csv') #check the folder in working dir tab
mtcarsDF.to_excel('mtcars.xlsx', sheet_name='mtcars1')
mtcarsDF.to_clipboard() #clipboard, paste it anywhere
import matplotlib.pyplot as plt
#scatter plot
plt.scatter(x=mtcarsDF.wt, y=mtcarsDF.mpg)
plt.scatter(x='wt', y='mpg', data=mtcarsDF)
plt.scatter(x='wt', y='mpg', data=mtcarsDF, label='MTCars : wt vs mpg')
#run these lines together
plt.scatter(x='wt', y='mpg', c='am' , cmap='bwr', marker ='s',data=mtcarsDF)
plt.scatter(x='wt', y='hp', c='am' , cmap='bwr', marker ='+', data=mtcarsDF)
plt.legend()
plt.show();
#barplot
mtcarsDF.groupby(['gear']).count()
df = mtcarsDF.groupby(['cyl'])['mpg'].mean()
df.plot.bar()
#using matplotlib
#%% other pandas function
#merge, missing values, outliers, join, reshape
|
c70cb4d42c6fb8eae5567f67f7007bc27cdc7a13 | gnd/cancer-works | /process_reading.py | 1,676 | 3.5 | 4 | # -*- coding: utf-8 -*-
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import argparse
# process user input
parser = argparse.ArgumentParser(description='Processes a body of text into sentence metadata for Tacotron 2.')
parser.add_argument('infile', help='Name of the infile.')
parser.add_argument('outfile', help='Name of the outfile.', default='metadata.csv')
args = parser.parse_args()
# read the infile
f = file(args.infile, 'r')
lines = f.readlines()
f.close()
# process the data
text = ""
for line in lines:
if line != '\n':
text += line.replace('\n',' ')
text = text.replace('!“','.')
text = text.replace('?“','.')
text = text.replace('!','.')
text = text.replace('?','.')
text = text.replace('„','')
text = text.replace('“','')
text = text.replace("'",'')
text = text.replace(",",'')
text = text.replace("‘",'')
text = text.replace('…','')
text = text.replace(' — ',', ')
text = text.replace(' —, ',', ')
text = text.replace(' (',', ')
text = text.replace(') ',', ')
text = text.replace(' ',' ')
# find fake sentence ends (mostly in direct speech, the next letter after '. ' is not capitalized)
text_clean = ""
for i in range(len(text)):
if i < len(text)-2:
if ((text[i] == '.') & (text[i+1] == ' ') & (text[i+2].islower())):
text_clean += ','
else:
text_clean += text[i]
# split the text into sentences
lines = text_clean.replace(':','.').split('. ')
# output the outfile
index = 1
f = file(args.outfile, 'w')
for line in lines:
line_out = "{:02d}|{}|{}\n".format(index, line.strip().strip('.'), line.strip().strip('.'))
f.write(line_out)
index+=1
f.close()
|
4c307af457089fe0cb50a811931c925b704505fc | Legacy-Coding/game | /ChildGame.py | 2,180 | 3.875 | 4 | # Stone paper scissors Game
# import pyinstaller
import random
chracters=[ "1", "2", "3"]
print( "1 for stone","2 for paper","3 for scissors")
computer_choice= random.choice(chracters)
no_of_chance=10
chance=0
human_point=0
computer_point=0
while no_of_chance > chance:
Your_input=input(" Select your input\nStone " " Paper " " Scissors ")
computer_input =random.choice(chracters)
# if both input same value
if computer_input==Your_input:
print("Match Tie\n kumbh ke bhai na mila gaye\n\n")
# If you input value is stone
elif Your_input=="1" and computer_input=="2":
computer_point = computer_point +1
print("bhai mujhe paper ne pakad liya \n computer wins 1 point\n\n")
chance = chance +1
elif Your_input=="1" and computer_input=="3":
human_point = human_point +1
print("pathar se scissors ko todh dala \n you wins 1 point\n\n")
chance = chance + 1
#if you input paper
elif Your_input=="2" and computer_input=="1":
human_point = human_point +1
print("paper se pathar ko pakadh liya \n you wins 1 point\n\n")
chance = chance + 1
elif Your_input=="2" and computer_input=="3":
computer_point = computer_point +1
print("Me barbadh ho gya kachi ne mujhe kar diya \n computer wins 1 point\n\n")
chance = chance + 1
#if your input value is scissors
elif Your_input == "3" and computer_input == "1":
computer_point = computer_point + 1
print("Mujhe kuchal diya gya!! \n computer wins 1 point\n\n")
chance = chance + 1
elif Your_input == "3" and computer_input == "2":
human_point = human_point + 1
print("kach!!! kach!!! kat paper ko \nyou wins 1 point\n\n")
chance = chance + 1
# declaring winners
print("Game Over\n")
elif computer_point > human_point:
print(f"Mr. computer wins by Mr. champ point {computer_point} and your point is {human_point}")
elif computer_point < human_point:
print(f"You wins the match by Your point {computer_point} and the losser points is {human_point}")
else: print("game over")
|
9a0bd2f22054bbc6c842a3fb0f1ec2d0857f15d9 | Farizabm/pp2 | /practice pygame/2.py | 573 | 3.703125 | 4 | import pygame
pygame.init()
#RGB(255,255,255)
black=(0,0,0)
white=(255,255,255)
blue=(0,0,255)
green=(0,255,0)
red=(255,0,0)
size =(400,500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("PyGame example")
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.quit:
done = True
screen.fill(white)
pygame.draw.line(screen, green, [0,0], [100,100],5)
for y in range(0,100,10):
pygame.draw.line(screen, red, [0,10+y], [100,110+y], 2)
pygame.display.flip()
pygame.quit() |
15d8d733d947afdf969320803bcd78e1887fb74b | CHENTHIRTEEN/PTA-PYTHON | /chap4/4-3.py | 83 | 3.6875 | 4 | n = int(input())
sum = 1
for i in range(1, n):
sum = (sum + 1) * 2
print(sum) |
b631b70a1bce5c11a6317600a8ffe995540aff32 | brunolange/dcp | /Chapter06/6.2/solution.py | 874 | 3.59375 | 4 |
"""
Reconstruct tree from pre-order and in-order traversals
"""
def reconstruct(pre_order, in_order):
if not pre_order and not in_order:
return None
if len(pre_order) == len(in_order) == 1:
return pre_order[0]
root = Node(pre_order[0])
i = in_order.index(root.value)
root.left = reconstruct(pre_order[1:i+1], in_order[:i])
root.right = reconstruct(pre_order[i+1:], in_order[i+1:])
return root
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return '{} ({}, {})'.format(self.value, self.left or '', self.right or '')
if __name__ == '__main__':
pre_order = ['a', 'b', 'd', 'e', 'c', 'f', 'g']
in_order = ['d', 'b', 'e', 'a', 'f', 'c', 'g']
print(reconstruct(pre_order, in_order))
|
3a4eb52866ceaf1315179647396e46ba22182b85 | mikeodf/Python_Line_Shape_Color | /ch5_prog_12_line_electrify_randomization_1..py | 7,529 | 4.03125 | 4 | """ ch5 No.12
Program name: line_electrify_randomization_1.py
Objective: Add random components to line segments.
Test edge conditions.
Keywords: line, random, edge cases.
============================================================================79
Comments:
Tested on: Python 2.6, Python 2.7.3, Python 3.2.3
Author: Mike Ohlson de Fine
"""
from Tkinter import *
#from tkinter import * # For Python 3.2.3 and higher.
from random import *
import math
root = Tk()
root.title(" Electrify the Line.")
cw = 600 # canvas width
ch = 300 # canvas height
canvas_1 = Canvas(root, width=cw, height=ch, background="white")
canvas_1.grid(row=0, column=1)
def rotate_shape(shape, xy_center, angle_rad):
""" Rotate any shape about a center point xy_center. ( ?????????????????????????? )
"""
#angle_rad = math.radians(angle_degrees)
x_cen = xy_center[0]
y_cen = xy_center[1]
new_shape = []
for i in range(int(len(shape)/2 )):
x_temp = shape[2*i] - x_cen
y_temp = shape[2*i+1] - y_cen
radian_temp = math.atan2(y_temp, x_temp )
length_temp = math.sqrt( y_temp**2 + x_temp**2)
new_angle = angle_rad + radian_temp
new_x = length_temp * math.cos(new_angle) + x_cen
new_y = length_temp * math.sin(new_angle) + y_cen
new_shape.append(new_x)
new_shape.append(new_y)
return new_shape # angle_deg = post rotation angle
def make_horizontal(segment):
""" Rotate to the horizontal.
Detect if a line is positive going right ( direction = 1),
negative going left ( direction = -1) or if slope is infinite.
The atan2() function should take care of verticals.
"""
x1 = segment[0]
y1 = segment[1]
x2 = segment[2]
y2 = segment[3]
delt_y = y2-y1
delt_x = x2-x1
if delt_x > 0: # Normal - x increasing, slope.
x_direction = 1
if delt_x < 0: # Negative moving line.
x_direction = -1
if delt_x == 0: # Vertical line, slope infinite.
x_direction = 0
angle = math.atan2(delt_y, delt_x) # Angle to make line horizontal.
length = math.sqrt(delt_y**2 + delt_x**2)
return length, angle, x_direction
def line_randomize_vertical(xy_line, x_direction, x_delta, standard_deviation):
""" Draw a segmented line with randomized vertical component
added.
"""
going_positive = 1
if xy_line[2] < xy_line[0]: # Negative going line.
going_positive = -1
if xy_line[2] > xy_line[0]: # Normal positive going line.
going_positive = 1
num_steps = int(going_positive * (xy_line[2] - xy_line[0])/x_delta) # A positive number.
xy_list = []
for i in range(num_steps):
y_randomized = xy_line[1] + gauss(mean, standard_deviation)
x_next = xy_line[0] + going_positive * x_direction * i * x_delta
xy_list.append(x_next)
xy_list.append(y_randomized)
return xy_list
def electrocute_line(xy_line):
""" Add a vertical (normal) component of random noise to a line segment.
"""
canvas_1.create_line(xy_line, fill='gray')
length, angle, x_direction = make_horizontal(xy_line) # Horizontalization parameters.
temp_line = [xy_line[0], xy_line[1], xy_line[0] + x_direction * length, xy_line[1]] # Pure horizontal line
canvas_1.create_line(temp_line, fill=kula)
temp_line = line_randomize_vertical(temp_line, x_direction, x_delta, standard_deviation)
xy_center = [ xy_line[0], xy_line[1] ]
temp_line = rotate_shape(temp_line, xy_center, angle)
canvas_1.create_line(temp_line, fill=kula)
# Execute and Demonstrate.
# ==========================
# Edge case test lines.
diagonal_rising_right = [ 50.0,150.0 , 150.0,50.0 ]
diagonal_dropping_left= [ 300.0,100.0 , 100.0,250.0 ]
horizontal_line = [ 400.0,100.0 , 550.0,100.0 ]
vertical_line = [ 350.0,50.0 , 350.0,250.0 ]
# Randomization parameters.
mean = 1.0
standard_deviation = 10.0
x_delta = 1.0 # If this is smaller than the length of a line there are not enough randomized points to plot.
''' Problem Alert! Still to be solved: What if a point is repeated? There should be a 'hedge' in the code:
Skip over the repeated point or take some other suitable measure.
'''
#Original and electrified/noisified lines.
kula = '#00dd00'
canvas_1.create_line( diagonal_rising_right, width=2, fill='#00dd00') # Positive slope.
electrocute_line( diagonal_rising_right)
kula = 'red'
canvas_1.create_line( diagonal_dropping_left, width=2, fill='red') # Negative slope.
electrocute_line(diagonal_dropping_left)
canvas_1.create_line( vertical_line, width=2, fill='red') # Infinite slope.
electrocute_line( vertical_line)
kula = 'blue'
canvas_1.create_line( horizontal_line,width=2, fill='blue') # Zero slope.
electrocute_line(horizontal_line)
root.mainloop()
def electrocute_shape(shape):
""" Add a vertical (normal) component of random noise to each line segment
of a polygon shape.
"""
for i in range(int(len(shape)/2 -1)):
xy_line = [ shape[2 *i], shape[2 *i+1], shape[2 *i+2], shape[2 *i+3] ]
length, angle, x_direction = make_horizontal(xy_line) # Horizontalization parameters.
temp_line = [xy_line[0], xy_line[1], xy_line[0] + x_direction * length, xy_line[1]] # Pure horizontal line
temp_line = line_randomize_vertical(temp_line, x_direction, x_delta, standard_deviation)
if len(temp_line) <= 2:
temp_line = [ temp_line[0], temp_line[1], temp_line[0]+1, temp_line[1] ] # Hedge for x_delta too small.
# Rotate back to original position.
xy_center = [ xy_line[0], xy_line[1] ]
temp_line = rotate_shape(temp_line, xy_center, angle)
canvas_1.create_line(temp_line, fill=kula)
# Execute and Demonstrate.
# ==========================
# Edge case test lines.
# Closed hexagon
hexagon_1 =[ 402.0, 201.0, 303.0, 243.0, 301.0, 363.0, 400.0, 401.0, 504.0, 362.0, 501.0, 241.0, 402.0, 201.0]
# Curl with pure horizontals and verticals.
electra_1 = [ 80,112.3 , 160,52.3 , 260,52.3 , 320,112.3 , 320,192.3 , 260,252.3 , 160,252.36218 , 120,212.3 , 120,132.3 , 180,92.3 , 240,92.3 , 280,132.3 ]
# Curl no horizontals or veticals.
electra_2 = [80,132.36218 , 120,72.362183 , 200,52.362183 , 280,72.362183 , 320,152.36218 , 300,212.36218 , 260,252.36218 , 200,272.36218 , 140,252.36218 , 100,192.36218 , 140,132.36218 , 200,112.36218 ]
# Randomization parameters.
mean = 1.0
standard_deviation = 6.0
x_delta = 1.0 # If this is smaller than the length of a line there are not enough randomized points to plot.
''' Problem Alert! Still to be solved: What if a point is repeated? There should be a 'hedge' in the code:
Skip over the repeated point or take some other suitable measure.
'''
kula = '#0044cc'
electrocute_shape(hexagon_1)
canvas_1.create_line(hexagon_1, width=3, fill=kula)
kula = '#00dd00'
electrocute_shape(electra_1)
canvas_1.create_line(electra_1, width=3, fill=kula)
kula = '#ff4400'
electrocute_shape(electra_2)
canvas_1.create_line(electra_2, width=3, fill=kula)
|
6af4235b803101d82cd6fbadcec4c96ec1a3c19e | ss4328/codingProblems | /archieve/leetcode/trees/lc98_validateBST.py | 911 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.isValidBSTHelper(root, float('-inf'), float('inf'))
#checks the left and right subtree of a particular non-leaf node
def isValidBSTHelper(self, node, low, high):
if not node:
return True
if node.val>=high or node.val<=low:
return False
if not self.isValidBSTHelper(node.right, node.val, high):
return False
if not self.isValidBSTHelper(node.left, low, node.val):
return False
return True
|
2c6e836cac80cc8223cf5c3a8d999bf43ecbf7b1 | Louis-sf/BIS-398-498-LiuShufan | /Assignment4/Assignment 4 - Exercise 7.9.py | 765 | 4.3125 | 4 | # 7.9 (Indexing and Slicing arrays) Create an array containing the
#values 1–15, reshape it into a 3-by-5 array, then use indexing and
#slicing techniques to perform each of the following operations:
import numpy as np
numbers = np.array([i for i in range(1,16)]).reshape(3,5)
#1. Select row 2.
numbers[2]
#2. Select column *4.
numbers[:, 4]
#3. Select rows 0 and 1.
numbers[0:2]
#4. Select columns 2–4.
numbers[:,2:5]
#5. Select the element that is in row 1 and column 4.
numbers[1,4]
#6. Select all elements from rows 1 and 2 that are in columns 0, 2
#and 4.
numbers[1:3, [0,2,4]]
#I am strictly follow the index number the question provided, for example,
# row 1 is row[1], instead of row[0] which I normally interpreted as row1 |
eb37a77b3868a887fd1fdb4c600077566f7d5cbe | mckannaj/Insight_Leetcode | /Week2/Problem6/Zephy_McKanna.py | 2,715 | 3.875 | 4 | """
Given an array where elements are sorted in ascending order,
convert it to a height balanced BST.
Source: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description
"""
import math
# Constructor for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# DO NOT CHANGE THIS CLASS
class Solution(object):
def sortedArrayToBST(self, nums):
##
"""
:type nums: List[int]
:rtype: TreeNode
"""
if (type(nums) is not list):
print('Unknown input; sortedArrayToBST takes a sorted list. Returning None.')
return None
if (len(nums) == 0):
return None
if (len(nums) == 1):
return TreeNode(nums[0])
mid_index = math.floor(len(nums) / 2)
head = TreeNode(nums[mid_index])
head.left = self.sortedArrayToBST(nums[0:mid_index])
head.right = self.sortedArrayToBST(nums[mid_index+1:])
return head
#Please come up with your own testcases below:
def main():
s = Solution()
head = s.sortedArrayToBST([1,2,3,4,5,6,7,8])
next = head
node_num = 0
while (next.left is not None):
node_num += 1
next = next.left
print("Leftmost value expected 1; received {}. Tree height moving left = {}.".format(next.val, node_num))
next = head
node_num = 0
while (next.right is not None):
node_num += 1
next = next.right
print("Rightmost value expected 8; received {}. Tree height moving right = {}.".format(next.val, node_num))
head = s.sortedArrayToBST(list(range(1001)))
next = head
node_num = 0
while (next.left is not None):
node_num += 1
next = next.left
print("Leftmost value expected 0; received {}. Tree height moving left = {}.".format(next.val, node_num))
next = head
node_num = 0
while (next.right is not None):
node_num += 1
next = next.right
print("Rightmost value expected 1000; received {}. Tree height moving right = {}.".format(next.val, node_num))
head = s.sortedArrayToBST(list(range(-9999, 10000, 1111)))
next = head
node_num = 0
while (next.left is not None):
node_num += 1
next = next.left
print("Leftmost value expected -9999; received {}. Tree height moving left = {}.".format(next.val, node_num))
next = head
node_num = 0
while (next.right is not None):
node_num += 1
next = next.right
print("Rightmost value expected 9999; received {}. Tree height moving right = {}.".format(next.val, node_num))
if __name__ == "__main__":
main() |
3ae166c356ab2dce9a8b37dc1557632d290ae20d | aWildOtto/chestnut-tutorial | /chestnutcrazy.py | 6,748 | 4.34375 | 4 | from collections import namedtuple
Customer = namedtuple('Customer', 'name order')
Store = namedtuple('Store', 'name inventory')
def part1(customers, stores):
"""
Function that does
Part 1:
Part 1A: Assuming the list is sorted in decending price, calculate and print
the average item price at each store in ascending price order (reverse the list).
Part 1B: If the list is out of order, print an error message.
"""
store_list = []
for store in stores:
store_items = store.inventory.keys()
allItemtotal = 0
allItemquantity = 0
for item in store_items:
price = store.inventory[item][0]
quantity = store.inventory[item][1]
total_price = price * quantity
allItemtotal += total_price
allItemquantity += quantity
avg_price = allItemtotal / allItemquantity
store_list.append({
'avg_price': avg_price,
'name': store.name,
'inventory': store.inventory
})
store_list.reverse()
prev = None
for store in store_list:
print('The average item at {} costs ${:.2f}'.format(
store['name'], store['avg_price']))
if(prev != None):
if prev >= store['avg_price']:
print('Error: Outdated information, quitting program...')
exit(1)
prev = store['avg_price']
return store_list
def part2(customers, stores):
"""asdklfjlka
Part 2: print sorted customer order
Jared wants 2 Chips, 100 Crisps.
Shannon does not want anything.
"""
customer_orders = []
for customer in customers:
customer_items = customer.order.keys()
customer_order_list = []
for item in customer_items:
customer_order_list.append({
'orderName': item,
'orderCount': customer.order[item]
})
customer_order_list = sorted(customer_order_list, key=sortFunc)
customer_orders.append({
'name': customer.name,
'order_list': customer_order_list
})
return customer_orders
def drone_delivery_service(customers, stores):
"""
Print Instructions for Drone Delivery Service.
:param customers: [Customer(str, {str: float})]
:param stores: [Store(str, {str: [float, int]})]
"""
customer_totals = {} # Use this for part 4
store_list = part1(customers, stores)
customer_orders = part2(customers, stores)
# print('customer_orders->', customer_orders)
# Part 3 & 4 might involve code from part 2...
# Part 3
# print(store_items)
# customer_bought_count = {} # Use this for part 4
for cust_order in customer_orders:
print('cust_order __', cust_order)
if not cust_order['order_list']:
print('{} does not want anything.'.format(cust_order['name']))
pass
else:
customer_totals[cust_order['name']] = {}
print('{} wants'.format(cust_order['name']), end=' ')
# print the line XXX wants x chips, x crips, x Ruby.
for order in cust_order['order_list']:
print('order====', order)
print('{} {}'.format(order['orderCount'],
order['orderName']), end='')
if order == cust_order['order_list'][-1]:
print('.')
else:
print(',', end=' ')
# print('customer_totals--->', customer_totals)
# print the lines XXX Purchased x chips, x crips, x Ruby from xxx
for order in cust_order['order_list']:
# print(order)
for store in store_list:
# print(customer_totals[cust_order['name']][store['name']])
# store => {'avg_price': 1.0, 'name': '99-Cent Store'}
# store(name='Albertsons', inventory={'Chips': [5.00, 10], 'Pizza': [12.00, 3], 'Fries': [5.00, 1]})
if store['name'] not in customer_totals[cust_order['name']].keys():
customer_totals[cust_order['name']][store['name']] = 0
# print(customer_totals)
if order['orderName'] in store['inventory'] \
and store['inventory'][order['orderName']][1] > 0 \
and order['orderCount'] > 0:
# print("store['inventory'][order['orderName']][1] --->", store['inventory'][order['orderName']][1])
buyCount = min(
order['orderCount'], store['inventory'][order['orderName']][1])
print('\tPurchased {} {} at {} for ${:.2f}'.format(
buyCount, order['orderName'], store['name'], buyCount * store['inventory'][order['orderName']][0]))
customer_totals[cust_order['name']][store['name']
] += buyCount * store['inventory'][order['orderName']][0]
# customer_bought_count[cust_order['name']][store['name']]=buyCount
order['orderCount'] -= buyCount
store['inventory'][order['orderName']][1] -= buyCount
# print(customer_totals[cust_order['name']][store['name']])
# print('\t\tcustomer_totals--->',customer_totals)
if order['orderCount'] > 0:
print('\tAll stores were sold out of {}; {} could not purchase {} {}'.format(
order['orderName'], cust_order['name'], order['orderCount'], order['orderName']))
# ----End here----
# print(customer_totals)
# print('\n')
# print( stores)
return customer_totals, stores
def sortFunc(item):
return item['orderName']
if __name__ == '__main__':
# Set submit_mode to False to be able to run this code in python tutor or development mode
# Ensure it is set to True when submitting code
submit_mode = False
if submit_mode:
drone_delivery_service(*eval(input()))
else:
print("THIS IS A TEST RUN - IF YOU ARE SEEING "
"THIS IN SUBMIT MODE, SET submit_mode = True AND RERUN")
drone_delivery_service(
[Customer(name='Jared', order={'Chips': 2, 'Crisps': 100}),
Customer(name='Shannon', order={}),
Customer(name='Caio', order={'Fries': 1, 'Chips': 10})],
[Store(name='Vons', inventory={'Cereal': [10.00, 10]}),
Store(name='Trader Joes', inventory={'Chips': [9, 1]}),
Store(name='Albertsons', inventory={
'Chips': [5.00, 10], 'Pizza': [12.00, 3], 'Fries': [5.00, 1]}),
Store(name='99-Cent Store', inventory={'Salsa': [1.00, 1]})])
|
235b6e3e36c657d3a56def5306da43038902e669 | rootAir/selenium-python | /python-intro/functions.py | 391 | 3.53125 | 4 | #Funções são funções como na matemática
#def
#Funções anônimas lambda
#Def > define, definir
# nome ( Argumento ou parametro )
#Return devolva um valor
def diga_ola (nome_da_pessoa):
return f'Olá {nome_da_pessoa}'
print(diga_ola('Elza'))
print(diga_ola('Maria'))
print(diga_ola('João'))
print(diga_ola('Fulano'))
print(diga_ola('Ciclano'))
print(diga_ola('Beltrano'))
|
da6bb267dbbd2e6949478f245c6b7562719fd476 | lainekendall/CS61A | /Lecture/Lec1:28.py | 1,086 | 4.15625 | 4 | Lecture 1/28
Fibonancci Sequence
0th element: 0
0 1 1 2 3 5 8...
creates a spiral in squares with side lengths of the #s
Generalization
generalizing patterns with arguments
regular geometic shapes relate length and area
Area(square)=r^2
Area(circle)=pi r^2
assert 3>2, 'Math is broken'
nothing will happen
assert 3<2, 'That is false'
if it's false, then you get an error message displaying That is false
assert statements stop execution! if before return statements or etc.
Higher order Functions
def sum_naturals(n):
total, k = 0 , 1
while k<=n:
total, k = total + k, k+1
return total
def sum_cubes(n):
total , k = 0, 1
while k<= n
total, k = total + pow(k,3), k+1
return total
def identity(k):
return k
def cub(k):
return pow (k,3)
def summation:
total , k = 0 , 1
while k<=
Functions as return values
two types of functions:
locally defined functions
functions defined within other functions bodies
are bound to naems in a local frame
def make_adder(n):
def adder(k):
return n+k
return adder
compound operator: make_adder(3)
|
fe2d788952dcef1ac3a332b4c90d031aa94d4757 | BjaouiAya/Cours-Python | /Other/Tools/docstring_course.py | 1,890 | 4.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def add(a, b):
"""
Adds two numbers and returns the result.
This add two real numbers and return a real result. You will want to
use this function in any place you would usually use the ``+`` operator
but requires a functional equivalent.
:param a: The first number to add
:param b: The second number to add
:type a: int
:type b: int
:return: The result of the addition
:rtype: int
:Example:
>>> add(1, 1)
2
>>> add(2.1, 3.4) # all int compatible types work
5.5
Il faut préciser qu’on veut tester une sortie tronquée avec +ELLIPSIS :
>>> print(list(range(20))) # doctest: +ELLIPSIS
[0, 1, ..., 18, 19]
>>> print(list(range(20))) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19]
Les espaces sont signficatifs, du coup il faut parfois marquer les tests
avec +NORMALIZE_WHITESPACE :
>>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
.. seealso:: sub(), div(), mul()
.. warnings:: This is a completly useless function. Use it only in a
tutorial unless you want to look like a fool.
.. note:: You may want to use a lambda function instead of this.
.. todo:: Delete this function. Then masturbate with olive oil.
"""
return a + b
# TODO: un truc à faire (format à utiliser si on prévoit la modification car
# reconnu par certain pareurs)
# A la fin de votre script, mettez ce snippet qui va activer les doctest
if __name__ == "__main__":
import doctest
doctest.testmod()
|
d3bcc4454fa7337652cdc7ebeb5ee4d525c7e107 | schaetimm/cg_1 | /Vector/Vector4.py | 6,510 | 3.796875 | 4 | class Vec4():
def __init__(self, x=0, y=0, z=0, w=0):
"""Constructor for Vec4
DO NOT MODIFY THIS METHOD"""
self.values = [x, y, z, w]
def __str__(self):
"""Returns the vector as a string representation
DO NOT MODIFY THIS METHOD"""
toReturn = ''
if self is None: return '0.00 0.00 0.00 0.00'
for c in range(0, 4):
toReturn += "%.2f" % self.values[c]
if c != 3:
toReturn += ' '
return toReturn
def mul(self, v):
"""Element wise multiplication of self by vector v
Returns the result as a new vector"""
return Vec4(self.values[0]*v.values[0], self.values[1]*v.values[1], self.values[2]*v.values[2], \
self.values[3]*v.values[3])
def mulc(self, c):
"""Element wise multiplication of vec4 by constant c
Returns the result as a new vector"""
return Vec4(self.values[0] * c, self.values[1] * c, self.values[2] *c, \
self.values[3] *c)
def add(self, v):
"""Element wise addition of vec4 by vector v
Returns the result as a new vector"""
return Vec4(self.values[0] + v.values[0], self.values[1] + v.values[1], self.values[2] + v.values[2], \
self.values[3] + v.values[3])
def addc(self, c):
"""Element wise addition of vec4 by constant c
Returns the result as a new vector"""
return Vec4(self.values[0] + c, self.values[1] + c, self.values[2] + c, \
self.values[3] + c)
def sub(self, v):
"""Element wise subtraction of vec4 by vector v
Returns the result as a new vector"""
return Vec4(self.values[0] - v.values[0], self.values[1] - v.values[1], self.values[2] - v.values[2], \
self.values[3] - v.values[3])
def subc(self, c):
"""Element wise subtraction of vec4 by constant
Returns the result as a new vector"""
return Vec4(self.values[0] - c, self.values[1] - c, self.values[2] - c, \
self.values[3] - c)
def cross(self, v):
"""Returns the cross product of self and vector v, ignore w in calculations
and set w of the resulting vector to 1"""
return Vec4(self.values[1] * v.values[2] - self.values[2] * v.values[1], self.values[2] * v.values[0] - self.values[0] * v.values[2], self.values[0] * v.values[1] - self.values[1] * v.values[0], 1)
def dot(self, v):
"""Returns the dot product of self and vector v"""
return self.values[0] * v.values[0] + self.values[1] * v.values[1] + self.values[2] * v.values[2] \
+ self.values[3] * v.values[3]
class Matrix4():
def __init__(self, row1=None, row2=None, row3=None, row4=None):
"""Constructor for Matrix4
DO NOT MODIFY THIS METHOD"""
if row1 is None: row1 = Vec4()
if row2 is None: row2 = Vec4()
if row3 is None: row3 = Vec4()
if row4 is None: row4 = Vec4()
self.m_values = [row1, row2, row3, row4]
def __str__(self):
"""Returns a string representation of the matrix
DO NOT MODIFY THIS METHOD"""
toReturn = ''
if self is None: return '0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00\n0.00 0.00 0.00 0.00'
for r in range(0, 4):
for c in range(0, 4):
toReturn += "%.2f" % self.m_values[r].values[c]
if c != 3:
toReturn += ' '
toReturn += '\n'
return toReturn
def setIdentity(self):
"""Sets the current Matrix to an identity matrix
self is an identity matrix after calling this method"""
vector_1000 = Vec4(1,0,0,0)
vector_0100 = Vec4(0,1,0,0)
vector_0010 = Vec4(0,0,1,0)
vector_0001 = Vec4(0,0,0,1)
self.m_values =[vector_1000, vector_0100, vector_0010, vector_0001]
def mulV(self, vector):
"""Multiplication: Matrix times vector.
'vector' is the vector with which to multiply.
Return the result as a new Vec4.
Make sure that you do not change self or the vector.
return self * v"""
return Vec4(self.m_values[0].values[0]*vector.values[0] + self.m_values[0].values[1]*vector.values[1] + self.m_values[0].values[2]*vector.values[2] + self.m_values[0].values[3]*vector.values[3], \
self.m_values[1].values[0]*vector.values[0] + self.m_values[1].values[1]*vector.values[1] + self.m_values[1].values[2]*vector.values[2] + self.m_values[1].values[3]*vector.values[3], \
self.m_values[2].values[0]*vector.values[0] + self.m_values[2].values[1]*vector.values[1] + self.m_values[2].values[2]*vector.values[2] + self.m_values[2].values[3]*vector.values[3], \
self.m_values[3].values[0]*vector.values[0] + self.m_values[3].values[1]*vector.values[1] + self.m_values[3].values[2]*vector.values[2] + self.m_values[3].values[3]*vector.values[3])
def roundM(self):
"""Rounds every entry in the matrix"""
for r in range(0,4):
for c in range(0,4):
self.m_values[r].values[c] = round(self.m_values[r].values[c])
return
def mulM(self, m):
"""Multiplication: Matrix times Matrix.
m is the matrix with which to multiply.
Return the result as a new Matrix4.
Make sure that you do not change self or the other matrix.
return this * m"""
return Matrix4(
Vec4(
self.m_values[0].dot(m.column(0)),
self.m_values[0].dot(m.column(1)),
self.m_values[0].dot(m.column(2)),
self.m_values[0].dot(m.column(3))),
Vec4(
self.m_values[1].dot(m.column(0)),
self.m_values[1].dot(m.column(1)),
self.m_values[1].dot(m.column(2)),
self.m_values[1].dot(m.column(3))),
Vec4(
self.m_values[2].dot(m.column(0)),
self.m_values[2].dot(m.column(1)),
self.m_values[2].dot(m.column(2)),
self.m_values[2].dot(m.column(3))),
Vec4(
self.m_values[3].dot(m.column(0)),
self.m_values[3].dot(m.column(1)),
self.m_values[3].dot(m.column(2)),
self.m_values[3].dot(m.column(3))),
)
|
4c7315defe0e946e4e0c6c7d76b208d68c21f592 | rajeshkannanb/PythonPrograms | /encapsulate.py | 1,243 | 4.1875 | 4 | class Encapsulate:
#declare private variables
__speed = None
__color = None
#Init method for class
def __init__(self):
self.__speed = 100
self.__color = "Grey"
#public method to set the speed of car
def set_speed(self, speed):
self.__speed = speed
#public method to set the color of car
def set_color(self, color):
self.__color = color
#private method to get the speed of car
def __get_speed(self):
return self.__speed
#private method to get the color of car
def __get_color(self):
return self.__color
#public method to display properties of car
def print_car_properties(self):
print(self.__get_speed())
print(self.__get_color())
#create object for class Encapsulate which will invoke the __init__ method.
honda = Encapsulate()
#honda.__speed = 200 //Invalid. Syntax is right. But the speed value will not be overriden.
honda.print_car_properties()
hyndai = Encapsulate()
hyndai.set_speed(200)
hyndai.print_car_properties()
ecoSport = Encapsulate()
ecoSport.set_speed(300)
ecoSport.set_color("Red")
#ecoSport.__get_speed() //Invalid invocation since the method is private.
ecoSport.print_car_properties()
|
8709a3c6773b8dbed3111e14450b51fa76256a8a | Gowri678/ResumeChatBot-Dialogflow | /experience.py | 581 | 3.5 | 4 | import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","1234","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EXPERIENCE")
# Create table as per requirement
sql = """CREATE TABLE EXPERIENCE (
ID INT ,
Company VARCHAR(15) ,
Joiningdate VARCHAR(50),
Enddate VARCHAR(50),
Role VARCHAR(20)
)"""
cursor.execute(sql)
# disconnect from server
db.close()
|
b960b883c0d1b7a2c5051aca0e6a9a8aa8c46310 | stronger-jian/learn_python3 | /python/pythonic/c3.py | 103 | 3.796875 | 4 | #列表推导式
#list set dict tuple
a={1,2,3,4,5,6,7,8,9,10}
b={i**2 for i in a if i>=5}
print(b) |
36a3a6abd182079786e382092aee71ed230b8bf6 | gutierrecunha/urionlinejudge_python | /URI_1012 - (8433094) - Accepted.py | 449 | 3.8125 | 4 | Arr = input().split( )
A=Arr[0]
B=Arr[1]
C=Arr[2]
TRIANGULO = (float(A) * float(C))/2
print("TRIANGULO: {:.3f}".format(TRIANGULO))
pi = 3.14159
CIRCULO= float(C)*float(C) * pi
print("CIRCULO: {:.3f}".format(CIRCULO))
TRAPEZIO = ((float(A)+float(B))*float(C))/2
print("TRAPEZIO: {:.3f}".format(TRAPEZIO))
QUADRADO= float(B)*float(B)
print("QUADRADO: {:.3f}".format(QUADRADO))
RETANGULO= float(A)*float(B)
print("RETANGULO: {:.3f}".format(RETANGULO)) |
eaac3eacd730c4ad7d6fc10efbfe1d8adb264ee9 | wintryJK/python_project | /day29/03 属性查找.py | 833 | 3.984375 | 4 |
# 单继承背景下的属性查找
# 示范一:
# class Foo:
# def f1(self):
# print('Foo.f1')
#
# def f2(self):
# print('Foo.f2')
# Foo.f1(self)
# # self.f1()
#
# class Bar(Foo):
# def f1(self):
# print('Bar.f1')
#
# obj = Bar()
# obj.f2()
# Foo.f2
# Bar.f1
# 示范2
# class Foo:
# def f1(self):
# print('Foo.f1')
#
# def f2(self):
# print('Foo.f2')
# Foo.f1(self)
#
# class Bar(Foo):
# def f1(self):
# print('Bar.f1')
#
# obj = Bar()
# obj.f2()
# 示范3
class Foo:
def __f1(self):
print('Foo.f1')
def f2(self):
print('Foo.f2')
# Foo.f1(self)
self.__f1() # 这里已经变形_Foo__f1
class Bar(Foo):
def f1(self): #__f1,也会调用Foo
print('Bar.f1')
obj = Bar()
obj.f2() |
be3feca0cf391b77b199e22d6a8c6337e884952c | 15929134544/wangwang | /py千峰/day13线程与协程/threading01.py | 1,839 | 4.125 | 4 | """
又想并行执行线程,又想保证数据的安全性,则引入同步
如果多个线程共同对某个数据进行修改,则可能出现不可预料的后果,为了保证数据的正确性,需要对
多个线程,需要对多个线程进行同步。
同步:一个一个的完成,一个完成另一个才能进来。效率就会降低。
使用Thread对象的Lock或者Rlock可以实现简单的线程同步,这两个对象都有acquire和release方法,
对于那些需要每次只允许一个线程操作的数据,可以将其放在acquire和release方法之间。(就可以将
要操作的数据锁住)
多线程的优势在于可以同时运行多个任务(至少感觉起来是这样)。但是当线程需要共享数据时,可能存在
数据不同步的问题,为了避免这种情况,所以才引入了锁的概念。
使用锁步骤:
1、创建锁对象:lock = threading.Lock()
2、请求得到锁:lock.acquire()
进行数据共享的操作...
3、释放锁:lock.release()
只要不释放锁,其他的线程都无法进入运行状态。
"""
import threading
import random
import time
# 创建锁对象
lock = threading.Lock()
list1 = [0] * 10 # 列表可以用+/*,*表示10个0
def task1():
# 申请获取线程锁,如果已经上锁,则等待锁的释放
# lock.acquire() # 阻塞
for i in range(len(list1)):
list1[i] = 1
time.sleep(0.5)
# lock.release()
def task2():
# lock.acquire() # 阻塞
for i in range(len(list1)):
print('--------->', list1[i])
time.sleep(0.5)
# lock.release()
if __name__ == '__main__':
# 创建线程
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t2.start()
t1.start()
t2.join()
t1.join()
print(list1)
|
eb9a7eeea9e3d9a7f620cc77568350d6d2fb6168 | meganjacob/CS50AI | /Project0/tictactoe/tictactoe.py | 3,482 | 3.9375 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
numOfEmpty = 0
for item in board:
for i in item:
if i == EMPTY:
numOfEmpty += 1;
if numOfEmpty % 2 == 0:
return O
else:
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
options = set()
for row in range(3):
for column in range(3):
if board[row][column] == EMPTY:
options.add((row, column))
return options
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
(row, column) = action
cp = copy.deepcopy(board)
cp[row][column] = player(board)
return cp
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
for row in board:
if row[0] == row[1] and row[1] == row[2]:
return row[0]
for column in range(3):
if board[1][column] == board[0][column] and board[1][column] == board[2][column]:
return board[1][column]
if board[0][0] == board[1][1] and board[0][0] == board[2][2]:
return board[0][0]
if board[0][2] == board[1][1] and board[1][1] == board[2][0]:
return board[0][2]
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) != None:
return winner(board)
return False
for item in board:
for i in item:
if i == EMPTY:
return False
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == X:
return 1
elif winner(board) == O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
#check if game is over
optimal = maximize(board)
return optimal
def maximize (board):
bestAction = None
lastIteration = None
bestScore = float("-inf")
for action in actions(board):
lastIteration = action
maxResult = result(board, action)
if terminal(maxResult) == True:
score = utility(maxResult)
if score > bestScore and action != None:
bestScore = score
bestAction = action
if score == 1:
return action
else:
minimize(maxResult)
if bestAction == None:
bestAction = lastIteration
return bestAction
def minimize (board):
lastIteration = None
bestAction = None
bestScore = float("inf")
for action in actions(board):
lastIteration = action
minResult = result(board, action)
if terminal(minResult) == True:
score = utility(minResult)
if score < bestScore and action != None:
bestScore = score
bestAction = action
if score == -1:
return action
else:
maximize(minResult)
if bestAction == None:
bestAction = lastIteration
return bestAction
|
07dbfdf51b070eb0b6c89a842f2c84d18bb44451 | anhnguyendepocen/Dynamics | /lineup.py | 1,025 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 20:57:37 2018
@author: shahrear
[email protected]
ref: https://matplotlib.org/examples/mplot3d/lorenz_attractor.html
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def lineup(x, y, z, a=10,b=1,c=10,d=1,e=3,f=2,g=3):
x_dot = a + b*x
y_dot = c + d*x + e*y
z_dot = f*y**2 + g*x**2
return x_dot, y_dot, z_dot
dt = 0.01
n = 10000
# Need one more for the initial values
x = np.empty((n + 1,))
y = np.empty((n + 1,))
z = np.empty((n + 1,))
# Setting initial values
x[0], y[0], z[0] = (1, 1, 2)
# Stepping through "time".
for i in range(n):
# Derivatives of the X, Y, Z state
x_dot, y_dot, z_dot = lineup(x[i], y[i], z[i])
x[i + 1] = x[i] + (x_dot * dt)
y[i + 1] = y[i] + (y_dot * dt)
z[i + 1] = z[i] + (z_dot * dt)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, z, lw=2.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("")
plt.show()
|
f16e49e286ffbc27eab62df2f774f7a799e8206a | aesopiaceo/newtest | /create_tables.py | 558 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 23:12:37 2020
@author: eddomboAesopia
"""
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE if NOT EXISTS users(id INTEGER PRIMARY KEY, username text, password text)" # AUTO-INCREMENTING ID
cursor = connection.execute(create_table)
create_table = "CREATE TABLE if NOT EXISTS items(id INTEGER PRIMARY KEY, name text, price real)"
cursor = connection.execute(create_table)
connection.commit()
connection.close()
|
1fd4c8fd677d857fe3dae7005f5d07bb7433dcf3 | danielts0121/Begginig | /hello-world.py | 89 | 3.703125 | 4 | num = 12 // 4
num = num * 2
num = num * 2
print(num)
def print_hello():
print("HI") |
ee5e85b0bd5e4f32fe069c6f14877c3bc396f004 | azalduar/cs215_Intro_to_Algorithms | /week3/pset3/BridgeEdge.py | 7,402 | 4.125 | 4 | # Bridge Edges v4
#
# Find the bridge edges in a graph given the
# algorithm in lecture.
# Complete the intermediate steps
# - create_rooted_spanning_tree
# - post_order
# - number_of_descendants
# - lowest_post_order
# - highest_post_order
#
# And then combine them together in
# `bridge_edges`
# So far, we've represented graphs
# as a dictionary where G[n1][n2] == 1
# meant there was an edge between n1 and n2
#
# In order to represent a spanning tree
# we need to create two classes of edges
# we'll refer to them as "green" and "red"
# for the green and red edges as specified in lecture
#
# So, for example, the graph given in lecture
# G = {'a': {'c': 1, 'b': 1},
# 'b': {'a': 1, 'd': 1},
# 'c': {'a': 1, 'd': 1},
# 'd': {'c': 1, 'b': 1, 'e': 1},
# 'e': {'d': 1, 'g': 1, 'f': 1},
# 'f': {'e': 1, 'g': 1},
# 'g': {'e': 1, 'f': 1}
# }
# would be written as a spanning tree
# S = {'a': {'c': 'green', 'b': 'green'},
# 'b': {'a': 'green', 'd': 'red'},
# 'c': {'a': 'green', 'd': 'green'},
# 'd': {'c': 'green', 'b': 'red', 'e': 'green'},
# 'e': {'d': 'green', 'g': 'green', 'f': 'green'},
# 'f': {'e': 'green', 'g': 'red'},
# 'g': {'e': 'green', 'f': 'red'}
# }
#
import pprint
def make_link(G, node1, node2, r_or_g):
# modified make_link to apply
# a color to the edge instead of just 1
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = r_or_g
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = r_or_g
return G
def create_rooted_spanning_tree(G, root):
# use DFS from the root to add edges and nodes
# to the tree. The first time we see a node
# the edge is green, but after that its red
open_list = [root]
S = {root:{}}
while len(open_list) > 0:
node = open_list.pop()
neighbors = G[node]
for n in neighbors:
if n not in S:
# we haven't seen this node, so
# need to use a green edge to connect
# it
make_link(S, node, n, 'green')
open_list.append(n)
else:
# we have seen this node,
# but, first make sure that
# don't already have the edge
# in S
if node not in S[n]:
make_link(S, node, n, 'red')
return S
# This is just one possible solution
# There are other ways to create a
# spanning tree, and the grader will
# accept any valid result
# feel free to edit the test to
# match the solution your program produces
def test_create_rooted_spanning_tree():
G = {'a': {'c': 1, 'b': 1},
'b': {'a': 1, 'd': 1},
'c': {'a': 1, 'd': 1},
'd': {'c': 1, 'b': 1, 'e': 1},
'e': {'d': 1, 'g': 1, 'f': 1},
'f': {'e': 1, 'g': 1},
'g': {'e': 1, 'f': 1}
}
S = create_rooted_spanning_tree(G, "a")
assert S == {
'a': {'c': 'green', 'b': 'green'},
'c': {'a': 'green', 'd': 'red'},
'b': {'a': 'green', 'd': 'green'},
'e': {'d': 'green', 'g': 'green', 'f': 'green'},
'd': {'c': 'red', 'b': 'green', 'e': 'green'},
'g': {'e': 'green', 'f': 'red'},
'f': {'e': 'green', 'g': 'red'}
}
test_create_rooted_spanning_tree()
###########
def post_order(S, root):
# return mapping between nodes of S and the post-order value
# of that node
pprint.pprint(S)
po = {root:0}
node_list = [root]
inc = 0
while len(node_list) > 0:
current_node = node_list.pop()
for child in S[current_node]:
if S[current_node][child] == "green":
if child not in po:
po[child] = 0
node_list.append(child)
else:
if child not in po:
inc+=1
po[child] = inc
return po
# This is just one possible solution
# There are other ways to create a
# spanning tree, and the grader will
# accept any valid result.
# feel free to edit the test to
# match the solution your program produces
def test_post_order():
S = {'a': {'c': 'green', 'b': 'green'},
'b': {'a': 'green', 'd': 'red'},
'c': {'a': 'green', 'd': 'green'},
'd': {'c': 'green', 'b': 'red', 'e': 'green'},
'e': {'d': 'green', 'g': 'green', 'f': 'green'},
'f': {'e': 'green', 'g': 'red'},
'g': {'e': 'green', 'f': 'red'}
}
po = post_order(S, 'a')
print po
"""assert po == {'a':7, 'b':1, 'c':6, 'd':5, 'e':4, 'f':2, 'g':3}"""
test_post_order()
##############
def number_of_descendants(S, root):
# return mapping between nodes of S and the number of descendants
# of that node
pass
def test_number_of_descendants():
S = {'a': {'c': 'green', 'b': 'green'},
'b': {'a': 'green', 'd': 'red'},
'c': {'a': 'green', 'd': 'green'},
'd': {'c': 'green', 'b': 'red', 'e': 'green'},
'e': {'d': 'green', 'g': 'green', 'f': 'green'},
'f': {'e': 'green', 'g': 'red'},
'g': {'e': 'green', 'f': 'red'}
}
nd = number_of_descendants(S, 'a')
assert nd == {'a':7, 'b':1, 'c':5, 'd':4, 'e':3, 'f':1, 'g':1}
###############
def lowest_post_order(S, root, po):
# return a mapping of the nodes in S
# to the lowest post order value
# below that node
# (and you're allowed to follow 1 red edge)
pass
def test_lowest_post_order():
S = {'a': {'c': 'green', 'b': 'green'},
'b': {'a': 'green', 'd': 'red'},
'c': {'a': 'green', 'd': 'green'},
'd': {'c': 'green', 'b': 'red', 'e': 'green'},
'e': {'d': 'green', 'g': 'green', 'f': 'green'},
'f': {'e': 'green', 'g': 'red'},
'g': {'e': 'green', 'f': 'red'}
}
po = post_order(S, 'a')
l = lowest_post_order(S, 'a', po)
assert l == {'a':1, 'b':1, 'c':1, 'd':1, 'e':2, 'f':2, 'g':2}
################
def highest_post_order(S, root, po):
# return a mapping of the nodes in S
# to the highest post order value
# below that node
# (and you're allowed to follow 1 red edge)
pass
def test_highest_post_order():
S = {'a': {'c': 'green', 'b': 'green'},
'b': {'a': 'green', 'd': 'red'},
'c': {'a': 'green', 'd': 'green'},
'd': {'c': 'green', 'b': 'red', 'e': 'green'},
'e': {'d': 'green', 'g': 'green', 'f': 'green'},
'f': {'e': 'green', 'g': 'red'},
'g': {'e': 'green', 'f': 'red'}
}
po = post_order(S, 'a')
h = highest_post_order(S, 'a', po)
assert h == {'a':7, 'b':5, 'c':6, 'd':5, 'e':4, 'f':3, 'g':3}
#################
def bridge_edges(G, root):
# use the four functions above
# and then determine which edges in G are bridge edges
# return them as a list of tuples ie: [(n1, n2), (n4, n5)]
pass
def test_bridge_edges():
G = {'a': {'c': 1, 'b': 1},
'b': {'a': 1, 'd': 1},
'c': {'a': 1, 'd': 1},
'd': {'c': 1, 'b': 1, 'e': 1},
'e': {'d': 1, 'g': 1, 'f': 1},
'f': {'e': 1, 'g': 1},
'g': {'e': 1, 'f': 1}
}
bridges = bridge_edges(G, 'a')
assert bridges == [('d', 'e')]
|
4c761268c0874cbc16af7f2f6696ad3995b896ec | vishwasks32/python3-learning | /myp3basics/examples/ex4.py | 298 | 3.78125 | 4 | #!/usr/bin/env python3
#
# Author : Vishwas K Singh
# Email : [email protected]
#
aList = [] # an empty list
bList = [1,2,3]
print(bList[2])
bList.append(4)
print(bList.pop())
print(bList)
bList.remove(2)
print(bList)
# Tuples
ktuple = (1,2,3,4)
print(ktuple)
print(len(ktuple))
print(ktuple[2])
print(ktuple[2:4])
|
6781a619f3cca60f64e9171692138ac5472152b7 | DrunkReaperMatt/LOG635-H2019 | /labo2/ImageProcessing/imageprocess.py | 1,187 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
'''
Program allowing the conversion of an image to Grey color and crop out the desired region.
Inspired from:
Programme Python basique pour extraction de primitives
Ameni MEZNI, [email protected]
Date: 22/08/2018
Necessary command(s):
pip install opencv-python
'''
# import necessary packages
import cv2 as cv
from labo2.ImageProcessing.squares import find_squares
# function that reads an image and returns its grayscale cropped square region
def process_image(image_path):
# import the image and transform it to grayscale
gray_image = cv.imread(image_path, cv.IMREAD_GRAYSCALE)
# find all squares in image
print(image_path + '......Loaded!')
squares = find_squares(gray_image)
cv.drawContours(gray_image, squares, -1, (0, 255, 0), 3)
# if no square was found, simply use the original image
cropped_image = gray_image
if len(squares) != 0:
# crop the grayscale image with the contours
cropped_image = gray_image[squares[0][0][1]:squares[0][2][1], squares[0][1][0]:squares[0][3][0]]
# resize image to make it smaller
resized_image = cv.resize(cropped_image, (32, 14))
return resized_image
|
6c7f802ccd68fed59a9d33efba7f17d4512abfd9 | houstonwalley/Kattis | /Python/Planina.py | 75 | 3.765625 | 4 | n = int(input())
h = 2
for i in range(n):
h += (h - 1)
print(pow(h, 2)) |
b3cfb3dd5be2370f3e17531498059fff03bebffc | aggykey/Bootcamp | /day_2/sum_digits.py | 223 | 3.9375 | 4 | def sum_digits(A):
'''
Takes a list A,and returns
the sum of all the digits in the
list e.g[10,30,45] should return
1+0+3+0+4=5
'''
total = 0
for i in A:
for i in str (i):
total+=int(i)
return total
|
b5311e11b16a6b1c61e907a9dfaad97650c53bf8 | ksaubhri12/ds_algo | /practice_450/greedy/32_smallest_number.py | 1,156 | 3.796875 | 4 | import math
def smallest_number(sum_value: int, digits: int):
max_sum = 9 * digits
if sum_value > max_sum:
return "-1"
curr_sum = 1
number = str(int(math.pow(10, digits - 1)))
return smallest_number_util(curr_sum, number, sum_value, digits)
def smallest_number_util(curr_sum: int, number: str, sum_need: int, digits: int):
for i in reversed(range(0, digits)):
if int(number[i]) == 0 or int(number[i]) == 1:
remaining_sum = sum_need - curr_sum
if remaining_sum >= 10:
number_list = list(number)
number_list[i] = str(9)
curr_sum = curr_sum + 9
number = ''.join(number_list)
return smallest_number_util(curr_sum, number, sum_need, digits)
else:
number_list = list(number)
value = int(number[i]) + remaining_sum
number_list[i] = str(value)
return ''.join(number_list)
if int(number[i]) == 9:
continue
return '-1'
if __name__ == '__main__':
print(smallest_number(20, 3))
print(smallest_number(9, 2))
|
85d9031b2ef97761ea742a363b586fea521c9d4e | omarsinan/hackerrank | /submissions/day_6.py | 248 | 3.75 | 4 | # author: Omar Sinan
# date: 01/09/2017
# description: HackerRank's "Day 6: Let's Review" Coding Challenge
n = int(raw_input())
strings = []
for i in range(n):
s = raw_input()
strings.append(s)
for i in strings:
print i[::2], i[1::2]
|
60f586e5c910ace0c67d8edcb7bb039bdf58e1ef | mrkiril/softheme | /simple.py | 2,571 | 3.78125 | 4 | from math import sqrt
import re
import time
class SimpleNumb(object):
"""
Some about this class
"""
def __init__(self, n):
self.n = n
def s_num(self):
"""
Search all simple numbers to the number
you input in class identification
"""
lst = [2]
for i in range(3, self.n + 1, 2):
if (i > 10) and (i % 10 == 5):
continue
for j in lst:
if j * j - 1 > i:
lst.append(i)
break
if (i % j == 0):
break
else:
lst.append(i)
return lst
def circle(self, s):
"""
Construct circle simple numbers
to the s number
"""
if len(s) == 1:
return [s]
if len(s) > 1:
arr_s = []
new_s = s + s
for s_i in range(len(s)):
arr_s.append(new_s[s_i:s_i + len(s)])
for i in range(len(arr_s)):
pattern = re.match("(0+)?(\d+)", arr_s[i])
arr_s[i] = pattern.group(2)
return arr_s
def ci_num(self, lst):
"""
check is the simple numbers is the
circle simple and return list of it
"""
ci_arr = []
i = 0
while True:
if i == len(lst):
break
w_num = False
for n in ["0", "2", "4", "5", "6", "8"]:
if n in str(lst[i]) and 1 < len(str(lst[i])):
w_num = True
i += 1
break
if w_num:
continue
lst_cir = self.circle(str(lst[i]))
is_all = False
for c_el in lst_cir:
if int(c_el) in lst:
is_all = True
if int(c_el) not in lst:
is_all = False
i += 1
break
if is_all:
for c in set(lst_cir):
ci_arr.append(c)
for c_el in set(lst_cir):
if int(c_el) not in lst:
_ = input("\r\nWTF error ?!")
if int(c_el) in lst:
lst.remove(int(c_el))
return ci_arr
start_time = time.time()
simple = SimpleNumb(1000000)
list_numb = simple.s_num()
ci_numb = simple.ci_num(list_numb)
print("Elapsed time: {:.3f} sec".format(time.time() - start_time))
for n in ci_numb:
print(n)
|
783656258bd5b5fcbff7385b151251f4cbfd3084 | yuchen125/mygit | /OOP/practice_school.py | 3,348 | 3.984375 | 4 | Course_list = []
class School(object):
def __init__(self, school_name):
self.school_name = school_name
self.students_list = []
self.teachers_list = []
global Course_list
def hire(self, obj):
self.teachers_list.append(obj.name)
print("我们现在聘请了一个新老师{0}".format(obj.name))
def enroll(self, obj):
self.students_list.append((obj.name))
print("我们又有了一个新学员{0}".format(obj.name))
class Grade(School):
def __init__(self, school_name, grade_code, grade_course):
super().__init__(school_name)
self.code = grade_code
self.course = grade_course
self.numbers = []
Course_list.append(self.course)
print("我们现在有了{}的{}的{}".format(self.school_name, self.code, self.course))
def course_info(self):
print("课程大纲{}是day01,day02,day03".format(self.course))
Python = Grade("北京", 3, "Python")
Linux = Grade("成都", 1, "Linux")
class School_member(object):
def __init__(self, name, age, sex, role):
self.name = name
self.age = age
self.sex = sex
self.role = role
self.course_list = []
print("我叫{},我是一个{}".format(self.name, self.role))
stu_num_id = 0
class Students(School_member):
def __init__(self, name, age, sex, role, course):
super().__init__(name, age, sex, role)
global stu_num_id
stu_num_id += 1
stu_id = course.school_name + 'S' + str(course.code) + str(stu_num_id).zfill(2)
# zfill 填充的作用,当只有一位数是前面填充0, 只能对str类型做操作
self.id = stu_id
self.mark_list = {}
def study(self, course):
print("我来这里学习{}课,我的学号是{}".format(course.course,self.id))
def pry(self, course):
print("我交1000块,给{}".format(course.course))
self.course_list.append(course.course)
def praise(self, obj):
print("{}觉得{}真棒".format(self.name, obj.name))
def mark_check(self):
for i in self.mark_list.items():
print(i)
def out(self):
print("我离开了")
tea_num_id = 0
class Teachers(School_member):
def __init__(self, name, age, sex, role, course):
super().__init__(name, age, sex, role)
global tea_num_id
tea_num_id += 1
tea_id = course.school_name + 'T' + str(course.code) + str(tea_num_id).zfill(2)
self.id = tea_id
def teach(self,course):
print("我来这里讲{}门课,我的ID是{}".format(course.course,self.id))
def record_mark(self, Date, course, obj, level):
obj.mark_list['Day' + Date] = level
a = Students("小张",18,"M","student",Python)
Python.enroll(a)
a.study(Python)
a.pry(Python)
b = Students("小王", 22, "F", "student", Python)
Python.enroll(b)
b.study(Python)
b.pry(Python)
c = Teachers("小周", 30, 'M', "teacher", Python)
Python.hire(c)
c.teach(Python)
c.record_mark("1", Python, a, "A")
c.record_mark("1", Python, b, "B")
c.record_mark("2", Python, a, "B")
c.record_mark("2", Python, b, "A")
print("小王查看了自己的课程")
print(b.course_list)
print("小王查看了自己的成绩")
b.mark_check()
print("小王退出了")
b.out()
print("给好评")
a.praise(c)
|
8fd85f810c2867a2f06435ba4892940632380931 | rishinkaku/advanced_python | /generators_and_iterators/generators.py | 1,450 | 3.96875 | 4 | """
Генераторы
Генераторы позволяют значительно упростить работу по конструированию итераторов. В предыдущих примерах, для построения
итератора и работы с ним, мы создавали отдельный класс. Генератор – это функция, которая будучи вызванной в функции
next() возвращает следующий объект согласно алгоритму ее работы. Вместо ключевого слова return в генераторе используется
yield.
"""
# Generator expression
exp = (x for x in range(10))
print(exp) # <generator object <genexpr> at 0x7f4f41942938>
print(type(exp)) # <class 'generator'>
print('*'*50)
# Generator object
def simple_generator(val):
while val > 0:
val -= 1
yield val
gen = simple_generator(10) # Create Generator
print(gen) # object simple_generator at 0x7f91294cc830>
print(type(gen)) # <class 'generator'>
for elem in gen:
print(elem) # 9, 8, 7, 6 ...
# Can be used only one time
print('*'*50)
gen2 = simple_generator(10) # Create Generator
print(next(gen2)) # 9, 8, 7, 6 ...
print(next(gen2))
print(next(gen2))
print(next(gen2))
print(next(gen2))
print('*'*50)
gen3 = (num*2 for num in range(10))
for _ in range(10):
print(gen3.__next__())
|
1f2762d5e4b677a7c6d538097c555802e1811556 | carmenLi555/python-challenge | /PyBank/main2.py | 2,452 | 3.796875 | 4 | import os
import csv
budgetcsv = os.path.join("Resources", "budget_data.csv")
with open (budgetcsv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header =next(csvfile)
print(f"Header: {header}")
# find net amount of profit and loss by creating a list
PandL = []
months = []
#read through each row of data after header by using append
for rows in csvreader:
PandL.append(int(rows[1]))
months.append(rows[0])
# find revenue change by creating a list inside the loop
difference = []
#Call len(obj) with obj as an iterable to return the number of items obj contains.
# set 1 as the indext starts at 1 and stops at the len(PanL) - last row
for x in range(1, len(PandL)):
difference.append((int(PandL[x]) - int(PandL[x-1])))
# calculate average revenue change
revenue_average = sum(difference) / len(difference)
# calculate total length of months
total_months = len(months)
# greatest increase in revenue
greatest_increase = max(difference)
# greatest decrease in revenue
greatest_decrease = min(difference)
# print the Results
print("Financial Analysis")
print("....................................................................................")
print("total months: " + str(total_months))
print("Total: " + "$" + str(sum(PandL)))
print("Average change: " + "$" + str(revenue_average))
print("Greatest Increase in Profits: " + str(months[difference.index(max(difference))+1]) + " " + "$" + str(greatest_increase))
print("Greatest Decrease in Profits: " + str(months[difference.index(min(difference))+1]) + " " + "$" + str(greatest_decrease))
# output to a text file
file = open("analysis/output.txt","w")
file.write("Financial Analysis" + "\n")
file.write("...................................................................................." + "\n")
file.write("total months: " + str(total_months) + "\n")
file.write("Total: " + "$" + str(sum(PandL)) + "\n")
file.write("Average change: " + "$" + str(revenue_average) + "\n")
file.write("Greatest Increase in Profits: " + str(months[difference.index(max(difference))+1]) + " " + "$" + str(greatest_increase) + "\n")
file.write("Greatest Decrease in Profits: " + str(months[difference.index(min(difference))+1]) + " " + "$" + str(greatest_decrease) + "\n")
file.close() |
8a61abc712fa702ca0377382bc1d1caa9d5f944a | Hunter-Chambers/WTAMU-Assignments | /CS3305/Demos/demo0/hello.py | 493 | 3.875 | 4 | #!/usr/bin/env python3
'''
This is a simple Python 3 program
Program text should be entered using vim or gvim
and saved in a file named hello.py.
At the CLI prompt, enter the command: chmod u+x hello.py
to inform the Linux OS that the file should be executable.
To execute this program, at the CLI prompt enter the
command: ./hello.py
'''
def main():
''' simple main to demonstrate Python'''
print("%s" % "Hello World!")
# end main
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.