blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
bcd71b974626cf9a62445a587cd21afb2085d9f8 | Sydcn-tek/Python-By-Sydcn | /day02.py | 8,413 | 3.78125 | 4 | # username=input('请输入用户名:')
# password=input('请输入密码:')
# if username =='admin' and password =='123456789':
# print('身份验证成功!')
# else:
# print('身份验证失败!')
# s=input('请输入成绩:')
# if '60'<=s<'70' :
# print('成绩为C!')
# elif '70'<=s<'80' :
# print('成绩为B!')
# else :
# print('成绩为A!')
# username=input('请输入用户名:')
# u=username[0]
# if u in '!@#$%^&*()':
# print('用户名不能以特使字符开头!')
# else :
# pass
# x=float(input('x='))
# if x>1:
# print(3*x-5)
# elif -1<=x<=1:
# print(x+2)
# else :
# print(x+3)
# a=float(input('请输入一个数字:'))
# b=input('输入一个运算符(+、-、*、/):')
# c=float(input('请输入另一个数字:'))
# if b=='+' :
# print('%a+c')
# elif b=='-':
# print('%a-c')
# elif b=='*':
# print('%a*c')
# else:
# print('%a/c')
# import numpy as nu
# res = np.random.choice(['剪刀','石头','布'])
# print(res)
# number=int(input('请输入一个五位数:'))
# a = int(number[0])
# b = int(number[1])
# c = int(number[2])
# d = int(number[3])
# e = int(number[4])
# if a==e and b==d :
# print('该数字为回文数!')
# else:
# print('该数字不是回文数!')
# import time
# import pygame
# file=r'D:\CloudMusic\薛之谦-慢半拍.mp3'
# pygame.mixer.init()
# print('播放音乐1')
# track = pygame.mixer.music.load(file)
# pygame.mixer.music.play()
# time.sleep(10)
# pygame.mixer,music.stop()
# sum1 = 0
# sum2 = 0
# for x in range(1,101):
# if x%2==0:
# sum2 += x
# else:
# sum1 += x
# print(sum1,sum2 )
# import time
# start = time.time()
# sum_= 0
# for i in range(1000000):
# sum_ += i
# end = time.time()
# print(end - start)
# for i in range(1,10):
# for j in range(1,i+1):
# print('%d*%d=%d'%(j,i,j*i),end='\t')
# print(end='\n')
# from math import sqrt
# num = int(input('请输入一个正整数: '))
# end = int(sqrt(num))
# is_prime = True
# for x in range(2, end + 1):
# if num % x == 0:
# is_prime = False
# break
# if is_prime and num != 1:
# print('%d是素数' % num)
# else:
# print('%d不是素数' % num)
# a = 'abcdefg'
# i = 0
# while i <len(a):
# print(a[i])
# i += 1
# 1.
# import math
# a=float(input('请输入第一个数字:'))
# b=float(input('请输入第二个数字:'))
# c=float(input('请输入第三个数字:'))
# if (b**2-4*a*c)>0:
# r1=(-b+math.sqrt(b**2-4*a*c))/(2*a)
# r2=(-b-math.sqrt(b**2-4*a*c))/(2*a)
# print('r1=%.6f,r2=%.6f'%(r1,r2))
# elif (b**2-4*a*c)==0:
# r1=(-b+math.sqrt(b**2-4*a*c))/(2*a)
# r2=(-b-math.sqrt(b**2-4*a*c))/(2*a)
# print('r1=%.6f'%r1)
# else:
# print('The equation has no real roots')
# 2.
# import numpy
# num1 =numpy.random.choice(range(0,100))
# num2 =numpy.random.choice(range(0,100))
# num3 =float(input('请输入一个数字'))
# if num3 == num1+num2:
# print('行吧...')
# else:
# print('滚!!!')
3.
num1=int(input('输入一个数字看看今天周几:'))
num2=int(input('你还想看哪天:'))
if num1==0:
today='Sunday'
elif num1==1:
today='Monday'
elif num1==2:
today='Tuesday'
elif num1==3:
today='Wednesday'
elif num1==4:
today='Thursday'
elif num1==5:
today='Friday'
elif num1==6:
today='Saterday'
if num2>7:
print((num1+num2)%7)
# 4.
# def count(a,b,c):
# num = [a,b,c]
# num.sort()
# print(num)
# def start():
# a = int(input('输入第一个整数:'))
# b = int(input('输入第二个整数:'))
# c = int(input('输入第三个整数:'))
# count(a,b,c)
# start()
# 5.
# def shop(weight1,weight2,price1,price2):
# package1 = weight1 / price1
# package2 = weight2 / price2
# if package1 > package2:
# print('package1 has the better price')
# else:
# print('package2 has the better price')
# def start():
# weight1 = float(input('第一种重量是:'))
# price1 = float(input('第一种价格是:'))
# weight2 = float(input('第二种重量是:'))
# price2 = float(input('第二种价格是:'))
# shop(weight1,weight2,price1,price2)
# start()
# 6.
# import calendar
# def num(year,month):
# print(calendar.monthrange(year, month)[1])
# def start():
# year = int(input('Enter year: '))
# month = int(input('Enter month number: '))
# num(year,month)
# start()
# 7.
# import random
# x = int(input('请输入你的猜测(1为正,2为反):'))
# a = random.randint(1,2)
# if x == a:
# print('你猜对了')
# else:
# print('你猜错了')
# 8.
# import random
# U_res = int(input('0:石头,1:剪刀,2:布>>>'))
# C_res = random.randint(0,2)
# if C_res == U_res:
# print('平局')
# else:
# if C_res == 0 and U_res == 1:
# print('电脑赢了 ')
# elif C_res == 1 and U_res == 2:
# print('电脑赢了 ')
# elif C_res == 2 and U_res == 0:
# print('电脑赢了 ')
# else:
# print('你赢了 ')
# 9.
# def main(year,m,d):
# a = ['周六','周日','周一','周二','周三','周四','周五']
# if m == 1:
# m = 13
# year = year - 1
# if m ==2:
# m = 14
# year = year - 1
# h = int(d+((26*(m+1))//10)+(year%100)+((year%100)/4)+((year//100)/4)+5*year//100)%7
# day = a[h]
# print('那一天是一周中的:%s' %day)
# def Start():
# year = int(input('输入哪一年:'))
# m = int(input('输入月份1-12:'))
# d = int(input('输入月份第几天1-31:'))
# main(year,m,d)
# Start()
# 10.
# def chou():
# import numpy as np
# daxiao=np.random.choice(['A','2','3','4','5','6','7','8','9','10','J','Q','K'])
# huase=np.random.choice(['梅花','红桃','方块','黑桃'])
# print('你选择的牌是 %s , %s'%(huase,daxiao))
# def Start():
# a = input("是否决定抽牌y/n:")
# if a == 'y':
# chou()
# else:
# pass
# Start()
# 11.
# num = input('输入一个三位数:')
# if int(num[0])==int(num[2]):
# print('是回文数')
# else:
# print("不是回文数")
# 12.
# a,b,c = map(float,input('enter three edge:').split(','))
# if a+b>c and a+c>b and b+c>a:
# L = a+b+c
# print("其周长为",L)
# else:
# print("不是三角形三条边")
# 2.
# money = 10000
# sum1 = 0
# for i in range(1,14):
# money = money * 0.05 + money
# if i ==10:
# print('十年之后的学费:%.2f'%money)
# if i >= 10:
# sum1 += money
# print('十年后大学四年的总学费为:%.2f'%sum1)
# 4.
# geshu = 0
# for i in range(100,1001):
# if i%5 == 0 and i%6 == 0:
# print(i,end=' ')
# geshu += 1
# if geshu % 10 == 0:
# print('\n')
# 5.
# n = 0
# m = 0
# while n**2 <= 12000:
# n += 1
# print('n的平方大于12000的最小整数n为:%d'%n)
# while m**3 < 12000:
# m += 1
# print('n的立方大于12000的最大整数n为:%d'%(m-1))
# 6.
# sum1 = 0
# sum2 = 0
# for i in range(1,50001):
# sum1 += 1/i
# i += 1
# print('从左向右计算为:',sum1)
# for i in range(50000,0,-1):
# sum2 += 1/i
# i -= 1
# print('从右向左计算为:',sum2)
#8.
# sum1 = 0
# for i in range(3,100,2):
# sum1 += (i-2)/i
# print('数列的和为:',sum1)
#9.
# pi = 0
# i = int(input('输入i的值:'))
# for j in range(1,i+1):
# pi += 4 * ((-1)**(1+j)/(2*j-1))
# print('π的值为:%f'%pi)
#11.
# list1 = []
# for i in range(1,8):
# for j in range(1,8):
# if i != j and sorted([i,j]) not in list1:
# list1.append([i,j])
# print('所有可能的组合为:',list1)
# print('组合总个数为:',len(list1))
|
9725fd88bf4149217c5cf924c2a9adc57ee036ba | srisaipog/ICS4U-Classwork | /Learning/Classes/encapsulating/oct 24.py | 841 | 3.796875 | 4 |
class Person:
def __init__(self, name: str, age: int):
self.set_name(name)
self._age = age
def get_age(self):
return self._age
def set_age(self, to_be_age):
if type(to_be_age) == int:
self._age = to_be_age
def get_name(self):
return self._first_name + " " + self._last_name
def set_name(self, to_be_name):
if type(to_be_name) == str:
first, last = to_be_name.split()
self._first_name = first
self._last_name = last
# Getters ans setters for every attribute
# Encapsulate if you are going to relase
# code to the public
VOTING_AGE = 18
p = Person(name="Jeff Dickinson", age=22)
if p.get_age() >= VOTING_AGE:
print(f"{p.get_name()} can vote")
else:
print(f"{p.get_name()} can not vote") |
caf7ebd6e43de85002b5607ae2cd6da15796ce22 | tolkamps1/sevens7 | /hands.py | 4,455 | 3.5625 | 4 | import db
import players
import board
def create_hand(hand, player_id):
clubs = []
diamonds = []
spades = []
hearts = []
for [num, suite] in hand:
print("HAND!!! num{} suite {}".format(num, suite))
if(suite == "clubs"):
clubs.append(str(num))
if(suite == "spades"):
spades.append(str(num))
if(suite == "hearts"):
hearts.append(str(num))
if(suite == "diamonds"):
diamonds.append(str(num))
clubs = " ".join(clubs)
spades = " ".join(spades)
hearts = " ".join(hearts)
diamonds = " ".join(diamonds)
print(clubs)
print(spades)
print(hearts)
print(diamonds)
conn = db.get_db()
curs = conn.cursor()
curs.execute("INSERT INTO hands (player_id, clubs, hearts, diamonds, spades) VALUES (?,?,?,?,?);",
(player_id, clubs, hearts, diamonds, spades))
conn.commit()
res = curs.execute("SELECT * FROM hands WHERE player_id=last_insert_rowid()").fetchall()
return db.hands_row_to_dict(res[0])
def find_7_clubs():
conn = db.get_db()
curs = conn.cursor()
rows = curs.execute ("SELECT * FROM hands").fetchall()
for row in rows:
b = db.hands_row_to_dict(row)
print(b)
clubs = str(b["clubs"]).split(" ")
for club in clubs:
if int(club) == 7:
return b["player_id"]
return -1
def lay_card_down(suit, num, player_id):
count = players.get_player_count()
next_turn = player_id % count + 1
conn = db.get_db()
curs = conn.cursor()
rows = curs.execute("SELECT {} FROM board".format(suit)).fetchone()
new_row = ''
li = []
if rows[0]:
if len(str(rows[0])) > 1:
li = rows[0].split(" ")
else:
li.append(str(rows[0]))
li.append(num)
new_row = " ".join(li)
else:
new_row = str(num)
print(new_row)
curs.execute("UPDATE board SET {}='{}', cur_player_id={};".format(str(suit), str(new_row), str(next_turn)))
conn.commit()
rows = curs.execute("SELECT * FROM board;").fetchone()
print("NEWBOARD "+str(rows[0]))
rows = curs.execute("SELECT {} FROM hands WHERE player_id={};".format(suit, player_id)).fetchone()
conn.commit()
if rows[0]:
prev_row = rows[0].split(" ")
new_row = []
for c in prev_row:
if c == num:
continue
new_row.append(c)
new_row = " ".join(new_row)
print(new_row)
print(suit)
print(player_id)
curs.execute("UPDATE hands SET {}='{}' WHERE player_id={};".format(suit, str(new_row), str(player_id)))
conn.commit()
else:
raise Exception("Excuse me, wut")
def update_hands(suit, num, player_id):
count = players.get_player_count()
taker = player_id % count + 1
print(player_id)
print(suit)
print(num)
conn = db.get_db()
curs = conn.cursor()
rows = curs.execute("SELECT {} FROM hands WHERE player_id={};".format(suit, player_id)).fetchone()
conn.commit()
if rows[0]:
prev_row = rows[0].split(" ")
new_row = []
for c in prev_row:
if c == num:
continue
new_row.append(c)
new_row = " ".join(new_row)
print(new_row)
print(suit)
print(player_id)
curs.execute("UPDATE hands SET {}='{}' WHERE player_id={};".format(suit, str(new_row), str(player_id)))
conn.commit()
else:
raise Exception("Excuse me, wut")
hand = get_hand(player_id)
print("GIVERS HAND ")
print(hand)
rows = curs.execute("SELECT {} FROM hands WHERE player_id={};".format(suit, str(taker))).fetchone()
conn.commit()
if rows[0]:
prev_row = rows[0].split(" ")
prev_row.append(num)
new_row = " ".join(prev_row)
print(new_row)
print(suit)
print(player_id)
curs.execute("UPDATE hands SET {}='{}' WHERE player_id={};".format(suit, str(new_row), str(taker)))
conn.commit()
else:
raise Exception("Excuse me, wut")
hand = get_hand(taker)
print("TAKERS HAND ")
print(hand)
def get_hand(player_id):
conn = db.get_db()
curs = conn.cursor()
res = curs.execute ("SELECT * FROM hands WHERE player_id={}".format(player_id)).fetchone()
print("le hand "+str(res))
return db.hands_row_to_dict(res) |
1495d71aad82337c3002d566f5d7548ed1387e81 | xaviBlue/curso_python | /tuples.py | 191 | 3.765625 | 4 | x = (1,2,3,4,5)
print(type(x))
y=tuple((1,2,3))
print(y)
print(x[0])
#usamos del para eliminer la tupla
locations={
(34.56,6431.4):"tokyo",
(34.6,641.4):"orlando"
}
print(locations) |
46b1efb1cb015d099bd0ae7db12bf2d3d90a688e | sanjaykumardbdev/pythonProject_1 | /19_ifelif_2.py | 190 | 3.953125 | 4 | x = 21
if x == 1:
print("One")
elif x == 2:
print("Two")
elif x == 3:
print("Three")
elif x == 4:
print("Four")
elif x == 5:
print("Five")
else:
print("Wrong Input")
|
3970600d8d6b34e49334b5d718fd1d1f9c5faa97 | SimonCWatts/CS50x | /dna.py | 2,924 | 4.25 | 4 | import sys
import csv
def main():
'''
The main function opens the csv & txt files,
extracts the list of STRs to search for,
and prints the name of the person whos dna profile matches the sample provided in the txt file.
'''
# If your program is executed with the incorrect number of command-line arguments, your program should print an error message of your choice (with print).
if len(sys.argv[:]) != 3:
print("USAGE: python dna.py databases/large.csv sequences/5.txt")
return
# Open people databse csv file and store in 'data'
csv_data = open(sys.argv[1], 'r')
# List of STRs to search for
reader = csv.reader(csv_data)
row1 = next(reader)
list_of_str = row1[1:]
# List of People
list_of_people = [line for line in reader]
# Open the dna file and store in 'dna'
txt_data = open(sys.argv[2], 'r')
dna = txt_data.read()
# Locate the STR sequences in the dna sample provided
str_sequences = findSTR(list_of_str, dna)
# Find the person who matches the dna sample
winner = findMatch(str_sequences, list_of_people)
# Print the name of the winner
print(winner)
# Close the files
csv_data.close()
txt_data.close()
return
def findSTR(list_of_str, dna):
'''
list_of_str: a list of strings that represent the STRs we are searching for.
dna: a string of dna code.
returns a list containing the longest consecutive sequence of each STR found within the dna sample
'''
# loc is a list of lists.
loc = []
# Each inner list represents the locations of each instance of a single STR in the dna sample.
for STR in list_of_str:
# Store each STR location in a list
STRlocs = [i for i in range(len(dna)) if dna[i: i + len(STR)] == STR]
loc.append(STRlocs)
# Make a list of the number of consecutive occurances of each STR
seq = []
for STRS in loc:
sequences = []
counter = 1
for i in range(len(STRS) - 1):
if (STRS[i + 1] - STRS[i]) == len(list_of_str[len(seq)]):
counter += 1
else:
sequences.append(counter)
counter = 1
sequences.append(counter)
seq.append(sequences)
# Find the MAX sequence from each list
max_seq = []
for s in seq:
max_seq.append(str(max(s)))
return max_seq
def findMatch(str_sequences, list_of_people):
'''
str_sequences: a list of maximum consecutive sequences for each STR found in the dna sample
list_of_people: a list of maximum consecutive sequences for each STR found in the that persons dna
returns: the name of the person who is identical to the STR sequences found in the sampel.
'''
for person in list_of_people:
if person[1:] == str_sequences:
return(person[0])
return("No Match")
# Execute main
main() |
e4350b17d767face5cf41d076617b98fc1843822 | azznggu/PythonGettingStart | /PythonGettingStart/list/list5comprehension.py | 521 | 3.890625 | 4 | # list안 for, if문 사용 가능.
a = [i for i in range(10)]
print(a)
b = list(i for i in range(10))
print(b)
#요소를 다른값과 연산 가능.
c = list(i*2 for i in range(10))
print(c)
#반복문 뒤 조건문 지정.
#range에의해 생성된 숫자 요소 조건문(짝수)인 경우에만 i로 지정, i를 리스트 요소로 리스트 생성.
d = list(i for i in range(10) if i%2== 0)
print(d)
#for,if 복수 사용 가능.
e = list(i*j for i in range(1,10)
for j in range(1,10))
print(e) |
c2f3dbd2cd86dc77bccf8a8fb6bf15e7b2daae53 | anthonyfong100/ntu-bookings | /src/utils.py | 250 | 3.5 | 4 | def is_valid_court_num(court_number: int) -> bool:
# valid court numbers are 1...6
return 1 <= court_number <= 6
def is_valid_time(start_time: int) -> bool:
# valid start time are 8...21 , 24 hour clock
return 8 <= start_time <= 21
|
97d5725d73346838e030c6e513f8e5b8da0316fd | Aimee-yjc/python_learning | /08/02/checktnt.py | 717 | 3.859375 | 4 | import re # 导入Python的re模块
pattern = r'(黑客)|(抓包)|(监听)|(Trojan)' # 模式字符串
about = '我是一名程序员,我喜欢看黑客方面的图书,想研究一下Trojan。'
match = re.search(pattern,about) # 进行模式匹配
if match == None: # 判断是否为None,为真表示匹配失败
print(about,'@ 安全!')
else:
print(about,'@ 出现了危险词汇!')
about = '我是一名程序员,我喜欢看计算机网络方面的图书,喜欢开发网站。'
match = re.match(pattern,about) # 进行模式匹配
if match == None: # 判断是否为None,为真表示匹配失败
print(about,'@ 安全!')
else:
print(about,'@ 出现了危险词汇!')
|
32b6c4aaf0a633608b996bd7a5fcda0f7db2ea07 | esantos92/aulas-praticas | /ProgramasPython/secao08/exercicio03.py | 150 | 4.15625 | 4 | vetor=[]
for i in range(0,10):
num=int(input("Digite um número: "))
vetor.append(num)
vetor.reverse()
for i in vetor:
print(i)
|
1fdd55ecdf66c1f7d6108198217e2e4b3a273fcf | abhimaprasad/Python | /Python/ObjectOrientedProgramming/DemoPrograms/student.py | 924 | 3.65625 | 4 | class student:
def __init__(self,roll,name,course,total):
self.roll=roll
self.name=name
self.course=course
self.total=total
def printstudent(self):
# print(self.roll)
print(self.name)
print(self.course)
print(self.total)
def __str__(self):
return self.name
list=[]
file=open("Student","r")
for lines in file:
line=lines.rstrip("\n").split(",")
print(line)
#['1', 'abhima', 'cs', '400']
id=line[0]
name=line[1]
course=line[2]
total=int(line[3])
obj=student(id,name,course,total)
list.append(obj)
# for obj in list:
# # print all students who have mark greater than 150
# if obj.total>150:
# print(obj)
# maximum value of total
total=[]
for obj in list:
total.append(obj.total)
# print(max(total))
maximum=max(total)
for obj in list:
if obj.total==maximum:
print(obj)
|
613fe48f962def97c979c959121a1850a18eb739 | Levintsky/topcoder | /python/leetcode/tree/429_N-ary_level.py | 1,207 | 4.03125 | 4 | """
429. N-ary Tree Level Order Traversal (Easy)
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
We should return its level order traversal:
[
[1],
[3,2,4],
[5,6]
]
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
"""
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
res = []
q1 = collections.deque()
q1.append(root)
if root is None: return []
while q1:
q2 = collections.deque()
subres = []
while q1:
n = q1.popleft()
if n is None:
continue
subres.append(n.val)
if n.children is not None:
for c in n.children:
q2.append(c)
q1 = q2
res.append(subres)
return res |
07c961c55308d04381bdd780ce617c8057eb3205 | spruce808/learning | /PythonApplication1/PythonApplication1/PythonPuzzle1.py | 1,133 | 3.90625 | 4 |
class Puzzle1Solver(object):
"""A program that prints all sequences of binary digits, such that each
digit in the sequence is a 0 or 1, and no sequence has two 1's adjacent
in the output.
"""
@classmethod
def main(cls):
num_bits = 32
max = (1 << num_bits) - 1
val = 0
while (val <= max):
is_valid = True
# Detect if we have any runs with two consecutive bits set
for bit_offset in range(0, num_bits - 1):
if 0x3 == (val >> bit_offset) & 0x3:
# two bits are set, skip the known intermediates
# - we know that the first clash will always occur when the
# least-significant bit (or bits) are zero, so we can skip
# in powers-of-two
val += 1 << bit_offset
is_valid = False
break
if is_valid:
print('Valid sequence: {:0{width}b}'.format(val, width=num_bits))
val += 1
if __name__ == "__main__":
Puzzle1Solver.main()
|
25a9d101935927eee207623fc563c7efd9ea3464 | Yaachaka/pyPractice1 | /bhch08/bhch08exrc11.py | 879 | 4.34375 | 4 | """
bhch08exrc11.py: Section 8.3 described how to use the shuffle method to create a random anagram of a string. Use the choice method to create a random anagram of a string.
"""
print('*'*80)
from random import choice
word = input('Enter a word: ')
letter_list = list(word)
l = ''
l = [choice(letter_list) for i in range(len(word))]
anagram = ''.join(l)
print(anagram)
print('*'*80)
"""PROGRAM OUTPUT
@@@@ Trial1:
*******************************************************************************
Enter a word: hello there
rheoh hhhrr
********************************************************************************
@@@@ Trial2:
********************************************************************************
Enter a word: I am not going.
t mgot gng g.o
********************************************************************************
""" |
379e45342717968aa1b37b163b0603401a298f92 | guyavrah1986/learnPython | /learnPython/classes_and_objects_9/accessSpecifiersInPython.py | 580 | 3.5625 | 4 |
class TestObj:
def __init__(self):
func_name = "TestObj::__init__ - "
print(func_name)
def __test_obj_private_function(self):
func_name = "TestObj::__test_obj_private_function - "
print("TestObj::__test_obj_private_function - ")
def example_func():
func_name = "example_func - "
print(func_name + "start")
# Although it is a private method, this way it is possible to
# invoke it wither way
myTestObj._TestObj__test_obj_private_function()
print(func_name + "end")
if __name__ == "__main__":
example_func()
|
f031d4e53b5b11b0b57a591769709e35f563c3c8 | BielMaxBR/Aulas-de-python | /AulasdePython/exercícios/ex004.py | 362 | 3.890625 | 4 | txt = input('digite algo:')
print('isso é um número?', txt.isnumeric())
print('isso é uma alfabético?', txt.isalpha())
print('isso é alfanumérico?', txt.isalnum())
print('isso é um espaço?', txt.isspace())
print('isso é apenas maiúsculo?', txt.isupper())
print('isso é apenas minúsculo?', txt.islower())
print('isso é capitalizado?', txt.istitle())
|
7815c0e169e6a29334e192d3ec3989deb5b403dc | AssiaHristova/SoftUni-Software-Engineering | /Programming Basics/nested_loops/car_number.py | 990 | 3.609375 | 4 | start_num = int(input())
end_num = int(input())
flag_1 = True
flag_2 = True
flag_3 = True
flag_4 = True
for num_1 in range(start_num, end_num + 1):
for num_2 in range(start_num, end_num + 1):
for num_3 in range(start_num, end_num + 1):
for num_4 in range(start_num, end_num + 1):
if num_1 % 2 == 0 and num_4 % 2 != 0:
flag_1 = True
else:
flag_1 = False
if num_1 % 2 != 0 and num_4 % 2 == 0:
flag_2 = True
else:
flag_2 = False
if num_1 > num_4:
flag_3 = True
else:
flag_3 = False
if (num_2 + num_3) % 2 == 0:
flag_4 = True
else:
flag_4 = False
if (flag_1 or flag_2) and flag_3 and flag_4:
print(f'{num_1}{num_2}{num_3}{num_4}', end=' ')
|
2ae0773cc4befe11e6d5163a41daa35c7bb6ccb1 | zzj0403/markdowm-summary | /python/面向对象总结/02定义与产生.py | 988 | 3.9375 | 4 | class Student:
# 学校
school = '清华大学' # 数据(属性)
name = '类中的name'
# 让对象在产生的时候 有自己的属性
def __init__(self,name,age,gender): # 形参中放 你想让对象有的而独立的属性 name,age,gender
self.name = name # self指代的就是每一次类实例化(加括号调用)产生的对象
self.age = age # 该句式 类似于往对象的空字典中 新增键值对
self.gender = gender
# 选课
def choose_course(self): # self就是一个普普通通的形参名而已 功能
print(self) # 对象来调 指代的就是对象本身
print(self.name)
print('学生选课功能')
obj = Student('jason',18,'male') # 其实类名加括号会执行类中__init__方法
"""
对象(类)获取名称空间中的属性和方法的统一句式 句点符(.)
__dict__ 查看对象所有的属性
"""
# print(obj.__dict__)
# print(obj.school)
# obj.choose_course() |
e6f987005d0c62775df81f4e25b71f50e715eb39 | Lakshanna/emiscel_training | /Thavamani/python1/default_arg.py | 63 | 3.609375 | 4 |
def add(num,n=3):
return num+n
print add(5,2)
print add(5)
|
aabc42b54fa3bdd3beaf8efecdcdbb41e4a26e07 | jtchuaco/Python-Crash-Course | /scripts/Chapter 7/cities.py | 693 | 4.28125 | 4 | # Using break to Exit a Loop
# use break statement to exit a while loop immediately without running any remaining code in the loop
# it directs the flow of your program
# use it to control which lines of codes are executed and which aren't
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
# will run forever unless it reaches a break statement
# when user enter quit, the break statement runs, causing Python to exit the loop
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go " + city.title() + "!")
# can use the break statement in any of Python's loop
|
734c435bf5b44483124ff9fa289ea80d86841078 | QuentinDuval/PythonExperiments | /graphs/NumberOfFlipsToZeroMatrix_hard.py | 1,917 | 3.65625 | 4 | """
https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/
Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.
Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.
Binary matrix is a matrix with all cells equal to 0 or 1 only.
Zero matrix is a matrix with all cells equal to 0.
"""
from collections import deque
from typing import List
class Solution:
def minFlips(self, mat: List[List[int]]) -> int:
h = len(mat)
w = len(mat[0])
def as_bits(mat: List[List[int]]) -> int:
bits = 0
for i in range(h):
for j in range(w):
if mat[i][j] == 1:
bits |= 1 << (w * i + j)
return bits
def flip(node, i, j):
pos = w * i + j
node ^= 1 << pos
if i < h - 1:
node ^= 1 << (pos + w)
if i > 0:
node ^= 1 << (pos - w)
if j < w - 1:
node ^= 1 << (pos + 1)
if j > 0:
node ^= 1 << (pos - 1)
return node
def get_neighbors(node):
for i in range(h):
for j in range(w):
yield flip(node, i, j)
start_node = as_bits(mat)
discovered = {start_node}
to_visit = deque([(start_node, 0)])
while to_visit:
node, dist = to_visit.popleft()
if node == 0:
return dist
for neigh in get_neighbors(node):
if neigh not in discovered:
discovered.add(neigh)
to_visit.append((neigh, 1 + dist))
return -1
|
434765ecdf86b0325683e59b729e2ca82d964d12 | sqlunet/builder | /semantikos/_schema.py | 1,049 | 3.546875 | 4 | #!/usr/bin/python3
import sqlite3
import sys
sql_tables_schema= """SELECT name, type FROM sqlite_schema WHERE type='table';"""
sql_indexes_schema="""SELECT name, type FROM sqlite_schema WHERE type='index';"""
sql_columns="""PRAGMA table_info('%s')"""
def collectNames(rows):
return [name for name,type in rows]
def collect(rows):
return sorted(list(zip(*rows))[1])
def collectColumns(rows):
return [(name,type) for cid,name,type,notnull,dflt_value,pk in rows]
def query(sql, consume):
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
r = consume(rows)
cursor.close()
return r
db=sys.argv[1]
connection = sqlite3.connect(db)
print("sql_tables_schema")
tables = sorted(query(sql_tables_schema, collectNames))
print(tables)
print("sql_indexes_schema")
indexes = sorted(query(sql_indexes_schema, collectNames))
print(indexes)
print("sql_table_columns")
for t in tables:
columns = query(sql_columns % t, collectColumns)
columns = ['%s %s' % (c[0],c[1]) for c in columns]
print('%s\n\t%s' % (t, columns))
|
f99b6131b967bea9c79a093c5aaa626c74911f2d | arpit04/Python-Exercism | /pig-latin/pig_latin.py | 498 | 4.0625 | 4 | vowel = ['a','e','i','o','u']
def translate(text):
if text[0:2] == 'xr' or text[0:2] == 'yt':
return text+"ay"
elif text[0] in vowel:
return text+"ay"
else:
for i in range(len(text)):
if text[i] == 'y' and i!=0:
return text[i:]+""+text[0:i]+"ay"
x = ((len(text)) - len(text)//2)
consonant = text[len(text)//2:]+""+text[0:(len(text)//2)]+"ay"
return consonant
text = input("Enter Word :")
print(translate(text)) |
11e0734856e43dea1087fed4541816be31e19422 | younguk95/kmove_python | /basic/while_test.py | 760 | 3.640625 | 4 | listdata=[]
while True:
print('''
==========리스트 데이터 관리======
1.리스트에추가 2. 리스트 데이터 수정 3. 리스트 데이터 삭제 4. 종료
''')
menu = int(input("메뉴를 선택하세요"))
if menu == 4:
break
elif menu == 1:
data=input("추가할 데이터를 입력하세요")
listdata.append(data)
print(listdata)
elif menu == 2:
data=input("추가할 데이터를 수정하세요")
data=[len-1]
data[2] = 4
listdata.append(data)
print(listdata)
elif menu == 3:
data=input("추가할 데이터를 삭제하세요")
data=[len-1]
del data[2]
listdata.append(data)
print(listdata) |
93049807f501effa6ac0b0e2fa1fc600a3fdf800 | wangpeibao/leetcode-python | /easy/easy1608.py | 1,828 | 3.9375 | 4 | """
1608. 特殊数组的特征值
给你一个非负整数数组 nums 。如果存在一个数 x ,使得 nums 中恰好有 x 个元素 大于或者等于 x ,
那么就称 nums 是一个 特殊数组 ,而 x 是该数组的 特征值 。
注意: x 不必 是 nums 的中的元素。
如果数组 nums 是一个 特殊数组 ,请返回它的特征值 x 。否则,返回 -1 。可以证明的是,如果 nums 是特殊数组,那么其特征值 x 是 唯一的 。
示例 1:
输入:nums = [3,5]
输出:2
解释:有 2 个元素(3 和 5)大于或等于 2 。
示例 2:
输入:nums = [0,0]
输出:-1
解释:没有满足题目要求的特殊数组,故而也不存在特征值 x 。
如果 x = 0,应该有 0 个元素 >= x,但实际有 2 个。
如果 x = 1,应该有 1 个元素 >= x,但实际有 0 个。
如果 x = 2,应该有 2 个元素 >= x,但实际有 0 个。
x 不能取更大的值,因为 nums 中只有两个元素。
示例 3:
输入:nums = [0,4,3,0,4]
输出:3
解释:有 3 个元素大于或等于 3 。
示例 4:
输入:nums = [3,6,7,7,0]
输出:-1
提示:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
"""
from typing import List
class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
num_index = 0
index = 1
while index <= len(nums) - num_index and num_index < len(nums):
if index <= nums[num_index]:
if index == len(nums) - num_index:
return index
index += 1
else:
num_index += 1
return -1
so = Solution()
print(so.specialArray(nums=[3, 5]) == 2)
print(so.specialArray(nums=[0, 0]) == -1)
print(so.specialArray(nums=[0, 4, 3, 0, 4]) == 3)
print(so.specialArray(nums=[3, 6, 7, 7, 0]) == -1)
|
79f720fa9e11f78a998b817cca43241c64dc29ab | ANkurNagila/My-Code | /Code48.py | 391 | 3.75 | 4 | t=input()
try:
t=int(t)
print("Invalid Input")
except:
res=""
i=True
for x in t:
if x=="G":
res+="C"
elif x=="C":
res+="G"
elif x=="T":
res+="A"
elif x=="A":
res+="U"
else:
print("Invalid Input")
i=False
break
if i==True:
print(res)
|
e08d7c16dda94331b6062b48fb6e0fb50a7dbac3 | jdacode/Blockchain-Electronic-Voting-System | /network.py | 398 | 3.609375 | 4 | from ipaddress import ip_address
class Network:
def __init__(self, ip):
self.ip = ip
@staticmethod
def is_a_valid_ip(ip):
try:
ip_add, port = ip.split(":")
if int(port) < 0 or ' ' in port: return False
if ip_add == 'localhost' or ip_address(ip_add): return True
except ValueError:
return False
|
7ad3596c8ab78cb6c8966b7a2d56b3d0852521fc | santosclaudinei/Python_Geek_University | /sec05_ex10.py | 280 | 3.546875 | 4 | sexo = input("Digite seu sexo: ")
altura = input("Digite sua altura: ")
if (sexo in "MmFF"):
if (sexo in "fF"):
print(f"O seu IMC é {62.1 * float(altura) - 47}")
else:
print(f"O seu IMC é {72.7 * float(altura) - 58}")
else:
print("Dados invalidos.") |
fd602eea2b7cbd8e5e053a8fa78805e23c6eb5a6 | nithen-ac/Algorithm_Templates | /data_structure/trie_tree.py | 1,474 | 3.875 | 4 | # The trie is a tree of nodes which supports Find and Insert operations. It is also called prefix tree.
# trie tree is built to help match the whole words list in one batch.
# Scenario: autocomplete, spell checker, IP routing, T9 predictive text, solving word games.
# just basic version, improvement like: double-array trie, tail compressed
#
# words list has k words, the max word len is m
# Time: O(m) for match once
# Space: O(mk)
# dict version
def trie_tree_template(word_to_match: str, words_to_build: 'List[str]'):
# create trie tree
trie = {}
# or use autovivification
# trie_tree = lambda: defaultdict(trie_tree)
# def trie_tree(): return defaultdict(trie_tree)
# trie = trie_tree()
# add words recursively
for w in words_to_build:
cur = trie
for c in w:
cur = cur.setdefault(c, {})
# end flag, record the whole words, or other data as you need
cur['#'] = w
# traverse with trie tree
cur, res = trie, []
for c in word_to_match:
if c not in cur:
# match failed
break
# prefix matched
cur = cur[c]
# the whole word matched
if "#" in cur:
res.append(cur['#'])
ALPHABET_SIZE = 26
# object-oriented array version
class TrieNode:
def __init__(self):
self.children = [None] * ALPHABET_SIZE
# is_end_of_word is True if node represent the end of the word
self.is_end_of_word = False
|
01cd0d465b67cbd296cff787a672eb7a7dfc5b84 | moreirafelipe/univesp-alg-progamacao | /S1/V2 - Arquivos/texto 2/hello.py | 736 | 3.65625 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> line1 = 'Olá, desenvolvedor Python...'
>>> line2 = 'Bem vindo ao mundo python!'
>>> print(line1)
Olá, desenvolvedor Python...
>>> print(line1)
Olá, desenvolvedor Python...
>>> print(line1 + '\n' + line2)
Olá, desenvolvedor Python...
Bem vindo ao mundo python!
>>>
================================ RESTART: Shell ================================
>>> print(line1)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(line1)
NameError: name 'line1' is not defined
>>> x = input('Digite seu nome')
Digite seu nome5
>>> x
'5'
>>> |
f47b2453c587a09f5370cdf11c801d9eebaf07aa | Sewoong-Lee/python-TIL | /p210329_01_print.py | 467 | 3.96875 | 4 |
#주석 : 프로그램의 설명을 적는다. (앞에 # 적으면 주석됨)(주석 할거 위 아래에""",''' 쓰면 전체주석)
#print함수
'''
print(10+30)
print(15+1)
print(13-4)
print(8/9)
print(45*7)
'''
"""
#문자는 "" 로 적음
#이스케이프문자 : \n 줄바꿈
#매개변수, 인자, 인수
print("헬로", end=",")
print('ㅋ')
print('"ㅋㅋㅋ"ㅋㅋ"ㅋㅋㅋㅋ"')
print('z','z',11)
print('zz'+'zz')
print('zz + 123')
print('z\nz\n' *3)
|
9e42b6803ef8ea0fdb880066c62743de5908e36e | alikhalilli/Algorithms | /.z/Arrays/Rotation/MultipleRotationsV2.py | 498 | 4.25 | 4 | """
@github: github.com/alikhalilli
Time Complexity: O(n)
Space Complexity: O(1)
arr = [1, 2, 3, 4, 5, 6]
k1 = 1, [2, 3, 4, 5, 6, 1]
k2 = 3, [4, 5, 6, 1, 2, 3]
k3 = 4, [5, 6, 1, 2, 3, 4]
"""
def leftRotate(arr, k):
n = len(arr)
start = k % n
for i in range(start, start+n):
print(arr[i % n], end=" ")
def rightRotate(arr, k):
n = len(arr)
start = (n-k) % n
for i in range(start, start+n):
print(arr[i % n], end=" ")
leftRotate([1, 2, 3, 4, 5, 6], 2)
|
b86eb96ffba8d5fd6a0deb0528ba50ab2551f2a7 | neilsambhu/CAP6415-project | /PatternTheory_WACV_Original/PatternTheory_WACV_Original/SupportBond.py | 2,840 | 3.6875 | 4 | import math as math
class SupportBond:
'Defines characteristics for bond type - Support - for a generator'
#Constructor for initializing an instance of a Support bond
def __init__(self, bondID, bondName, bondDir, currGenID):
self.type = "Support" #Bond Type
self.compatible = {} #Dictionary of compatible generators and compatability score
self.name = bondName #Bond Name
self.ID = bondID #Bond ID
self.energy = 0 #Energy of bond. 0 if not active
self.status = False #Status of bond. False if inactive, True if active
self.currGen = currGenID #ID of the generator to which current bond belongs to
# Bond Direction - IN(0) or OUT (1)
if(bondDir == "IN"):
self.direction = 0
elif(bondDir == "OUT"):
self.direction = 1;
else:
raise ValueError('Bond Type must be either IN or OUT')
self.compBondID = None #Complementary bond ID. i.e. ID of the bond on the other side of connection
self.compGenID = None #Complementary generator ID. i.e. ID of the generator on the other side of connection
# Function to get current Bond status. Returns the bond ID, Type and status as a tuple
def getBondStatus(self):
print "-------------------------Bond Status -------------------------------------------"
print self.ID, self.type, self.status, self.compBondID, self.compGenID, self.currGen
# Function to check bond compatability
def checkCompatible(self, bond):
return ((bond.type == self.type) and (bool(bond.direction) ^ bool(self.direction)) and (bool(bond.name == self.name)) and not (bond.status or self.status))
# return true only if bonds are complementary (IN vs OUT) -- got using XOR
# and compatible based on type -- if candidate bond type is same as self bond type
# Bond Acceptor Function. Return energy:
def calcEnergy(self, candidate, k=2.):
# print "calcEnergy"
score = self.compatible.get(candidate, None)
energy = None
if score is not None:
energy = math.tanh(-k * score)
return energy
#Function to reset Bond to default:
def resetBond(self):
self.energy = 0
self.status = False
t1 = self.compBondID
self.compBondID = None
t2 = self.compGenID
self.compGenID = None
# print t1, t2
return t1, t2
# Function to set current Bond to be active
def formBond(self, bond, candLabel, candGenID):
# print "formBond"
isCompatabile = self.checkCompatible(bond)
if isCompatabile:
t = self.calcEnergy(candLabel)
if t == None:
isCompatabile = False
return (isCompatabile, bond)
self.energy = t
self.compBondID = bond.ID
self.status = True
self.compGenID = candGenID
bond.status = True
bond.energy = self.energy
bond.compBondID = self.ID
bond.compGenID = self.currGen
# print "Form bond -------------"
# print bond.ID, self.ID, isCompatabile, bond.energy, self.currGen, candGenID
return (isCompatabile, bond) |
1e2a78fe1e37555e935d79597d8f2e92e5b29d1b | seObando19/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,907 | 3.75 | 4 | #!/usr/bin/python3
"""
Define Square class.
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""
"""
def __init__(self, size, x=0, y=0, id=None):
"""
Initialize square class
Arguments:
size (int): value to square side.
x (int): integer number.Defaults to 0.
y (int): integer numer. Defaults to 0.
id (int): integer number.Defaults to None.
"""
super().__init__(size, size, x, y, id)
def __str__(self):
"""
Return descriptor of Rectangle
[Square] (<id>) <x>/<y> - <size>
"""
respond = "[Square] ({}) {}/{} - {}"
return respond.format(self.id, self.x,
self.y, self.width)
@property
def size(self):
"""
Method get for size atribute
"""
return self.width
@size.setter
def size(self, value):
"""
Method set for size atribute
Arguments:
value (int): value integer
"""
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""
That assigns an argument to each attribute
Arguments:
args()
kwargs()
"""
attr = ['id', 'size', 'x', 'y']
if 0 < len(args) <= 4:
for i in range(len(args)):
super().__setattr__(attr[i], args[i])
else:
for j in kwargs:
super().__setattr__(j, kwargs[j])
def to_dictionary(self):
"""
Method that returns the dictionary
representation of a Square
"""
myDict = {'id': self.id,
'size': self.width,
'x': self.x,
'y': self.y}
return myDict
|
d4e23f1fa4ca386f15145daad32e68a9f4085ed2 | liyi-1989/neu_ml | /code/data/sample_helix.py | 2,453 | 3.84375 | 4 | import pdb
import numpy as np
def sample_helix(n_points, z_range, var=0.0, frequency=1.0, x_amplitude=1.0,
y_amplitude=1.0, x_phase=0.0, y_phase=0.0, z_locs=None):
"""Randomly generate samples from a helix function.
This function is used to generate random noisy samples from a helix.
The user can specify the parameters of the helix, the number of desired
points, the range over which the samples are drawn, and
the amount of noise added to the x- and y-locations.
Parameters
----------
n_points : int
Number of desired data points
z_range : array, shape ( 2 )
This is a 2D vector indicating the minimum and maximum of
the input range of the 'n_points'. The z-locations will be randomly
(uniformly) sampled within this range, and the x- and y- locations
will be computed at those input locations
var : float
The x- and y-locations will be corrupted with Gaussian noise with the
specified variance
frequency : float, optional
The frequency governing the sine and cosine terms in the helix
equation. This term controls the "tightness" of the helix
x_amplitude : float, optional
The helix amplitude in the x-direction
y_amplitude : float, optional
The helix amplitude in the y-direction
x_phase : float, optional
The phase of the cosine in the x-direction
y_phase : float, optional
The phase of the cosine in the y-direction
z_locs : array, shape ( n_instances ), optional
A specific list of z-locations at which to evaluate the helix. If
specified, the input variables 'n_points' and 'z_range' will be
ignored.
Returns
-------
data : array, shape ( n_points, 3 )
The first column corresponds to the x-axis, the second the y-axis, and
the third the z-axis
"""
# First generate the z location values. They should be distributed
# randomly and uniformly across the range specified
if z_locs is None:
z_locs = (z_range[1] - z_range[0])*np.random.rand(n_points) + z_range[0]
x_locs = x_amplitude*np.cos(frequency*z_locs + x_phase) + \
np.sqrt(var)*np.random.randn(n_points)
y_locs = y_amplitude*np.sin(frequency*z_locs + y_phase) + \
np.sqrt(var)*np.random.randn(n_points)
data = np.array([x_locs, y_locs, z_locs])
return data.T
|
06fc9b2e4eacb04fc706a0e2c7acb55a7d42c731 | leexingmunjolene/python2013lab4 | /compress.py | 931 | 3.625 | 4 | # compress.py
# Devise an effective and efficient lossless compression algorithm
# for compressing large textual documents.
# @, # , &, *
try:
infile = open('flintstones.txt','r')
outfile = open('cflintstones.txt','w')
char = 0
consec = 1
for line in infile:
while char+1 != len(line):
if line[char] == line[char+1]:
consec += 1
char += 1
else:
if consec == 1:
outfile.write(line[char])
char +=1
else:
outfile.write(line[char]+str(consec))
char += 1
consec = 1
char = 0
outfile.write(line[char]+str(consec)+'\n')
## words = line.split()
## for word in words:
infile.close()
outfile.close()
except IOError:
print("Error in reading fintstones.txt.")
|
4392106f06cf535b95be3f391b0b2dc30c501b6e | AdamRhoades95/Python-SQL | /Programming/Python/Test_Ex/Read_Write_File/write.py | 770 | 4.25 | 4 | # this will just write a file for the first time
# this will get path and file name
# this will get text from user
# this will continue until text = !1-
# ask user for path and file
print("type \"default\"\nor type out a path followed by the file")
file_Path = raw_input("file path: ")
if file_Path.lower() == "default":
file_Name = raw_input("file name: ")
file_Path = ("/root/Programming/Python/Test_Ex/Read_Write_File/Written_Files/" + file_Name)
# open file
text=""
try:
file = open(file_Path, "w+")
line = 1
# loop for line of text till text = !1-
while text != "!1-":
text = raw_input("Enter line "+str(line)+ ": ")
if text != "!1-":
file.write(text+"\n")
line+=1
# close file
file.close()
except:
print("sorry, the path does not exist")
|
0fcf50bc574c6c25c2c84ccfd1dfd39ac56f5c03 | FRANKLIU90/Python | /18 April/3-24-18_python class toolkit.py | 817 | 3.953125 | 4 | import math
class Circle:
print('class circle')
def __init__(self, radius):
self.radius = radius
print('init circle')
def perimeter(self):
return 4 * self.radius
def area(self):
a = self.__perimeter()
s = (a / 4)**2
return s
__perimeter = perimeter
def pint(self):
print('jiji')
_pint = pint
class Tire(Circle):
def perimeter(self):
return Circle.perimeter(self) * 2
# __perimeter = perimeter
c_1 = Circle(2)
c_2 = Circle(4)
# c_1._pint()
# print(dir(c_1))
# print(dir(Circle))
# print('+++++')
# print(dir(Tire))
t_1 = Tire(3)
# print(t_1.perimeter())
# print(t_1._Tire__perimeter())
# print(t_1.area())
print(vars(c_1))
d = {'radius': 2}
print({b: a for a, b in d.items()})
# print(class(t1).__name__)
|
0206eb5f6b2b5a6af2e116f2a03b2c9ca86769df | OddExtension5/ProgrammingBitcoin_from_scratch | /NumberTheory/lcm.py | 1,353 | 4 | 4 | #lcm(a,b) of integers a & b ( both different from zero) is the smallest positive integer that is divisible by both a&b
# we know lcm(a,b) * gcd(a,b) = a*b
def lowest_common_multiple(a, b):
"""
>>> lowest_common_multiple(3,2)
6
>>> lowest_common_multiple(12, 80)
240
Note: The Least Common Multiple (LCM), lowest common multiple, or smallest common multiple of two integers a and b,
usually denoted by LCM(a, b), is the smallest positive integer that is divisible by both a and b.
"""
assert a > 0 and b > 0
return (a * b) / greatest_common_divisor(a, b)
# Euclid's Lemma : d divides a and b, if and only if d divides a-b and b
# Euclid's Algorithm
def greatest_common_divisor(a, b):
"""
>>> greatest_common_divisor(7,5)
1
Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime
if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1.
>>> greatest_common_divisor(121, 11)
11
"""
if a < b:
a, b = b, a
while a % b != 0:
a, b = b, a % b
return b
# import testmod for testing our function
from doctest import testmod
if __name__ == '__main__':
testmod(name='lcm', verbose=True)
testmod(name='greatest_common_divisor', verbose=True)
|
997f086977310ad033bc1358ee3b529384cfb36b | TodimuJ/Python | /starGenerator.py | 196 | 4.125 | 4 | number = int(input("What is n: "))
for i in range(number):
for j in range(number):
if i == j or j == (number-i-1):
print("*")
else:
print(" ") |
4766de6b99247d61f8be5f477a94db9708b46d4a | KARTHICKMUTHUSAMY/beginer | /pro19.py | 159 | 3.609375 | 4 | n1=int(input())
arr1=list()
for x in range(n1):
arr2=list(map(int,input().split()))
arr1=arr1+arr2
arr1=sorted(arr1)
for s in arr1:
print(s,end=" ")
|
d35b0b7f8a3f1617f3f80d3af5ebafa6b44216c8 | daringli/PERFECT_utils | /new_plot/sort_species_list.py | 1,060 | 4.15625 | 4 | def sort_species_list(species_list,first=["D","He"],last=["e"]):
#sorts list so that the first element in "first" that is in species_list will be first, then the second that exists, etc.
#elements between first and last have no prefered order
output_list=[]
if any([f in last for f in first]):
print "sort_species_list: warning: recieved directive to both place element first and last. List will be extended to place it both first and last."
for f in first:
if f in species_list:
output_list.append(f)
for s in species_list:
if (s not in last) and (s not in first):
output_list.append(s)
#first in last will be last, since list is reversed
for l in last[::-1]:
if l in species_list:
output_list.append(l)
return output_list
if __name__=="__main__":
a=["1","2","3","4","5","6"]
f=["4","3"]
l=["2","1"]
print sort_species_list(a,f,l)
print sort_species_list(["e","D","He","N","C","W"])
print sort_species_list(["e","He","N"])
|
c1a75896b59838f26755a0681a4851bc566091d1 | huboa/xuexi | /oldboy-python18/day02-列表-字典/00-day02/day2/dd.py | 238 | 3.765625 | 4 | #coding:utf-8
x=u'你瞅啥' #python2的字符串就是bytes
# # print type(x) is bytes
print(x)
# unicode--------->encode('utf-8')----->bytes
#bytes----------decode('gbk')------------>unicode
# x=u'你瞅啥'
# print x
# print type(x) |
94053e49679a026aaaca81ca52e70248159bb024 | aksbaih/portfolio | /Python/Neocis Coding Challenge/part2opt.py | 2,215 | 3.5 | 4 | '''
This is an optimized approach to the problem described in part2.py. It uses
scipy's minimization function to minimize a loss function with variables x, y, r:
the x and y coordinates of the center of the circle and its radius respectively. The
loss is the sum of the distance squared of each toggled point from the circumference
of the ring. A starting position is determined using the algorithm from part2.py.
Created by Akram Sbaih on Oct 26, 2019 for Neocis
'''
from interface import interface
import numpy as np
from scipy.spatial import distance
import scipy.optimize as optimize
# This function is called when the user hits the 'generate/reset' button and
# executes the optimized version of the algorithm. It draws two circles:
# a blue one for the result of the basic algorithm, and a red one for the optimized.
def find_best_circle(gui):
if(np.count_nonzero(gui.toggles) < 2): # reset because there are no enough points
gui.clean_screen()
gui.paint_balls()
gui.paint_generate_button()
return
# Implementation of the basic algorithm. Check part2.py for details.
center = (int(gui.xs[gui.toggles].mean()), int(gui.ys[gui.toggles].mean()))
mean_distance = np.sqrt((gui.xs[gui.toggles] - center[0]) ** 2 + (gui.ys[gui.toggles] - center[1]) ** 2).mean()
gui.draw_ring(center, int(mean_distance), 'blue', width=2)
# This loss function is the sum of the squared distances of toggled points from the
# circumference of the circle centered at params[0], params[1] and radius params[2]
def loss(params):
x, y, r = params
distances = np.sqrt((gui.xs[gui.toggles] - x) ** 2 + (gui.ys[gui.toggles] - y) ** 2)
distances = (distances - r) ** 2
return distances.sum()
# use the scipy.optimize utility to find the optimal x, y, r with least loss
result = optimize.minimize(loss, [center[0], center[1], mean_distance])
if result.success: # optimization succeeded; draw a red circle of the result
gui.draw_ring((int(result.x[0]), int(result.x[1])), int(result.x[2]), 'red', width=2)
else:
print("Optimal solution not found")
# toggle all points off
gui.toggles ^= gui.toggles
# make an instance of a GUI and set its behavior to 'generate' mood
GUI = interface(generate= find_best_circle) |
1ad96d1660218814c5a52b522d161f211d75d113 | ids0/ATBSWP | /Chapter_06/tablePrinter.py | 1,328 | 4.125 | 4 | tableData =[['apples','oranges','cherries','banana'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
def printTable(table):
rows = len(table[0]) # Number of rows to print
col = len(table) # Number of columns to print
colWith = [0] * len(table) # A list of the same number of items as columns to print, will be used to save the longest strin in each column
for c in range(col): # Iterates in every column to find the longes string
longest = 0 # Every time the loop adds 1 it resets the count
for r in range(rows): # Iterates every strig in every list, it also can be done with 'item in talbe[c]'
if len(table[c][r]) > longest:
longest = len(table[c][r])
colWith[c] = longest # Saves the length of the longest string in order
for r in range(rows): # Same principle as in the printT first the rows act as columns
if r != 0: # First line without new line
print()
for c in range(col):
print(table[c][r].rjust(colWith[c]),end=' ') # [c][r] is a must, becouse table has only 'c' items and table[c] has 'r'items
printTable(tableData)
input()
|
1f58fae86be0e38796d7befa44dee320e8b105e5 | vineetkumarsharma17/MyPythonCodes | /String/Check_substring.py | 190 | 4.21875 | 4 | str=input("Enter a string:")
sub=input("Enter sub string:")
if sub not in str:
print("not")
else:print("yes")
#using find method
if(str.find(sub)==-1):
print("not")
else:print("yes") |
6426eb703f777100c005013a67c7c36d1248d8c8 | callmezzzhy/python-creeper | /算法和数据结构/去重.py | 171 | 3.84375 | 4 | l=[2,2,3,1,2,74,5,6,6,7,8,9,9]
l1=list(set(l))
l1.sort(key=l.index)
print(l1)
l2={}.fromkeys(l).keys()
print(l2)
l3=[]
[l3.append(x) for x in l if x not in l3]
print(l3)
|
179fb80953e5f9aa806abc59f532742aee9cb92f | rohit20001221/leetcode | /stacks_que/bfs_tree.py | 787 | 3.890625 | 4 | from collections import deque as dque
class Node:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def BFSTree(root):
ans = []
if root is None:
return ans
queue = dque([root])
while queue:
n = len(queue)
temp = []
for i in range(n):
el = queue.popleft()
temp.append(el.value)
if el.right:
queue.append(el.right)
if el.left:
queue.append(el.left)
ans.append(temp)
temp = []
return ans
root = Node(10)
root.right = Node(20)
root.left = Node(5)
root.left.left = Node(8)
root.right.left = Node(3)
root.right.right = Node(7)
print(BFSTree(root)) |
1bdfbc535b84f020c071ce98c6c96ee347b89a0c | rootid23/fft-py | /dp-top20/edit-distance-dp-5.py | 1,109 | 3.828125 | 4 |
# LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
# LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
# Input: str1 = "geek", str2 = "gesek"
# Output: 1
# We can convert str1 into str2 by inserting a 's'.
# Input: str1 = "cat", str2 = "cut"
# Output: 1
# We can convert str1 into str2 by replacing 'a' with 'u'.
# Input: str1 = "sunday", str2 = "saturday"
# Output: 3
# Last three and first characters are same. We basically
# need to convert "un" to "atur". This can be done using
# below three operations.
# Replace 'n' with 'r', insert t, insert a
def edit_distance(a, b) :
m, n = map(len, [a, b])
if(m == 0) : return n
if(n == 0) : return m
if(a[0] == b[0]) :
return edit_distance(a[1:], b[1:])
#3 cases 1. insert 2. delete 3. replace
return 1 + min(edit_distance(a, b[1:]), edit_distance(a[1:],b), edit_distance(a[1:], b[1:]))
# print(edit_distance ("cat", "cut"))
assert(edit_distance ("geek", "gesek") == 1)
assert(edit_distance ("cat", "cut") == 1 )
assert(edit_distance ("sunday", "saturday") == 3 )
|
b04593a85d772d10a96470e714a2799e41db60b4 | andrei-kozel/100daysOfCode | /python/day002/exercise1.py | 312 | 3.90625 | 4 | # 🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
# 🚨 Don't change the code above 👆
####################################
#Write your code below this line 👇
num_one = int(two_digit_number[0])
num_two = int(two_digit_number[1])
print(num_one + num_two) |
2925e3f7c1711de434805d2976331fa02ac61248 | vidh2000/Aurora-Borealis-Simulation | /vector.py | 5,677 | 3.875 | 4 | import random
import math
import numpy as np
# Get pi
PI = 3.141592653589793
class Vector:
# If two arguaments are given, set z = 0
def __init__(self, *args):
if len(args) > 3 or len(args) < 2:
raise ValueError("Must pass 2 or 3 arguments but {len(args)} were given")
self.x = args[0]
self.y = args[1]
self.z = 0 if len(args) == 2 else args[2]
# If 2 argumanets are given, set z = 0
def fromPolar(*args):
if len(args) > 3 or len(args) < 2:
raise ValueError("Must pass 2 or 3 arguments but {len(args)} were given")
if len(args) == 2:
x = args[0] * math.cos(args[1])
y = args[0] * math.sin(args[1])
z = 0
else:
x = args[0] * math.cos(args[1]) * math.sin(args[2])
y = args[0] * math.sin(args[1]) * math.sin(args[2])
z = args[0] * math.cos(args[2])
return Vector(x, y, z)
# Create a unit vector in a random direction w/ z = 0
def random2D():
return Vector.fromPolar(1, random.random() * 2 * PI)
# Create a 3d unit vector in a random direction
def random3D():
return Vector.fromPolar(1, random.random() * 2 * PI, random.random() * PI)
# Turn vector into printable form
def toString(self):
return f"Vector({self.x}, {self.y}, {self.z})"
# Turn vector into list (ignore z component)
def toList2D(self):
return [self.x, self.y]
# Turn vector into a list (include z component)
def toList3D(self):
return [self.x, self.y, self.z]
# Like copy.deepcopy, make a non-related copy of vector
def copyVector(self):
return Vector(self.x, self.y, self.z)
# Check if two vectors are the same
def equals(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z
# Round each entry of vector to int
def roundVector(self):
return Vector(round(self.x), round(self.y), round(self.z))
# Set the lowest and highest magnitudes
def constrainVector(self, lower, upper):
prev_mag = self.getMagnitude()
new_mag = prev_mag
if prev_mag < lower:
new_mag = lower
elif upper != "infty":
if prev_mag > upper:
new_mag = upper
return self.setMagnitude(new_mag)
# Use * sign
# If Vector * Vector => dot product
# If Vector * scalar => scalar product
# *** If scalar * Vector => Unsupported operant type ***
def __mul__(self, other):
if type(other) == Vector:
return self.x * other.x + self.y * other.y + self.z * other.z
else:
x = self.x * other
y = self.y * other
z = self.z * other
return Vector(x, y, z)
# Use + sing
# Adds two vectors
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
# Use - sign
# Subtracts two vectors
def __sub__(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
# Use **
# Cross product of two Vectors
def __pow__(this, other):
return Vector(this.y * other.z - this.z * other.y, this.z * other.x - this.x * other.z, this.x * other.y - this.y * other.x)
# Get magnitude of a Vector
def getMagnitude(self):
return (self.x**2 + self.y**2 + self.z**2)**0.5
# Set magnitude of a Vector
def setMagnitude(self, new_mag):
prev = self.toPolar()
return Vector.fromPolar(new_mag, prev[1], prev[2])
# Set magnitude to 1
def normalize(self):
return self.setMagnitude(1)
# Calculate the distance between two position Vectors
def dist(self, other):
return (self - other).getMagnitude()
# Turn a Vector in cartesian coordinates to spherical polar
def toPolar(self):
r = self.getMagnitude()
phi = math.atan2(self.y, self.x)
theta = math.atan2((self.x**2 + self.y**2)**0.5, self.z)
return (r, phi, theta)
# Turn a Vector in cartesian coordinates to cylindrical
def toCylindrical(self):
rho = (self.x**2 + self.y**2)**0.5
phi = math.atan2(self.y, self.x)
return (rho, phi, self.z)
#
def rotation_matrix_3d(axis, theta):
rot_mat = [[math.cos(theta) + axis.x**2 * (1 - math.cos(theta)), axis.x * axis.y * (1 - math.cos(theta)) - axis.z * math.sin(theta), axis.x * axis.z * (1 - math.cos(theta)) + axis.y * math.sin(theta)],
[axis.y * axis.x * (1 - math.cos(theta)) + axis.z * math.sin(theta), math.cos(theta) + axis.y**2 * (1 - math.cos(theta)), axis.y * axis.z * (1 - math.cos(theta)) - axis.x * math.sin(theta)],
[axis.z * axis.x * (1 - math.cos(theta)) - axis.y * math.sin(theta), axis.z * axis.y * (1 - math.cos(theta)) + axis.x * math.sin(theta), math.cos(theta) + axis.z**2 * (1 - math.cos(theta))]]
return rot_mat
# Rotate a Vector an angle theta (radians) (float) about an axis (Vector)
# IMPORTANT: axis must be normalized
# Example: V = Ihat
# U = V.rotateAboutAxis(Khat, PI / 2)
# => U = Jhat
def rotateAboutAxis(self, axis, theta):
rot_mat = Vector.rotation_matrix_3d(axis, theta)
new = np.matmul(rot_mat, self.toList3D())
return Vector(new[0], new[1], new[2])
# Define the unit Vectors for simplicity
# Exmaple:
# from vector import *
# print(Ihat.toString())
# => Vector(1, 0, 0)
Ihat = Vector(1, 0, 0)
Jhat = Vector(0, 1, 0)
Khat = Vector(0, 0, 1)
|
740ddc3126b371eea60d78f47de6aa126e05ff32 | ffismine/leetcode_github | /普通分类/tag分类_贪心算法/55_跳跃游戏.py | 1,731 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# Author : Zhang Xie
# Date : 2020/3/18 0:11
"""
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4] 输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4] 输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
"""
'''
思考:重点在于 最多可跳跃nums[i]
例如[2 3 1 1 4]
第0位置可以跳跃到第1或者第2
第1位置可以2 3 4
第2位置可以3
无法选择
因为可以跳的最远的位置之前的所有位置都可以到达
所以只需要当前位置能够达到,并且当前位置+跳数>最远位置,就可以更新最远位置
最后只需要比较最远位置和数组长度就可以了
'''
class Solution:
def canJump(self, nums) -> bool:
len_nums = len(nums)
index = []
for i in range(len(nums)):
index.append(i + nums[i])
jump_index = 0
max_jump = index[0]
# 只需要小于整体长度 并且 当前位置能够达到
while jump_index < len_nums and jump_index <= max_jump:
# 当前位置+跳数>最远位置,更新最远位置
if index[jump_index] > max_jump:
max_jump = index[jump_index]
jump_index += 1
if jump_index == len_nums:
return True
return False
a = Solution().canJump([3,2,1,0,4])
print(a)
|
bd08145d8486b886360f3df5a2614ea5cd67265f | BohdanVey/Tic_tac_toe_game | /game.py | 1,286 | 3.984375 | 4 | """
The main module to play game
"""
from board import Board
from btree import BinaryTree
def make_move(board):
"""
Make move
:return: None
"""
board.print_board()
if board.move == Board.player:
while True:
pos_x, pos_y = [int(x) for x in input("Enter move coordinate separated"
" by spaces").split()]
if 1 <= pos_x <= 3 and 1 <= pos_y <= 3:
pos_x -= 1
pos_y -= 1
if board.board[pos_x][pos_y] == ' ':
board.board[pos_x][pos_y] = Board.player
break
else:
print("This field isn't empty\n"
"Choose another one")
else:
print("This coordinates does not exist\n"
"print coordinates in range from 1 to 3")
board.move = Board.computer
else:
pos_x, pos_y, _, _ = BinaryTree(board).get_best_move(Board.computer)
board.board[pos_x][pos_y] = Board.computer
board.move = Board.player
if not board.status():
make_move(board)
else:
board.print_board()
if __name__ == '__main__':
make_move(Board([[' '] * 3 for x in range(3)]))
|
c02288ed11075c655ff68070ddeec2cebccd2b3d | norbertbago/codecademy | /learn_python_3/functional_programming.py | 636 | 3.5625 | 4 | from six.moves import reduce
list_1 = range(9)
list_2 = ["Hi", "Hello", "Cao", "Ahoj", "Cau", "Hola", "Halo"]
#map function
print(list(map(len, list_2)))
print(list(map(lambda x: (x, -x), list_1)))
print(list(map(lambda two: two+"hi", list_2)))
print(list(map(lambda square: square**2, list_1)))
#filter funciton
print(list(filter(lambda odd: odd % 2 != 0, list_1)))
print(list(filter(lambda even: even % 2 == 0, list_1)))
#reduce function
def reduce_sum(a, b):
return a + b
def product(a,b):
return a * b
print(reduce(reduce_sum, list_1))
print(reduce(product, range(1,3)))
print(reduce(lambda x,y: x+y, list_1))
|
14537db9558216bc013dd422d9a6d9bf4db6a904 | chadonet-65/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,008 | 3.609375 | 4 | #!/usr/bin/python3
def matrix_divided(matrix, div):
errorMessage = "matrix must be a matrix (list of lists) of integers/floats"
if not matrix:
raise TypeError(errorMessage)
if not isinstance(matrix, list):
raise TypeError(errorMessage)
for lists in matrix:
if not isinstance(lists, list):
raise TypeError(errorMessage)
for item in lists:
if not isinstance(item, int) and not isinstance(item, float):
raise TypeError(errorMessage)
for lists in matrix:
if len(lists) == 0:
raise TypeError(errorMessage)
if not isinstance(div, int) and not isinstance(div, float):
raise TypeError("div must be a number")
if not all(len(lists) == len(matrix[0]) for lists in matrix):
raise TypeError("Each row of the matrix must have the same size")
if div == 0:
raise ZeroDivisionError("division by zero")
return [[round(item / div, 2) for item in lists] for lists in matrix]
|
13915cad41fa1d4d26ff12f9d2f087b46d1ac96f | sysnad/LearnPythonTheHardWay | /ex6.py | 1,192 | 4.46875 | 4 |
#this line explains how many types of of people there are by using python format d which
#is meant to denote decimal integers
x = "There are %d types of people." % 10
#binary is a string representing the word binary so we're allow to charcterise through
#%s format
binary = "binary"
#since we are not able to call a variable don't we use spacing as do not which represents
#the word don't
do_not = "don't"
#y is the punch line of the joke meaning we're talking about only two types of people when we
#originally claimed 10 people
y = "Those who know %s and those who %s." % (binary, do_not)
#we would now print the joke
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
#here we have a boolean variable for the hilarity of the joke
hilarious = False
#here we observe that we left a raw data format opened to make use in our future print of the joke evaluation.
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of ..."
e = "a string with a right side."
#this would sum up the strings w and e allowing to make sense of a joke when combined.
print w + e
|
9251f7e1e974babc0f4f5dd002de343c89bff81f | karthikaDR/AlgorithmsPrep2 | /Matrix/WordSearch.py | 1,296 | 3.984375 | 4 | def checkword(board, row,column, string):
if len(string) == 0:
word = 'Found'
return word
#Increment/Decrement the row and column
dfs = [(0,1), (0,-1), (1,0),(-1,0)]
if (row >= len(board) or row < 0 or column >= len(board[0]) or column < 0 or board[row][column] != string[0]):
return
# Change the current checking entry to '@'
#so that it is not traversed again.
temp = board[row][column]
board[row][column] = '@'
for i, j in dfs:
if (checkword(board, row+i, column+j,string[1:])):
return True
board[row][column] = temp
return False
def wordsearch(board, rows,columns):
for row in range(rows):
for column in range(columns):
#Check only if the current entry starts with the string first letter
if board[row][column] == word[0]:
if (checkword(board, row,column, word)):
return True
print('False')
board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]
word = "ABCB"
rows = len(board)
columns = len(board[0])
print(wordsearch(board, rows, columns)) |
a7a5318c462dafc3c53f674a3db2d3335bd71551 | avi527/Data-Structure-Algorithms | /Array/find_maxm_distance_between_two_number.py | 533 | 4.1875 | 4 | # Python3 code to Find the minimum
# distance between two numbers
def minDist(arr, n, x, y):
min_dist = 99999999
for i in range(n):
for j in range(i + 1, n):
if (x == arr[i] and y == arr[j] or
y == arr[i] and x == arr[j]) and min_dist > abs(i-j):
min_dist = abs(i-j)
return min_dist
# Driver code
arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print("Minimum distance between ", x, " and ",
y, "is", minDist(arr, n, x, y))
# This code is contributed by "Abhishek Sharma 44"
|
2e9dfff42105dfcebf8c8ec1a3d943274a864e4e | bhaskar7310/Multiple-Reaction-OCM | /reaction.py~ | 24,555 | 3.515625 | 4 | '''
This module will read the rate equation provided by the user in
the [reaction_system]_rates.txt file and then convert it to a
mathematical form, which will be called for different values of
Temperature and mole fractions to calculate the actual rate.
Now one important point to note is that this calculation file is
entirely dependent on the validity of the [name]_rates.txt file.
If there is any manual input error, rest of the calculations will then
be effected. So one drawback to be dealt with in future is handling
user input errors.
We also need some getters and setters here, we need to implement
the principle of 'INFORMATION HIDING'.
There can be different ways of writing the rate expression based on
the mechanism. It can be Langmuir-Hinshelwood type or Power-Law type.
Even in Power Law model, the reverse rate expressions
may not be available and can be calculated from thermodynamics.
Our code can tackle all these different types of rate expressions.
For LNHW or ER reaction mechanisms, this code will only work if the
reaction mechanism is single site and
the rate-determining step is irreversible.
'''
import os
import numpy as np
import warnings
warnings.filterwarnings("error")
class Reaction:
R_g = 8.314
eps = 1e-06
def __init__(self, rate_type, k_f, Ea_f, species_f, n_f, k_r,
Ea_r, species_r, n_r, power, del_H, del_S):
self.rate_type = rate_type # Type of the reaction, PL/LNHW
self.k_f = k_f # Fwd reaction pre-exp factors
self.Ea_f = Ea_f # Fwd reaction activation energies
self.species_f = species_f # Fwd reaction species
self.n_f = n_f # Fwd reaction exponents
self.k_r = k_r # Rev reaction pre-exp factors
self.Ea_r = Ea_r # Rev reaction activation (or ads) enegies
self.species_r = species_r # So and So
self.n_r = n_r # So and So
self.power = power
self.del_H = del_H # Polynomial coefficients
# for calculating heat of reactions
self.del_S = del_S # Polynomial coefficient
# for calculating change in entropy
def calc_PL_rate(self, conc_dict, basis, k, Ea, spec, n, T, P):
'''
This function calculates PL type rates which are specifically
in the form of
rate = k * exp(-Ea/RT) * spec['A']**n['A'] * spec['B']**n['B']
'''
rate_const = k * np.exp(-Ea/(self.R_g * T)) # Raw reaction rate
#### Correction based on the basis of the reaction rates
if basis == 'mole_fraction':
rate_const *= (self.R_g * T/(101325 * P)) ** (sum(n) - 1)
elif basis == 'pressure' or basis == 'partial_pressure':
rate_const *= (self.R_g * T) ** (sum(n))
else:
if basis != 'concentration':
raise Exception ('Basis of the reaction rates (whether '
'concentration, pressure, or '
'mole fraction) is not understood')
rate = rate_const
if spec[0] != None:
for e1, e2 in zip(spec, n):
if e2 >= 1:
rate *= conc_dict[e1] ** e2
else:
rate *= (conc_dict[e1] ** (1+e2))/(conc_dict[e1] + self.eps)
return rate_const, rate
def act_rate(self, Y, species, basis, P=1):
'''
This function calculates the actual rate calculated at a
specific temperature and mole fractions.
'''
#### Unpacking the input list Y
Ylist = Y[:-1]
T = Y[-1]
#### Initialization
rate_fwd_const = [] # List of the forward rate constants
rate_fwd_list = [] # List of the actual forward reaction rates
rate_rev_const = [] # List of the reverse rate constants
rate_rev_list = [] # List ofof the actual reverse reaction rates
act_rate_list = [] # List of actual rates,
# (fwd - rev) for PL and (num/den) for LNHW
#### Manipulating the inputs
conc_dict = dict(zip(species, Ylist))
#### Calculating the forward rate (for PL type)
### or the numerator (for LNHW type)
for k, Ea, spec, n in zip(self.k_f, self.Ea_f,
self.species_f, self.n_f):
fwd_const, fwd_rate = self.calc_PL_rate(conc_dict, basis, k, Ea,
spec, n, T, P)
rate_fwd_const.append(fwd_const)
rate_fwd_list.append(fwd_rate)
#### Calculating the reverse rate (for PL type)
#### or the denominator (for LNHW type)
index = 0 # Keeps a count of the reactions
for rate_type, k, Ea, spec, n in zip(self.rate_type, self.k_r,
self.Ea_r, self.species_r,
self.n_r):
#### Power Law type reverse reaction rates
if rate_type == 'PL':
#### The reaction rates are provided
if k > 0:
rev_const, rev_rate = self.calc_PL_rate(conc_dict, basis,
k, Ea, spec, n,
T, P)
rate_rev_const.append(rev_const)
rate_rev_list.append(rev_rate)
#### Irreversible reaction rates
elif k == 0:
rate_rev_list.append(0)
rate_rev_const.append(0)
#### Reaction rate constant is calculated from thermodynamics
elif k == -1:
del_H = self.del_H[:, index, :]
del_S = self.del_S[:, index, :]
H_T_dependence = np.array([T, T**2/2, T**3/3,
T**4/4, T**5/5, 1]).reshape(6, 1)
S_T_dependence = np.array([np.log(T), T, T**2/2, T**3/3,
T**4/4, 1]).reshape(6, 1)
if T > 1000:
del_H_T = np.dot(del_H[0, :], H_T_dependence)
del_S_T = np.dot(del_S[0, :], S_T_dependence)
else:
del_H_T = np.dot(del_H[1, :], H_T_dependence)
del_S_T = np.dot(del_S[1, :], S_T_dependence)
del_G_T = del_H_T - T * del_S_T
K_eq_T = np.exp(-del_G_T/(self.R_g * T))
rate_rev = rate_fwd_const[index]/K_eq_T[0]
rate_rev_const.append(rate_rev)
if spec != None:
for e1, e2 in zip(spec, n):
if e2 >= 1:
rate_rev *= conc_dict[e1] ** e2
else:
rate_rev *= (conc_dict[e1] ** (1+e2))\
/ (conc_dict[e1] + self.eps)
rate_rev_list.append(rate_rev)
act_rate_list.append(rate_fwd_list[index] - rate_rev_list[index])
index += 1
elif rate_type == 'LNHW':
deno_sum = 1
for k_1, Ea_1, spec_1, n_1 in zip(k, Ea, spec, n):
deno_const, deno_rate = self.calc_PL_rate(conc_dict,
basis, k_1, Ea_1, spec_1, n_1, T, P)
if basis == 'mole_fraction':
deno_rate *= (self.R_g * T)/(101325 * P)
deno_sum += deno_rate
rate_rev_list.append(deno_sum**self.power[index])
act_rate_list.append(rate_fwd_list[index]/rate_rev_list[index])
index += 1
#### Other options
else:
raise Exception('We are stuck here, work is in progress, '
'we will calculate this soon!!!')
#### Shipping
actual_rate = np.array(act_rate_list)
return actual_rate
def reaction_jacobian(self, Y, fvec, *args):
'''
This function calculates the derivatives of reaction
rates with respect to concentration and temperature and
returns the jacobian matrix.
'''
#### Checking the inputs
no_of_cols = Y.shape[0]
no_of_reaction = fvec.shape[0]
#### Specifying variables
column = 0.
eps = 1e-06
J = np.zeros([no_of_reaction, no_of_cols], dtype=float)
Y_pos = Y.copy()
for i in range(no_of_cols):
h = eps * Y[i]
if h == 0:
h = eps
Y_pos[i] = Y[i] + h
column = (self.act_rate(Y_pos, *args) - fvec)/h
J[:, i] = column[:]
Y_pos[i] = Y_pos[i] - h
#### Packaging and Shipping
J_conc = J[:, :-1]
J_T = J[:, -1]
return J_conc, J_T;
def get_rate_type(react_ID):
'''
This function takes in the reaction ID (which is a string)
and looks for consecutive upper case letters and then returns
joining all those upper case consecutive letters
(which will represent the reaction rate type).
Possible types of rate expressions are:
LNHW : Langmuir-HinshelWood Hougen Watson
ER : Eley-Riedel
MVK : Mars van Krevelen
PL : Power Law (Arrhenius type)
'''
#### A not-so-required assertion statement
assert isinstance(react_ID, str), 'Error!!! The input has to be a string!!!'
index = 0
new_index = 0
possible_rate_type = ['LNHW', 'ER', 'MVK', 'PL']
#### Iterating over the react_ID string
for elem in react_ID:
if elem.isupper():
new_react_ID = react_ID[index:]
else:
index += 1
for new_elem in new_react_ID:
if new_elem.isupper():
new_index += 1
else:
break
rate_type = new_react_ID[:new_index]
if rate_type not in possible_rate_type:
raise Exception('Reaction rate type is not understood.')
else:
return rate_type
def get_rxn_no(react_ID):
'''
This function takes in the reaction ID (which is string)
looks for consecutive numbers and then returns
that number. That number represents the reaction number.
'''
index = 0
num_str_list = []
new_index = 0
#### Iterating through the react_ID
for elem in react_ID:
try:
int(elem)
except ValueError:
index += 1
else:
num_str_list.append(elem)
index += 1
new_ID = react_ID[index:]
break
for new_elem in new_ID:
try:
int(new_elem)
except ValueError:
break
else:
num_str_list.append(new_elem)
new_index += 1
rxn_no_str = ''.join(num_str_list)
rxn_no = int(rxn_no_str)
rate_type = get_rate_type(new_ID[new_index:])
return rxn_no, rate_type
def segregate_PL(rate_exp):
'''
This function identifies the different components in the
Power Law (Arrhenius) type rate expression.
By different components we mean:
rate_const : Pre-exponential
activation_energy: Activation energy
n_react : Exponents of species
species_reactive : Active species involved in the rate expression
'''
#### Variable Initialization
activation_energy = 0
n_react = 0
species_react = None
terms = rate_exp.split('*')
try:
#### Pre-exponential factor
rate_const = float(terms[0])
except ValueError:
rate_const = -1
else:
#### Activation Energy
if (rate_const !=0):
second_word = terms[1]
#### Checking for the sign inside the exponential
if second_word[4] == '-':
index = 5
else:
index = 4
num_start = index
for elem in second_word[num_start+1:]:
index += 1
if elem == '/':
break
activation_energy = float(second_word[num_start:index])
if (num_start == 4):
activation_energy *= -1
finally:
#### Active Species in rate equation
if (rate_const != 0):
species = terms[2:]
species_react = []
n_react = []
for elem in species:
if elem != '':
try:
num = float(elem)
n_react.append(num)
except:
species_react.append(elem[1:-1])
return rate_const, activation_energy, n_react, species_react
def segregate_LNHW(deno_exp):
'''
This function identifies the different expressions in the
denominator of a LNHW (or Eley Ridel) type rate
expression with a single site mechanism.
If the mechanism is dual site, this code will fail.
Neither can it handle rate expressions where the rate-
determining step is reversible. For all other single site reaction
mechanisms with irreversible rate
determining step, this code will work fine.
General expression of the denominator:
deno_exp = (1 + K1*exp(-del_H1_/RT) * [A]**n_A * [B]**n_B
+ K_2*exp(-del_H2/RT) * [A]**n2_A * [B]**n2)**2
'''
#### List Initialization
K_ads = []
del_H_ads = []
n_ads = []
species_ads = []
power_list = []
#### Getting the power to which the denominator
#### of LNHW type reaction rate is raised
n = len(deno_exp)
for i in range(-1, -(n+1), -1):
try:
int(deno_exp[i])
except ValueError:
if deno_exp[i] == '.':
power_list.append(deno_exp[i])
elif deno_exp[i:i-2:-1] == '**':
i -= 2
break
elif deno_exp[i] == ')':
break
else:
raise Exception ('The expression of denominator given by {} '
'cannot be recognised'.format(deno_exp))
else:
power_list.append(deno_exp[i])
if power_list:
power_str = ''.join(power_list) # Making a single string from the list
power = float(power_str[::-1]) # Making a floating point number
# from the reversed list
else:
power = 1
#### Iterating through the true expression
#### (devoid of the power it is raised to)
expression = deno_exp[1:i]
terms = expression.split('+')
for elem in terms:
try:
float(elem)
except ValueError:
rate_const, \
adsorption_enthalpy, \
n_react, species_react = segregate_PL(elem)
K_ads.append(rate_const)
del_H_ads.append(adsorption_enthalpy)
n_ads.append(n_react)
species_ads.append(species_react)
else:
term_num = float(elem)
return term_num, K_ads, del_H_ads, n_ads, species_ads, power
def instantiate(react_system, const, catalyst= None):
'''
This funtion reads the kinetic data file and then stores the
rate expressions of homogeneous and catalytic rate expressions.
'''
#### Finding the correct file:
filename, ext = os.path.splitext(react_system)
if catalyst:
newFileName = filename + '_' + catalyst.lower() + '_rates' + ext
else:
newFileName = filename + '_rates' + ext
if not os.path.isfile(newFileName):
raise FileNotFoundError ('The rate expression of {} system is '
'not provided.'.format(filename))
#### Initialization of lists
k_f = []
Ea_f = []
species_f = []
n_f = []
k_r = []
Ea_r = []
species_r = []
n_r = []
deno_raised_power = []
cat_index = []
homo_index = []
nu_homo_index = []
nu_cat_index = []
rate_type_list = []
#### Reading the rate expression file and storing the required data
with open(newFileName, 'r') as infile:
infile.readline() # Reading customary first line
count = 0 # Counting the number of lines
react_count = 0 # Reaction counting no.
for line in infile.readlines():
count += 1
if (count % 2) != 0:
react_count += 1
forward = True
reverse = False
else:
forward = False
reverse = True
line_new = line.replace(' ', '').replace('\n', '')
id_expression = line_new.split('=')
#### Reaction identifier (whether Catalytic or Homogeneous)
react_ID = id_expression[0]
rate_exp = id_expression[1]
if (count % 2) != 0:
rxn_no, rate_type = get_rxn_no(react_ID)
rate_type_list.append(rate_type)
if react_ID[2] == 'c':
nu_cat_index.append(rxn_no - 1)
cat_index.append(react_count - 1)
elif react_ID[2] == 'h':
nu_homo_index.append(rxn_no - 1)
homo_index.append(react_count - 1)
#### Power-law (PL) type reactions
if (rate_type == 'PL') or (forward == True):
rate_const, \
activation_energy, \
n_react, species_react = segregate_PL(rate_exp)
#### Langmuir-Hinshelwood (LNHW) type reactions
elif (rate_type == 'LNHW') and (reverse == True):
term_num, \
K_ads, \
del_H_ads, \
n_ads, species_ads, power = segregate_LNHW(rate_exp)
#### Any other type of reaction rate expressions
else:
raise Exception('We are still working on it. Come back later.')
#### Storing all the rate expression information
if (forward == True):
k_f.append(rate_const)
Ea_f.append(activation_energy)
species_f.append(species_react)
n_f.append(n_react)
elif (reverse == True) and (rate_type == 'PL'):
deno_raised_power.append(0)
if (rate_const > 0):
k_r.append(rate_const)
Ea_r.append(activation_energy)
species_r.append(species_react)
n_r.append(n_react)
elif (rate_const == 0):
k_r.append(0)
Ea_r.append(0)
species_r.append(None)
n_r.append([0])
elif (rate_const == -1):
k_r.append(rate_const)
Ea_r.append(0)
species_r.append(species_react)
n_r.append(n_react)
else:
raise Exception ('Error in the reverse expression '
'of Reaction : {}, in '
'Power Law (PL) '
'type rate expression'.format(rxn_no))
elif (reverse == True) and (rate_type == 'LNHW'):
k_r.append(K_ads)
Ea_r.append(del_H_ads)
species_r.append(species_ads)
n_r.append(n_ads)
deno_raised_power.append(power)
else:
raise Exception ('Something unusual spotted in Reaction : {}, '
'in reaction type.'.format(rxn_no))
#### Converting all the lists to np.ndarray
k_f = np.array(k_f)
Ea_f = np.array(Ea_f)
species_f = np.array(species_f)
n_f = np.array(n_f)
k_r = np.array(k_r, dtype= object)
Ea_r = np.array(Ea_r, dtype= object)
species_r = np.array(species_r, dtype= object)
n_r = np.array(n_r, dtype= object)
deno_raised_power = np.array(deno_raised_power, dtype= object)
rate_type_arr = np.array(rate_type_list)
#### Segregating the homogeneous and catalytic reaction parameters
k_f_homo = list(k_f[homo_index])
Ea_f_homo = list(Ea_f[homo_index])
species_f_homo = list(species_f[homo_index])
n_f_homo = list(n_f[homo_index])
k_r_homo = list(k_r[homo_index])
Ea_r_homo = list(Ea_r[homo_index])
species_r_homo = list(species_r[homo_index])
n_r_homo = list(n_r[homo_index])
power_homo = list(deno_raised_power[homo_index])
homo_rate_type = list(rate_type_arr[homo_index])
k_f_cat = list(k_f[cat_index])
Ea_f_cat = list(Ea_f[cat_index])
species_f_cat = list(species_f[cat_index])
n_f_cat = list(n_f[cat_index])
k_r_cat = list(k_r[cat_index])
Ea_r_cat = list(Ea_r[cat_index])
species_r_cat = list(species_r[cat_index])
n_r_cat = list(n_r[cat_index])
power_cat = list(deno_raised_power[cat_index])
cat_rate_type = list(rate_type_arr[cat_index])
#### Retrieving the Thermodynamic datas
all_del_H = const['all_del_H']
all_del_S = const['all_del_S']
del_H_homo = all_del_H[:, nu_homo_index, :]
del_H_cat = all_del_H[:, nu_cat_index, :]
del_S_homo = all_del_S[:, nu_homo_index, :]
del_S_cat = all_del_S[:, nu_cat_index, :]
#### Instantiating the reaction parameters
homo = Reaction(homo_rate_type, k_f_homo, Ea_f_homo,
species_f_homo, n_f_homo, k_r_homo, Ea_r_homo,
species_r_homo, n_r_homo, power_homo,
del_H_homo, del_S_homo)
cat = Reaction(cat_rate_type, k_f_cat, Ea_f_cat,
species_f_cat, n_f_cat, k_r_cat, Ea_r_cat,
species_r_cat, n_r_cat, power_cat,
del_H_cat, del_S_cat)
#### Shipping
return homo, cat, nu_homo_index, nu_cat_index
if __name__ == '__main__':
import constants
react_system = 'OCM_two_reaction.txt'
catalyst = 'La_Ce'
homo_basis = 'mole_fraction'
cat_basis = 'mole_fraction'
const, thermo_object = constants.fixed_parameters(react_system)
homo, cat, \
homo_index, cat_index = instantiate(react_system, const, catalyst)
print(homo.n_r)
species = const['species']
no_of_species = len(species)
ID = np.arange(no_of_species)
species_ID = dict(zip(species, ID))
print(species_ID)
inlet_species = 'CH4'
inlet_ratio = 4
F_A_in = inlet_ratio/(inlet_ratio+1)
F_B_in = 1/(inlet_ratio+1)
F_in = 1e-08 * np.ones(no_of_species)
A_index = species_ID[inlet_species]
B_index = species_ID['O2']
F_in[A_index] = F_A_in
F_in[B_index] = F_B_in
T_f = 300
conc_dict = dict(zip(species, F_in))
fwd_rate = homo.calc_PL_rate(conc_dict, homo_basis, homo.k_f[0],
homo.Ea_f[0], homo.species_f[0],
homo.n_f[0], T_f, 1)
print(fwd_rate)
print(homo.k_r)
|
ccd01ce30c1a553c5cb3018871dfc54eae0b5691 | vijgan/HackerRank | /Search/find_maximum_index_product.py | 3,079 | 4.5 | 4 | '''
This function,
1. Takes the original array and 2 generated arrays (left_array and right_array)
2. left_array and right_array are the exact length as the original array
3. It calls 2 functions get_left_index and get_right_index.
4. Each of these functions will calculate the left and right value (greater than current or 0)
for the current index
5. Print that maximum value
'''
def find_max_index_product(array,length):
maximum=0
if length<3:
print (0)
sys.exit(1)
for i in range(1,length-1):
get_left_index(array,array[i],i)
get_right_index(array,array[i],i,length)
value=left_array[i]*right_array[i]
if value>maximum: maximum=value
print (maximum)
'''
This function,
1. Takes in current_value, current_index and the array
2. Here, we will update the left_index array with index of the first element greater than current element
3. To do this, we will consider 3 criterias,
i. If the previous element is less than the current,
we can set the start_index (for iteration) to the index returned for previous element.
By, this we can skip elements which are already computed.
ii. If the previous element is equal to current element, assign the left_index to value
of the previous element and return
iii. If none of the condition is set, we can set start to index of previous element
'''
def get_left_index(array,current,index):
global left_array
if array[index-1]<current:
start=left_array[index-1]
elif array[index-1]==current:
left_array[index]=left_array[index-1]
return
else:
start=index-1
for i in range(start,-1,-1):
if array[i]>current:
left_array[index]=i+1
return
else: continue
'''
This function is very similar to get_left_index,
1. Takes in current_value, current_index, array and last_index
2. Here, we will update the right_index array with index of the first element greater than current element
3. To do this, we will consider 3 criterias,
i. If the next element is less than the current,
we can set the start_index (for iteration) to the index returned for next element.
By, this we can skip elements which are already computed.
ii. If the next element is equal to current element, assign the right_index to value
of the previous element and return
iii. If none of the condition is set, we can set start to index of next element
'''
def get_right_index(array,current,index,length):
global right_array
if array[index+1]<current:
start=right_array[index+1]
elif array[index+1]==current:
right_array[index]=right_array[index+1]
return
else:
start=index+1
for i in range(start,length):
if array[i]>current:
right_array[index]=i+1
return
else: continue
length=int(input())
left_array=[0]*length
right_array=[0]*length
array=list(input().split())
array=[int(elem) for elem in array]
find_max_index_product(array,length)
|
682a500dc5822d2aa950d79c099cd3e50ef36a65 | batukochan/VSCode-Python-Egitim | /04_liste_string_metodlar/listeler_islemler.py | 1,979 | 3.890625 | 4 | #region iki listeyi birleştirmek
"""
sayilar = [1,2,3,4,5,6,7,8]
harfler = ['a',"b","c","d"]
''' summation'''
listelerinBirlesimi = sayilar + harfler
print(listelerinBirlesimi)
listelerinBirlesimi = harfler +sayilar
print(listelerinBirlesimi)
print(type(listelerinBirlesimi)) #list
listelerinBirlesimi.append("python")
print(listelerinBirlesimi)
print(sayilar,harfler)
print(type(listelerinBirlesimi)) #list
"""
#endregion
#region multiplyist
"""
sayilar = [1,2,3,4,5,6,7,8]
liste = sayilar*5
print(liste)
"""
"""
sayilar = [1,2,3,4,5,6,7,8,9,10]
karesi = []
print(sayilar)
for i in sayilar:
kare = i**2
karesi.append(kare)
print(karesi)
"""
#endregion
#region
"""
karesi = [sayi**2 for sayi in range(1,11)]
print(karesi)
"""
'''
kenar uzunlukları 1den 10a kadar olan
eşkenar üçgenlerin alanını bulan program
'''
#alan = (((3**1/2)*(a**2))/4)
"""
alanlar = [round((((3**1/2)*(i**2))/4),3) for i in range(1,11)]
print(alanlar)
"""
#1den 10000e kadar olan çiftleri
"""
ciftSayilar = [sayi for sayi in range(2,1001,2)]
print(ciftSayilar)
"""
#hem çift hem de üçe tam bölünen
"""
ucVecift = [sayi for sayi in range(1,1001) if sayi % 3 == 0]
print(ucVecift)
"""
"""
ucVecift = [sayi for sayi in range(1,101) if sayi % 3 == 0 and sayi % 2 == 0]
print(ucVecift)
"""
"""
isimler = ["ahmet","mehmet","onur","oğuzhan","doğukan"]
ismiOileBaslayanlar = [isim for isim in isimler if .startw with('o') ]
"""
#endregion
#region örnek
"""
list1 = [10,20,30]
list2 = [2,7,11,13]
yeniListe = []
for i in list1:
for j in list2:
yeniListe.append(i*j)
print(yeniListe)
"""
"""
list1 = [10,20,30]
list2 = [2,7,11,13]
yeniListe = [x*y for x in list1 for y in list2 if x*y <= 200]
print(yeniListe)
"""
"""
list1 = [10,20,30]
list2 = [2,7,11,13]
sayi = 110
if sayi in [x*y for x in list1 for y in list2 if x*y <= 200] :
print("ok")
"""
#endregion
#region
"""
kordinat = [5,3,2]
x,y,z = kordinat[:3]
multiply = x*y*z
print(multiply)
"""
#endregion
|
e92e484b8d6b3ad718abd8cc09f9e905b5ce21e2 | bjflamm/python | /python_practice/gcd.py | 580 | 3.84375 | 4 | # //calculate gcd of two numbers
def gcd(num1,num2):
divisor = 1
gcd = 1
while(divisor <= num1 and divisor <= num2):
if(num1 % divisor == 0) and (num2 % divisor == 0):
gcd = divisor
divisor += 1
return gcd
def gcd2(num1,num2):
gcd = 1
if(num1 < num2):
for i in range(1,num1-1):
if(num1 % i == 0 and num2 % i == 0):
gcd = i
else:
for i in range(1,num2-1):
if(num1 % i == 0 and num2 % i == 0):
gcd = i
return gcd
print(gcd2(40,30)) |
ca7f65e50aa637dd87b450dd52fe323b5d7e38fb | calfdog/Robs_automation_tools | /misc_utils/covert_string_to_dict.py | 777 | 3.96875 | 4 | """
Developed by: Rob Marchetti July 2021
Lazy man's script that lets you take a string that you want as a dict and converts it to a dictionary
Example:
INPUT: s = "Lang1 Python Lang2 Ruby Lang3 Java Lang4 Perl"
OUTPUT: {'Lang1': 'Python', 'Lang2': 'Ruby', 'Lang3': 'Java', 'Lang4': 'Perl'}
Updated for Python 3
"""
def covert_string_to_dict(s):
"""Take a string, split it, quote it, convert to list convert to dict"""
lst = list(s.split())
res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)}
return res_dct
# string to convert
s = "Lang1 Python Lang2 Ruby Lang3 Java Lang4 Perl"
dct = covert_string_to_dict(s)
print(dct) # {'Lang1': 'Python', 'Lang2': 'Ruby', 'Lang3': 'Java', 'Lang4': 'Perl'}
print(dct["Lang1"]) # Python
|
e64b975130d584713de066d60a70b46e5e55c883 | danoliveiradev/PythonExercicios | /ex104.py | 455 | 4.03125 | 4 | def leiaInt(msg):
"""
-> Função que só aceita a leitura de números
:param msg: recebe texto pedindo um número
:return: retorna o resultado na análise
"""
num = input(msg)
while num.isnumeric() is False:
print('\033[31mERRO! Digite um número inteiro válido.\033[m')
num = input(msg)
return num
# Programa Principal
n = leiaInt('Digite um número: ')
print(f'Você acabou de digitar o número {n}')
|
b1bb38fdcc138be9623a825c3249aa4d2ab0a936 | makubex01/python_lesson | /ch5/kwargs.py | 243 | 3.53125 | 4 | def show_keywords(**args):
for key, value in args.items(): #argsのキーとvalueに代入
print(key + "=" + str(value)) #1つずつkeyとvalueを出力
print("---")
show_keywords(a=55,b=87)
show_keywords(c=55,d=87,e=62) |
e107ea669cde1d90afef49fea00f20cbdfcc0209 | deepakag5/Data-Structure-Algorithm-Analysis | /leetcode/puzzle_generate_parenthesis.py | 660 | 3.515625 | 4 | # Time : O(4^n/ sqrt(n))
# Space : O(4^n/ sqrt(n))
def generate_parenthesis(n):
if n == 0:
return []
result = []
def backtrack(s='', left=0, right=0):
# we need to have a closing bracket for each opening bracket
# so a pair hence 2*n
if len(s) == 2 * n:
result.append(s)
return
# we need open brackets at most the length of n
if left < n:
backtrack(s + '(', left + 1, right)
# we will place a closing bracket only after we have an open bracket
if right < left:
backtrack(s + ')', left, right + 1)
backtrack()
return result
|
fdd914f82bab8a9c0ef614df8d964509f4597c0f | beczkowb/algorithms | /binarysearch.py | 1,614 | 3.828125 | 4 | import unittest
def search(A, p, r, x):
if len(A) == 0:
return None
elif r < 0 or p > len(A):
return None
elif p == r:
if A[p] == x:
return p
else:
return None
else:
q = (r-p) // 2
if A[q] == x:
return q
elif x > A[q]:
return search(A, q+1, r, x)
else:
return search(A, p, q-1, x)
class SearchTestCase(unittest.TestCase):
def test0(self):
A = []
p, r, x = 0, 0, 0
self.assertIsNone(search(A, p, r, x))
def test1(self):
A = [1]
p, r, x = 0, 0, 1
self.assertEqual(0, search(A, p, r, x))
p, r, x = 0, 0, 2
self.assertEqual(None, search(A, p, r, x))
p, r, x = 0, 0, 0
self.assertEqual(None, search(A, p, r, x))
def test2(self):
A = [1, 2]
p, r, x = 0, 1, 1
self.assertEqual(0, search(A, p, r, x))
p, r, x = 0, 1, 2
self.assertEqual(1, search(A, p, r, x))
p, r, x = 0, 1, 0
self.assertEqual(None, search(A, p, r, x))
p, r, x = 0, 1, 0
self.assertEqual(None, search(A, p, r, x))
def test3(self):
A = [1, 2, 3]
p, r, x = 0, 2, 1
self.assertEqual(0, search(A, p, r, x))
p, r, x = 0, 2, 2
self.assertEqual(1, search(A, p, r, x))
p, r, x = 0, 2, 3
self.assertEqual(2, search(A, p, r, x))
p, r, x = 0, 2, 0
self.assertEqual(None, search(A, p, r, x))
p, r, x = 0, 2, 4
self.assertEqual(None, search(A, p, r, x)) |
9e649402ca52f83c02723632c7253f477bc2652c | codinggosu/algorithm-study | /src/dongjoo/week4/minaddparan.py | 853 | 3.515625 | 4 | # 921. Minimum Add to Make Parentheses Valid
class Solution:
def minAddToMakeValid(self, S: str) -> int:
# decrease counter for ')' and increase for '('
count = 0
idx = 0
answer = 0
while idx < len(S):
if S[idx] == ")":
count -= 1
elif count>= 0 and S[idx] == "(":
count += 1
elif count < 0 and S[idx] == "(":
answer += abs(count)
count = 1
idx += 1
return answer + abs(count)
answer = Solution()
print(answer.minAddToMakeValid("((("))
# Runtime: 28 ms, faster than 98.99% of Python3 online submissions for Minimum Add to Make Parentheses Valid.
# Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Minimum Add to Make Parentheses Valid. |
e6b4b59a45456e827d53e0c624d553bd2c81505c | JonesPaul98/guvi | /perimeter of a rectangle | 145 | 3.953125 | 4 | l=int(input("enter the length of a rectangle:"))
b=int(input("enter the breadth of a rectangle:"))
p=2*(l+b)
print("perimeter of a rectangle",p)
|
6e53d955acd35f5f1da0fcdde636fa234e57bfcb | snail15/CodingDojo | /Python/week3/Dictionary/dictionary.py | 227 | 4.375 | 4 | dict = {
"name": "Sungin",
"country of birth": "Korea",
"age": 30,
"favorite language": "Korean"
}
def printdict(dict):
for key in dict:
print("My {0} is {1}".format(key, dict[key]))
printdict(dict) |
d6af1267c2a31667e03870df1398a4f3bb7afc50 | juniortheory/python-programming | /unit-2/problem4.py | 1,278 | 4.15625 | 4 | '''
#problem 4
a = str(input('What caculation would you like to do? Add, Subtract, Multiply or Divide: '))
if 'Add' == a:
print('Add!')
b = int(input('What number would you like to Add?: '))
c = int(input('What other number would you like to Add?: '))
print('Your total is:', (b + c))
elif 'Subtract' == a:
print('Subtract!')
b = int(input('What number would you like to Subtract?: '))
c = int(input('What other number would you like to Subtract?: '))
print('Your total is:', (b - c))
elif 'Multiply' == a:
print('Multiply!')
b = int(input('What number would you like to Multiply?: '))
c = int(input('What other number would you like to Multiply?: '))
print('Your total is:', (b * c))
elif 'Divide' == a:
print('Divide!')
b = int(input('What number would you like to Divide?: '))
c = int(input('What other number would you like to Divide?: '))
print('Your total is:', (b / c))
'''
#teacher
op = input('What calculations would you like to do? ')
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number:'))
if op == 'add':
res = 'Your result is {}. Calc you later!'.format(num1 + num2)
print(res)
if op == 'add':
ans = num1 + num2
print(f'Your result is {ans}. Calc you later!')
|
af37be8e2663b3101ec34d4203382446e1462f80 | Minions1128/helloworld | /basic/parameters_of_function.py | 1,382 | 4.25 | 4 | # -*- coding: UTF-8 -*-
"""
介绍了函数参数的传递过程:
1,list参数传递
2,参数的打包
3,开包
4,函数作为参数
"""
# 参数传递
a = 1
def plus(a):
a += 1
return a
print plus(a)
print a
"""
输出结果:2,1
"""
b = [1, 2, 3]
def pluss(b):
b[0] += 1
return b
print pluss(b)
print b
"""
输出结果:
[2, 2, 3]
[2, 2, 3]
"""
# 参数的默认值
def f(a, b, c):
# 未使用默认参数
return a + b + c
print f(1, 2, 3)
def fun1(a, b, c=3):
# 有默认值的参数只能放在多个函数参数的后面
return a + b + c
print fun1(2, 3)
# 2, 3分别为a和b的值,c的值为默认值
print fun1(c=1, a=2, b=3)
# 可以将参数的位置进行调换,但其名称无法改变
# 参数打包
def func(*nameshen):
# 参数相当于tuple
print nameshen
func(1,4,6)
func(5,6,7,1,2,3)
def func(**dictzhe):
# 参数相当于dict
print dictzhe
func(a=1,b=9)
func(m=2,n=1,c=11)
print "\nUnpacking"
def func(a,b,c):
print a,b,c
args = (1,3,4)
func(*args) #tuple的数量必须和函数的数量相同
dictJian = {'a':1,'b':2,'c':3}
func(**dictJian) #dict中的key和value必须与func中的一致
print "\nfunction as arguements"
def func(x,y):
return x+y
def test(f,a,b):
print 'test'
print f(a,b)
test(func, 3, 5)
test((lambda x, y:x**2+y), 6, 9)
|
efabd0778655c682f8bb5dd951d1439d99ec6e9b | A01376718-Silvia/Mision-04 | /Software.py | 955 | 3.921875 | 4 | # Autor: Silvia Ferman Muñoz
# Programa que lee el número de paquetes comprados e imprime la cantidad descontada (si la hay) y el total.
# Tecnica Top-Down
# CONSTANTE del costo
costo = 1500
# Calcular el descuento, depende de las unidades
def calcularDescuento(paquetes):
if paquetes < 10:
return 0
if paquetes >= 10 and paquetes <= 19:
return .2
if paquetes >= 20 and paquetes <= 49:
return .3
if paquetes >= 50 and paquetes <= 99:
return .4
if paquetes >= 100:
return .5
# Calcular el total a pagar
def calcularTotalPagar(paquetes):
if paquetes > 0:
return (costo * paquetes) * (calcularDescuento(paquetes))
else:
print("ERROR, NO se puede calcular")
# Función principal
def main():
paquetes = int(input("Los paquetes comprados son: "))
print("El total a pagar es de: $%.2f" % (calcularTotalPagar(paquetes)))
# Llama a la función principal
main() |
355d7487fca677d69c659436fad7e5b197f3ca97 | JineshKamdar98/Codchef-Problem-Solutions | /Codechef Problem solutions/byte to bit.py | 409 | 3.5625 | 4 | for t in range(int(input())):
n=int(input())
n=n-1
bit,nibble,byte=0,0,0
r=n%26
k=n//26
if(r>=0 and r<2):
bit+=pow(2,k)
print(bit,nibble,byte)
elif(r>=2 and r<10):
nibble+=pow(2,k)
print(bit,nibble,byte)
elif(r>=10 and r<26):
byte+=pow(2,k)
print(bit,nibble,byte)
|
6efe9ab64465563e4517ea469eed3a917584b16b | choukin/learnPython | /day1/str.py | 414 | 3.75 | 4 | # -*- coding: utf-8 -*-
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125))
s1 = 72
s2 = 85
r = '{0} 成绩提升了 {1:.1f} %'
s3 = (s2-s1)%s1
print(r.format('小明',s3))
print('%s 成绩提升了 %.1f %%'%('小明', s3))
ch = '中文'
chencode = ch.encode('utf-8')
print(chencode)
chdecode = chencode.decode('utf-8')
print(chdecode) |
796c7f5f7d63fffbadcf38588d5ba43db3a42b3b | Kdcc-ai/python | /面向对象高级编程/6.使用枚举类.py | 2,828 | 3.8125 | 4 | # 当我们需要定义常亮时 一个办法使用大写变量用过整数来定义。。
# 比如定义12个月 显得麻烦
# 所以有个好方法 是为这样的枚举类型定义一个class类型
# 每个常量都是class的唯一实例
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# 这样 我们就获得了Month 类型 的 枚举类 可以直接用 Month.Jan来引用一个常亮
# 或者枚举他的所有成员:
print(Month.Jan)
print(Month['Jan'])
print(Month.Jan.value)
print(list(Month))
for name,member in Month.__members__.items():
print(name,'=>',',',member.value)
# value属性则是自动 赋给 成员的int常量 默认从1开始计数
# Enum派生出自定义类
from enum import Enum,unique
@unique
class Weekday(Enum):
Sun=0
Mon=1
Tue=2
Wed=3
Thu=4
Fri=5
Sat=6
# @unique装饰器帮助我们检查保证没有重复值
# 访问这些枚举类型有若干种方法
print(Weekday.Mon)
print(Weekday['Mon'])
print(Weekday(1))
print(Weekday.Tue.value)
for name,member in Weekday.__members__.items():
print(name,'=>',member)
# 练习:
# 把Student的gender属性改造为枚举类型,可以避免使用字符串
@unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
print('测试通过!')
else:
print('测试失败!')
# 补充 枚举类型可以看做是一种标签或者是一系列常量的集合
# 通常用于表示某些特定的有限集合
class Color:
RED = 1
GREEN = 2
BLUE = 3
# 这样也可以呀!!!
# 不过这样有弊端 可以被修改对吧?
# 最好的方法:
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
print(Color.red)
print(repr(Color.red))
print(type(Color.red))
print(isinstance(Color.red,Color))
#枚举类型不可实例化 不可更改
# 定义枚举 成员名不允许重复
# class Color(Enum):
# red = 1
# green = 2
# red = 3 # TypeError: Attempted to reuse key: 'red'
# 成员值允许相同 第二个成员的名称被视作第一个成员的别名
class Color(Enum):
red = 1
green = 2
blue = 1
print(Color.red)
print(Color.blue)
# 输出Color.red
print(Color.red is Color.blue)
# True
print(Color(1))
# Color.red
# 若不能定义相同的成员值,可以用unique装饰
# from enum import Enum, unique
# @unique
# class Color(Enum):
# red = 1
# green = 2
# blue = 1 # ValueError: duplicate values found in <enum 'Color'>: blue -> red
# 枚举比较 枚举的成员可以通过is同一性 或通过==比较
# 不能进行大小比较
|
3b76e2302ce7a135efe0a170974f4f5a0f592ca1 | salee1023/TIL | /3.Algorithm/07. Tree/중위순회.py | 764 | 3.59375 | 4 | def f(n): # n번 노드 방문, 방문 후 유효한 노드인지 검사
if tree[n][0]: # 유효한 노드면
f(tree[n][1]) # 왼쪽 자식으로 이동
print(tree[n][0], end='') # n번 노드에서 할일 (왼쪽자식에서 리턴 후, 중위순회 in-order)
f(tree[n][2]) # 오른쪽 자식으로 이동
# -------------------------------------
for tc in range(1, 11):
N = int(input())
tree = [[0]*3 for _ in range(N+1)]
for i in range(1, N+1):
data = input().split()
tree[int(data[0])][0] = data[1]
if len(data) > 2:
tree[int(data[0])][1] = int(data[2])
if len(data) > 3:
tree[int(data[0])][2] = int(data[3])
print(f'#{tc} ', end='')
f(1)
print() |
93be0f3ac9172a34f68970d07f8b0d771b0b110b | frankcj6/Data_Structure_Review | /binary search.py | 3,883 | 3.890625 | 4 | # linear search
def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return True
return False
# binary search
def binary_search_iterative(data, target):
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target > data[mid]:
low = mid + 1
else:
high = mid - 1
return False
def binary_search_recursive(data, target, low, high):
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target > data[mid]:
return binary_search_recursive(data, target, mid + 1, high)
else:
return binary_search_recursive(data, target, low, mid - 1)
data = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12]
target = 11
print(binary_search_recursive(data, target, 0, len(data) - 1))
print(binary_search_iterative(data, target))
# find closest number
def closest_number(data, target):
min_diff = float('inf')
low = 0
high = len(data) - 1
closest_num = None
if len(data) == 0:
return None
if len(data) == 1:
return data[0]
while low <= high:
mid = (low + high) // 2
if mid + 1 < len(data):
min_dff_right = abs(data[mid + 1] - target)
if mid > 0:
min_dff_left = abs(data[mid - 1] - target)
if min_dff_left < min_dff_right:
min_diff = min_dff_left
closest_num = data[mid - 1]
if min_dff_right < min_dff_left:
min_diff = min_dff_left
closest_num = data[mid + 1]
if data[mid] < target:
low = mid + 1
elif data[mid] > target:
high = mid - 1
else:
return data[mid]
return closest_num
s = [1, 2, 3, 6, 7, 8, 11]
print(closest_number(s, 9))
# find fixed point at a distinct sorted array
def fixed_point(s1):
low = 0
high = len(s1) - 1
while low <= high:
mid = (low + high) // 2
if s1[mid] < mid:
low = mid + 1
elif s1[mid] > mid:
high = mid - 1
elif s1[mid] == mid:
return s1[mid]
return None
s2 = [-1, 1, 3, 4, 5]
print(fixed_point(s2))
# find bitonic peak
def find_highest_number(A):
low = 0
high = len(A)-1
if len(A) < 3:
return None
while low<= high:
mid = (low + high)//2
mid_left = A[mid-1] if mid > 1 else float('-inf')
mid_right = A[mid+1] if mid +1 < len(A) else float('-inf')
if mid_left< A[mid] and A[mid] < mid_right:
low = mid + 1
elif mid_left > A[mid] and A[mid] > mid_right:
high = mid -1
elif mid_left < A[mid] and A[mid] > mid_right:
return A[mid]
A = [1,2,3,4,3,2,1]
print(find_highest_number(A))
import bisect
# bisect method
# built-in version of python
A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401]
print(bisect.bisect_left(A, -10))
# first occurence of 285
print(bisect.bisect_left(A, 285))
# index after element
print(bisect.bisect_right(A, 285))
# insert number in a certain order
bisect.insort_left(A, -10)
print(A)
# integer square root
k = 300
def integer_square_root(k):
low = 0
high = k
while low <= high:
mid = (low+high)//2
if mid*mid <= k:
low = mid + 1
else:
high = mid - 1
return low - 1
print(integer_square_root(300))
# cyclical sorted list
A = [4, 5, 6, 7, 1, 2, 3]
def find_cyclical_list(A_):
low = 0
high = len(A_)-1
while low < high:
mid = (low + high)//2
if A_[mid] > A_[high]:
low = mid + 1
elif A_[mid] <= A_[high]:
high = mid
return low
print(find_cyclical_list(A))
|
a8d77aa92095f20ee41157e21c21ce81e59ca2b5 | sunnyyeti/Leetcode-solutions | /493 Reverse Pairs_MergeSort_BIT.py | 1,186 | 3.578125 | 4 | # Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
# You need to return the number of important reverse pairs in the given array.
# Example1:
# Input: [1,3,2,3,1]
# Output: 2
# Example2:
# Input: [2,4,3,5,1]
# Output: 3
# Note:
# The length of the given array will not exceed 50,000.
# All the numbers in the input array are in the range of 32-bit integer.
import bisect
class Solution:
def reversePairs(self, nums: List[int]) -> int:
self.ans = 0
sorted_nums = sorted(set(nums))
inds_map = {e:i for i,e in enumerate(sorted_nums)}
bit = [0]*(len(inds_map)+1)
for e in reversed(nums):
t = e/2
ind = bisect.bisect_left(sorted_nums,t)
self.ans += self.get_sum_to(bit,ind-1)
self.add_delta_to(bit,inds_map[e],1)
return self.ans
def get_sum_to(self, bit, ind):
ind+=1
ans = 0
while ind>0:
ans += bit[ind]
ind -= ind&(-ind)
return ans
def add_delta_to(self,bit,ind,delta):
ind+=1
while ind<len(bit):
bit[ind]+=delta
ind+=ind&(-ind) |
dbe56dfff93c189916655272ba1e7cf9807c8214 | 824zzy/Leetcode | /A_Basic/String/L0_1805_Number_of_Different_Integers_in_a_String.py | 312 | 3.703125 | 4 | """ https://leetcode.com/problems/number-of-different-integers-in-a-string/
check if character is digit by `if c.isdigit():`
"""
class Solution:
def numDifferentIntegers(self, word: str) -> int:
word = ''.join([c if c.isdigit() else ' ' for c in word])
return len(set(map(int, word.split()))) |
0c520ffed9ddd6b62d29d1a4356a44e4cda99f4e | GitFiras/CodingNomads-Python | /03_more_datatypes/1_strings/03_01_replace.py | 446 | 4.40625 | 4 | '''
Write a script that takes a string of words and a symbol from the user.
Replace all occurrences of the first letter with the symbol. For example:
String input: more python programming please
Symbol input: #
Result: #ore python progra##ing please
'''
words = input("Please write a number of words, separated by commas ")
symbol = input("Please insert 1 symbol of choice ")
words2 = words[0] + words[1:].replace(words[0], "*")
print(words2)
|
0ec1a804791046dfe0bc7b6e9544518bc34b18a7 | vkd8756/Python | /array/encrypt.py | 747 | 3.515625 | 4 | class Crypto:
def __init__(self,str1,encrypt=[]):
self.str1=str1
self.encrypt=[0]*26
j=4
for i in range(26):
if j+97>122:
j=0
self.encrypt[i]=chr(j+97)
j+=1
#print(self.encrypt)
def encryption(self):
a=list(self.str1)
#print(a)
b=[]
for i in a:
if not i!=" ":
b.append(" ")
continue
c=abs(ord(i)-97)
b.append(self.encrypt[c])
return "".join(b)
def __str__(self):
return "{}".format(self.encryption())
str2="my name is vivek"
c1=Crypto(str2)
#c1.encryption("my name is vivek")
print(str2)
print(c1)
|
1c6a3b08bccd7d8f88ce82276d24c2c20bc98fce | nafSadh/py | /arith/phrase_num.py | 1,137 | 3.90625 | 4 | import sys
words = [
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
]
tens = ["", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"]
def phrase_num(n):
def triplets(num, mod, phrase):
m = num%mod
return phrase_num(int(num/mod))+' '+phrase+ (' '+phrase_num(m) if m > 0 else '')
if n==0: return "zero"
if 0 < n < 20: return words[n]
if 20<= n < 100:
m = n%10
return tens[int(n/10)]+ ('-'+words[m] if m>0 else '')
if 100<= n < 1000:
m = n%100
return words[int(n/100)]+' hundred' + (' '+phrase_num(m) if m > 0 else '')
if 1000<= n < 1000**2: return triplets(n, 1000, "thousand")
if 1000**2<= n < 1000**3: return triplets(n, 1000**2, "million")
if 1000**3<= n < 1000**4: return triplets(n, 1000**3, "billion")
if 1000**4<= n < 1000**5: return triplets(n, 1000**4, "trillion")
return triplets(n, 1000**5, "trillion")
if __name__ == '__main__':
print(phrase_num(int(sys.argv[1])))
|
597c70f4beebbbc7a5c31d3bcbbac0f9786523ce | warleyzee/python | /lista/zip_zipLongest.py | 845 | 3.5625 | 4 | """
ZIP - Unindo Interáveis
ZIP_LONGEST - Itertools
"""
from itertools import zip_longest, count
#Criar um indice automatico
indice = count()
"""
Código
"""
cidade = ['São Paulo', 'Belo Horizonte', 'Salvador', 'Monte Belo', 'Outra']
"""
Mais Código
"""
estado = ['SP', 'MG', 'BA']
"""
Mais Código
"""
siglas = ['SP', 'BH', 'SV', 'MB', 'Ot']
#Zip reuni todas as lista contando a menor lista, neste caso a lista de estados
cidade_estado = zip(indice, cidade, siglas, estado)
for indice, cidade, siglas, estado in cidade_estado:
print(indice, cidade, siglas, estado)
print("IMPRIMIR LISTA COMPLETA")
#zip_longuest imprime toda as listas, onde estiver vazio fica com o valor NONE a menos que user fillvalue,
cidade_estado_siglas = zip_longest(cidade, siglas, estado, fillvalue='Estados')
print(list(cidade_estado_siglas)) |
1e9f49d4a1fa38e5f883e28dc83bda1ec6cf0035 | cesslab/mazegame | /experiment/maze_game.py | 3,414 | 3.5 | 4 | import random
from typing import List
class Maze:
def __init__(self, name: str, start_x: int, start_y: int, end_x: int, end_y: int):
self.name = name
self.start_x = start_x
self.start_y = start_y
self.end_x = end_x
self.end_y = end_y
class MazeCollection:
def __init__(self):
self.mazes = [
Maze('20_100_1', 147, 2, 169, 314),
# Maze('20_100_2', 147, 2, 169, 314),
# Maze('20_100_3', 147, 2, 169, 314),
# Maze('20_100_4', 147, 2, 169, 314),
# Maze('20_100_5', 147, 2, 169, 314),
Maze('40_40_1', 147, 2, 169, 314),
Maze('40_40_2', 147, 2, 169, 314),
# Maze('40_40_3', 147, 2, 169, 314),
# Maze('40_40_4', 147, 2, 169, 314),
# Maze('40_40_5', 147, 2, 169, 314),
Maze('40_60_1', 147, 2, 169, 314),
Maze('40_60_2', 147, 2, 169, 314),
# Maze('40_60_3', 147, 2, 169, 314),
# Maze('40_60_4', 147, 2, 169, 314),
# Maze('40_60_5', 147, 2, 169, 314),
Maze('50_50_1', 147, 2, 169, 314),
Maze('50_50_2', 147, 2, 169, 314),
# Maze('50_50_3', 147, 2, 169, 314),
# Maze('50_50_4', 147, 2, 169, 314),
# Maze('50_50_5', 147, 2, 169, 314),
Maze('60_40_1', 147, 2, 169, 314),
Maze('60_40_2', 147, 2, 169, 314),
# Maze('60_40_3', 147, 2, 169, 314),
# Maze('60_40_4', 147, 2, 169, 314),
# Maze('60_40_5', 147, 2, 169, 314),
# Maze('60_60_1', 147, 2, 169, 314),
# Maze('60_60_2', 147, 2, 169, 314),
# Maze('60_60_3', 147, 2, 169, 314),
# Maze('60_60_4', 147, 2, 169, 314),
Maze('60_60_5', 147, 2, 169, 314),
# Maze('100_20_1', 147, 2, 169, 314),
# Maze('100_20_2', 147, 2, 169, 314),
# Maze('100_20_3', 147, 2, 169, 314),
# Maze('100_20_4', 147, 2, 169, 314),
# Maze('100_20_5', 147, 2, 169, 314),
# Maze('easy1', 147, 2, 169, 314),
# Maze('easy2', 147, 2, 169, 314),
# Maze('easy3', 147, 2, 169, 314),
# Maze('easyM1', 147, 2, 169, 314),
# Maze('easyM2', 147, 2, 169, 314),
# Maze('easyM3', 147, 2, 169, 314),
# Maze('hard1', 147, 2, 169, 314),
# Maze('hard2', 147, 2, 169, 314),
# Maze('hard3', 147, 2, 169, 314),
# Maze('hardV1', 147, 2, 169, 314),
# Maze('hardV2', 147, 2, 169, 314),
# Maze('hardV3', 147, 2, 169, 314),
# Maze('medium1', 147, 2, 169, 314),
# Maze('medium2', 147, 2, 169, 314),
# Maze('medium3', 147, 2, 169, 314)
]
random.shuffle(self.mazes)
self.rounds = len(self.mazes)
def maze(self, round_number: int) -> Maze:
return self.mazes[round_number - 1]
def num_mazes(self) -> int:
return len(self.mazes)
def maze_ids(self) -> List[str]:
return [maze.name for maze in self.mazes]
class Participant:
@staticmethod
def get_maze_collection(player) -> MazeCollection:
return player.participant.vars['maze_collection']
@staticmethod
def set_maze_collection(player, maze_collection: MazeCollection):
player.participant.vars['maze_collection'] = maze_collection
|
05422d10f392834e00dd24ecf98a5ff6ce2b6d2f | Arnoldj2/Python-Projects | /File_Transfer_Project/File_Transfer_3.py | 2,641 | 3.515625 | 4 | from tkinter import *
import tkinter as tk
from tkinter import filedialog
import os
from datetime import *
import os.path, time
import shutil
class ParentWindow(Frame): # Tkinter frame class
def __init__(self, master, *args, **kwargs):
Frame.__init__(self, master, *args, **kwargs)
# define our master frame configuration
self.master = master
self.master.minsize(500,300)
self.master.maxsize(700,500)
self.master.title("File Copy")
self.lbl1 = tk.Entry(self.master) #displays selected file path obtain from "button1"
self.lbl1.grid(row=0, columnspan=5)
self.button1 = Button(text="Source Folder",command=self.browse_button_1) # uses func "browse_button_1" which asks the user to input the directory
self.button1.grid(row=0, column=8)
self.lbl2 = tk.Entry(self.master) #displays selected file path obtain from "button2"
self.lbl2.grid(row=2, columnspan=5)
self.button2 = Button(text="Destination Folder",command=self.browse_button_2) # uses func "browse_button_2" which asks the user to input the directory
self.button2.grid(row=2, column=8)
self.button3 = Button(self.master, text="Initiate File Check ",comman=self.transfer)
self.button3.grid(row=4, column=4)
def browse_button_1(self):
filename = filedialog.askdirectory() #obtains directory
self.lbl1.insert(0,filename) #assigns value to lbl1
def browse_button_2(self):
filename1 = filedialog.askdirectory() #obtains directory
self.lbl2.insert(0,filename1) #assigns value to lbl2
def transfer(self):
source = self.lbl1.get() # get() to pull file path
destination = self.lbl2.get() # get() to pull file path
files = os.listdir(source)
for i in files:
modifyTime = os.path.getmtime(source + "/" + i) # Returns the time of last modification for all files in the source folder.
modifyDate = datetime.fromtimestamp(modifyTime)#.strftime('%Y-%m-%d') to convert to a formated string
todaysDate = datetime.today() # current date
DateLimit = todaysDate - timedelta(days=1) # If modified within last 24 hours
if modifyDate > DateLimit : # If the file was edited less then 24 hours ...
shutil.copy(source + "/" + i, destination) # ... copy file
if __name__ == "__main__":
root = tk.Tk()
App = ParentWindow(root)
root.mainloop()
|
669bba65e007052c8782432798a59803a4942341 | cybelewang/leetcode-python | /code990SatisfiabilityOfEqualityEquations.py | 2,288 | 4.1875 | 4 | """
990 Satisfiability of Equality Equations
Given an array equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b". Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.
Example 1:
Input: ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second. There is no way to assign the variables to satisfy both equations.
Example 2:
Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.
Example 3:
Input: ["a==b","b==c","a==c"]
Output: true
Example 4:
Input: ["a==b","b!=c","c==a"]
Output: false
Example 5:
Input: ["c==c","b==d","x!=z"]
Output: true
Note:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] and equations[i][3] are lowercase letters
equations[i][1] is either '=' or '!'
equations[i][2] is '='
"""
class Solution:
# my union find solution
def equationsPossible(self, equations):
"""
:type equations: list[str]
:rtype: bool
"""
root = list(range(26))
def find(x):
"""
union find
"""
while root[x] != x:
x = root[x]
return x
# parse equations
equal, not_equal = [], []
for e in equations:
a, b = ord(e[0]) - ord('a'), ord(e[3]) - ord('a')
if e[1] == '=':
equal.append((a, b))
else:
not_equal.append((a, b))
# union those equals together
for a, b in equal:
ra, rb = find(a), find(b)
root[ra] = rb
# now check those non-equals
for a, b in not_equal:
ra, rb = find(a), find(b)
if ra == rb:
return False
return True
equations = ["a==b","b!=c","c==a"]
print(Solution().equationsPossible(equations)) |
817418f96e93c9d9fc239b0560c19fc82d6bf611 | Aasthaengg/IBMdataset | /Python_codes/p02419/s376849379.py | 163 | 3.53125 | 4 | w = input()
t = []
while True:
temp = input()
if temp == 'END_OF_TEXT':
break
else:
t += [s.strip(',.') for s in temp.lower().split(' ')]
print(t.count(w)) |
95cbb5c8705d31f801db363a9df3e307bc215d3b | EdisonZhu33/Algorithm | /备战2020/052-二叉树的最大最小深度.py | 2,251 | 4.125 | 4 | """
@file : 052-二叉树的最大最小深度.py
@author : xiaolu
@time : 2020-02-25
"""
from typing import List
class TreeNode(object):
""" Definition of a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
# 后续遍历构造二叉树
def helper(in_left, in_right):
# 没有元素构造节点
if in_left > in_right:
return None
# 取最后一个元素构造节点
val = postorder.pop()
root = TreeNode(val)
# 然后在中序遍历中分割
index = idx_map[val]
# 建立右子树
root.right = helper(index + 1, in_right)
# 建立左子树
root.left = helper(in_left, index - 1)
return root
idx_map = {val: idx for idx, val in enumerate(inorder)}
return helper(0, len(inorder) - 1)
def maxDepth(self, root):
'''
最大深度
:param root: 根节点
:return:
'''
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
def minDepth(self, root):
'''
最小深度
:param root:
:return:
'''
if not root:
return 0
children = [root.left, root.right]
# 代表没有任何孩子
if not any(children):
return 1
min_depth = float('inf')
for c in children:
if c:
min_depth = min(self.minDepth(c), min_depth)
return min_depth + 1
if __name__ == '__main__':
# 首先构造二叉树
# 中序遍历
inorder = [9, 3, 15, 20, 7]
# 后序遍历
postorder = [9, 15, 7, 20, 3]
sol = Solution()
root = sol.buildTree(inorder, postorder)
depth = sol.maxDepth(root)
print('二叉树的最大深度为:', depth)
depth = sol.maxDepth(root)
print('二叉树的最小深度为:', depth)
|
23aedb0f4162872f656c7f1ba65a4b760d5f6c87 | Flutflut/Dictionary_Examples | /printdict.py | 492 | 3.890625 | 4 | import json
#Open the dictionary file
dictfile = open('dictionary.json',)
#load the dictionary file into a database
database = json.load(dictfile)
#Close the file now that I am done with it
dictfile.close()
# for each entry in the dictionary
for entry in database:
print("========================\n")
#print the entry
print(entry)
#get the definition of for the entry
definition = database[entry]
#print the definition
print(definition)
|
9c98fceb8962a15c428845244820b48eee2d001b | kasamdh/python | /swap.py | 605 | 4 | 4 | '''
Implement function swapFL() that takes a list as input and swaps the first and last elements of the list.
You may assume the list will be nonempty.
The function should not return anything.
>>> ingredients = ['flour', 'sugar', 'butter', 'apples']
>>> swapFL(ingredients)
>>> ingredients
['apples', 'sugar', 'butter', 'flour']
'''
def swapFL(ingredients):
ingredientFirst=ingredients[0]
ingredientLast=ingredients[-1]
ingredients[0]= ingredientLast
ingredients[-1]=ingredientFirst
return(ingredients)
ingredients = ['flour', 'sugar', 'butter', 'apples']
print(swapFL(ingredients))
|
caaa87f7045a7552926a4a704050679f375b69f4 | rai-roshan/beautifulsoup_web_scarping | /csv_r_W/read_csv.py | 620 | 3.921875 | 4 | import csv
with open('names.csv','r') as f: #filehandling open file as f
csv_f=csv.reader(f) #convert file f in csv file object
#next(csv_f) #skip the first list ['.....','......','.........']
#for line in csv_f:
# print(line)
# print(line[0],line[1],line[2]) #we have to use index
#writing a csv file
with open('new_names.csv','w') as new_f:
csv_write=csv.writer(new_f,delimiter='#') #csv file object !! delimeter is used to seprate data in a row
for line in csv_f:
csv_write.writerow(line) #object of csv file.method
|
cc9ee4ee85f49cb743c47c4f353f4a92ae4a4973 | pm0824/June-Leetcoding-Challenge-2020 | /Find_The_Duplicate_Number.py | 1,173 | 4.03125 | 4 | '''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
'''
#Solution: Visit https://leetcode.com/articles/find-the-duplicate-number/
class Solution:
def findDuplicate(self, nums):
# Find the intersection point of the two runners.
tortoise = hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
# Find the "entrance" to the cycle.
tortoise = nums[0]
while tortoise != hare:
tortoise = nums[tortoise]
hare = nums[hare]
return hare
|
dc1857b9442e55fec5fab0f6de8238874a768b33 | jagnoor/python-challenge | /PyBank/Resources/PyBank.py | 2,964 | 4.09375 | 4 |
# Python Homework - Py Me Up, Charlie - PyBank
# Import Modules/Dependencies
import os
import csv
# Variables
month = 0
amount = 0
change = []
month_count = []
increase = 0
increase_month = 0
decrease = 0
decrease_month = 0
# Set Path For File
PyBankPath = os.path.join('.', 'PyBank', 'Resources', 'budget_data.csv')
# Open & Read CSV File
with open(PyBankPath, newline='') as csvfile:
# CSV Reader Specifies Delimiter & Variable That Holds Contents
PyBankReader = csv.reader(csvfile, delimiter=',')
csv_header = next(PyBankReader)
row = next(PyBankReader)
# Calculate Total Number Of Months, Net Amount Of "Profit/Losses" & Set Variables For Rows
previous_row = int(row[1])
month += 1
amount += int(row[1])
increase = int(row[1])
increase_month = row[0]
# Read Each Row Of Data After The Header
for row in PyBankReader:
# Calculate Total Number Of Months Included In Dataset
month += 1
# Calculate Net Amount Of "Profit/Losses" Over The Entire Period
amount += int(row[1])
# Calculate Change From Current Month To Previous Month
revenue_change = int(row[1]) - previous_row
change.append(revenue_change)
previous_row = int(row[1])
month_count.append(row[0])
# Calculate The Greatest Increase
if int(row[1]) > increase:
increase = int(row[1])
increase_month = row[0]
# Calculate The Greatest Decrease
if int(row[1]) < decrease:
decrease = int(row[1])
decrease_month = row[0]
# Calculate The Average & The Date
average_change = sum(change) / len(change)
highest = max(change)
lowest = min(change)
# Print Analysis
print(f"Financial Analysis")
print(f"--------Done by JAG-------------------")
print(f"Total Months: {month}")
print(f"Total: ${amount}")
print(f"Average Change: ${average_change:.2f}")
print(
f"Greatest Increase in Profits:, {increase_month}, (${highest})")
print(f"Greatest Decrease in Profits:, {decrease_month}, (${lowest})")
print(f"-----------------------------------------")
# Specify File To Write To
output_file = os.path.join('.', 'PyBank', 'Resources',
'budget_data_revised.text')
# Open File Using "Write" Mode. Specify The Variable To Hold The Contents
with open(output_file, 'w',) as txtfile:
# Write New Data in the text file
# #TODO Take a screenshot for readme File
txtfile.write(f"Financial Analysis\n")
txtfile.write(f"--------Done by JAG -------------------\n")
txtfile.write(f"Total Months: {month}\n")
txtfile.write(f"Total: ${amount}\n")
txtfile.write(f"Average Change: ${average_change}\n")
txtfile.write(
f"Greatest Increase in Profits:, {increase_month}, (${highest})\n")
txtfile.write(
f"Greatest Decrease in Profits:, {decrease_month}, (${lowest})\n")
txtfile.write(f"---------------------------\n")
|
027d7adb29a53a376a109fa1a4dc70e83a329eea | avalliere/swap-meet | /swap_meet/vendor.py | 1,840 | 3.5 | 4 | class Vendor:
def __init__(self, inventory=[]):
self.inventory = inventory
def add(self, item):
self.inventory.append(item)
return item
def remove(self, item):
if item not in self.inventory:
return False
self.inventory = [
thing for thing in self.inventory if thing != item
]
return item
def get_by_category(self, category):
category_items = [
item for item in self.inventory if item.category == category
]
return category_items
def swap_items(self, other_vendor, my_item, their_item):
if my_item not in self.inventory or their_item not in other_vendor.inventory:
return False
other_vendor.remove(their_item)
self.remove(my_item)
other_vendor.add(my_item)
self.add(their_item)
return self.inventory
def swap_first_item(self, other_vendor):
if len(self.inventory) == 0 or len(other_vendor.inventory) == 0:
return False
my_item = self.inventory[0]
their_item = other_vendor.inventory[0]
return self.swap_items(other_vendor, my_item, their_item)
def get_best_by_category(self, category):
category_items = self.get_by_category(category)
if len(category_items) == 0:
return None
best_condition = 0
for item in category_items:
if item.condition > best_condition:
best_condition = item.condition
best_item = item
return best_item
def swap_best_by_category(self, other, my_priority, their_priority):
their_best = other.get_best_by_category(my_priority)
my_best = self.get_best_by_category(their_priority)
return self.swap_items(other, my_best, their_best)
|
cd3185fb5029b4d1f8bdaa9231ae59a5a0efd3db | AnaTrzeciak/Curso_Python | /3-Looping/tabuleiro.py | 274 | 4 | 4 | #ecoding:utf-8
#Loop dentro de loop
#Tabuleiro NxN
print("Vamos criar um tabuleiro de tamanho NxN.")
n= int(input("Digite N (tamanho do tabuleiro):"))
for linha in range(n):
for coluna in range(n):
print("x ",end= '')
print() #quebra de linha
|
bc89d28e19ca5761c98e7e6887837a2ea8a90ad7 | gagande90/Data-Structures-Python | /Sets/sets1.py | 1,670 | 4.1875 | 4 | number_set = {1, 2, 3, 4} # sets use curly braces for creation
letter_set = {'a', 'b', 'c', 'd'}
mixed_set = {1, 'a', 2, (1, 2, 3)} # types must be "hashable", i.e. immutable
empty_set = set() # have to use the set() function, cannot use = {}
print(number_set)
print(letter_set)
print(mixed_set)
print(empty_set) # returns: set(). {} would be a dict, not a set
print(type(number_set)) # <class 'set'>
###
number_set_unique = {1, 2, 3, 4, 2, 3, 4} # sets only store unique values
print()
print(number_set_unique) # {1, 2, 3, 4}, ignores dupes
###
number_set.add(5) # add an item to the set
print()
print(number_set)
###
print()
print()
number_set.add(4) # try to add existing item to the set
number_set.add(5) # try to add existing item to the set
print(number_set) # no duplicates, nothing got added
###
print()
print()
number_set.remove(1) # remove an item from the set
print(number_set)
###
print()
print()
try: # if the item is not in the set
number_set.remove(3) # KeyError: 98
print("Test worked fine! Cool!! Move Ahead!!!")
except Exception as e:
print('** caught Exception:', e)
###
### # use the 'in' keyword
print()
print()
if (98 in number_set):
print("Yes, its there!")
else:
print("Nope, its not there!")
|
3e51500a4051bef24af3a074352a7485a3bde501 | hotheat/LeetCode | /098. Validate Binary Search Tree/recur.py | 568 | 3.5 | 4 | from collections import deque
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
else:
return self.helper(None, root, None)
def helper(self, minv, root, maxv):
if root is None:
return True
if (minv is not None and root.val < minv) or (maxv is not None and root.val > maxv):
return False
left = self.helper(minv, root.left, root.val - 1)
right = self.helper(root.val + 1, root.right, maxv)
return left and right |
9cd42b86cae256361425411a230ef5f21836fbd6 | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/ncbden001/question4.py | 657 | 4.1875 | 4 | import math
lower = eval(input("Enter the starting point N: \n"))
upper = eval(input("Enter the ending point M: \n"))
print("The palindromic primes are:")
def prime(n):
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(math.sqrt(n))+1, 2):
if n % x == 0:
return False
return True
for j in range(lower+1,upper):
forwards = str(j)
backwards = forwards[::-1]
checker = prime(j)
if forwards == backwards and checker == True : print(forwards)
|
4d06b383051957bc4ff42b9a10378675e70610ee | jonowadsworth/Crash-Dictionaries | /Dict_test.py | 1,205 | 4.3125 | 4 | # Nesting a dictionary within a list.
# Syntax seems to be:
# dict
# dict
# dict
#list[dict1, dict2,dict3] etc
alien_0 = {'Colour': 'Green', 'Points': 10}
alien_1 = {'Colour': 'Yellow', 'Points': 5}
alien_2 = {'Colour': 'Red', 'Points': 15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
# More realistically, get the program to create the aliens for you
# first, make an empty LIST for storing the aliens:
aliens_list = []
# Now make 30 aliens using range()
for alien_number in range(30): #simple range call for 20 of whatever code comes now
new_alien = {'Colour': 'Green', 'Points': 10} # create a dictionary and give it these characteristics
aliens_list.append(new_alien) # update the blank aliens_list 30 times in this loop with the new dict
# of the new alien we created above.
#show the first 5 aliens
for alien in aliens_list[:5]:
print(alien)
print("...")
# to confirm number of created aliens, use LEN to get the length of a list as usual
print(f"The total number of aliens loose is: {len(aliens_list)}")
for eyeball in range(10):
print("EyeBall ten four!")
print("This is a github test, newlines added for merge test")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.