blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
e85bc40354408e448f8c81f726e7e0756a3dd060 | jm-sas/sims | /fox_and_rabbits.py | 2,432 | 3.828125 | 4 | #fox and rabbits
import turtle
import random
#initalizes the food
#you could combine this with foxes and rabbits
def seed_plants(num_plants):
plants = []
for i in range(num_plants):
plants.append(turtle.Turtle())
for plant in plants:
x = random.randint(-460,460)
y = random.randint(-400,400)
plant.penup()
plant.color('green')
plant.shape('circle')
#make the food smaller
plant.shapesize(0.5,0.5,0.5) #default is 1,1,1
plant.goto(x,y)
#plants grow over time
#def grow():
#seeking behavior towards rabbits
#def foxes():
#seeks plants, runs from foxes
#def rabbits():
#I'm still fuzzy on how to get functions to interact
#rabbit.health() = 100
#if it eats a plant
#rabbit.health() += 25 or whatever
#if rabbit.health() == 0:
# death
#def run():
def fox_and_rabbits():
screen = turtle.Screen()
screen.bgcolor('black')
screen.tracer(0)
num_plants = 20
#num_rabbits
#num_foxes
seed_plants(num_plants)
rabbit = turtle.Turtle()
rabbit.penup()
rabbit.color('blue')
x = random.randint(-460,460)
y = random.randint(-400,400)
rabbit.goto(x,y)
while True: #this needs to get turned into a function
screen.tracer(0)
rabbit.dx = random.randint(-5,5)
rabbit.dy = random.randint(-5,5)
rabbit.da = random.randint(-10,10)
rabbit.rt(rabbit.da)
rabbit.setx(rabbit.xcor() + rabbit.dx)
rabbit.sety(rabbit.ycor() + rabbit.dy)
if rabbit.ycor() < -400:
rabbit.sety(-400) #prevents it from going out of bounds
rabbit.dy *= -1
rabbit.da = random.randint(-10,10)
rabbit.rt(rabbit.da)
elif rabbit.ycor() > 400:
rabbit.sety(400)
rabbit.dy *= -1
rabbit.da = random.randint(-10,10)
rabbit.rt(rabbit.da)
if rabbit.xcor() > 460:
rabbit.setx(460)
rabbit.dx *= -1
rabbit.da = random.randint(-15,15)
rabbit.rt(rabbit.da)
elif rabbit.xcor() < -460:
rabbit.setx(-460)
rabbit.dx *= -1
rabbit.da = random.randint(-15,15)
rabbit.rt(rabbit.da)
screen.update()
turtle.done()
if __name__ == "__main__":
fox_and_rabbits()
|
04db2a7794d22229705ec77c8dce6b6c9b25bcec | bigeast/ProjectEuler | /(#386)Antichains.py | 3,263 | 3.703125 | 4 | def Primes(a):
sieve=[True]*(a+1)
sieve[:2]=[False, False]
sqrt=int(a**.5)+1
for x in range(2, sqrt):
if sieve[x]:
sieve[2*x::x]=[False]*(a/x-1)
return sieve
b=20
primes=Primes(b)
print "done"
def factor():
sieve=[0]*(b+1)
sieve2=[0]*(b+1)
sieve[:2]=[0,1]
for x in xrange(2, len(sieve)):
if primes[x]:
for y in xrange(x,len(sieve),x):
sieve[y]+=1
for x in xrange(2,int(len(sieve)**.5)+1):
if primes[x]:
for y in xrange(x**2,len(sieve),x**2):
sieve2[y]+=1
return sieve, sieve2
def factorize():
sieve=[[]]*(b+1)
for x in xrange(2,len(sieve)):
if primes[x]:
sieve[x]=[x]
print sieve
for x in xrange(2,len(sieve)):
print x
if primes[x]:
count=2
for y in xrange(x*2,len(sieve),x):
#sieve[y]=sieve[y]+[x]
add=[x,count]
print y, count
if not primes[count]
sieve[y]=sieve[y]+sieve[count]
count+=1
return sieve
print factorize()
tris=[1,2,3]
def tri(x):
if x>len(tris):
tris.append((x-1)*x/2)
return (x-1)*x/2
return tris[x-1]
def main():
total=0
f,f2=factor()
print "done"
for x in xrange(1,len(f)):
y=f[x]
z=f2[x]
#print y
'''if z>3:
print x, tri(y), z'''
if y==1:
total+=1
#print x, y, z, 1, total
elif y==2 and z==2:
total+=3
#print x, y, z, 3, total
elif y==2 and z==1:
total+=2
#print x, y, z, 2, total
else:
total+=tri(y)
#print x, y, z, tri(y)+z, total
total+=z
if x==10000:
print x, y, tri(y),z, total
if x==2*2*3*5*7*11:
print x, y, tri(y), z
#print x, y, z, tri(y)+z, total
print total, x
main()
def factor2(x):
a=set([1])
if x%2==0:
for y in range(2,int(x**.5+1)):
if x%y==0:
a.add(y)
a.add(x/y)
a=list(a)
a.sort()
return a
else:
for y in range(3,int(x**.5+1),2):
if x%y==0:
a.add(y)
a.add(x/y)
return a
return a
f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]
def checkSubs(n):
a=factor2(n)
#print a
for x in reversed(f(a)):
b=False
for y in x:
for z in x:
if y!=z:
if y%z==0:
b=True
if b==True:
break
if b==False:
#print x
return x
return 0
def main2(a):
global primes
p=Primes(a)
total=0
for x in range(len(p)):
if p[x]:
primes.append(x)
for x in range(1,a+1):
total+=len(checkSubs(x))
#print "x: ",x, "S(x): ", checkSubs(x), "factors: ",factor(x), "length: ",len(factor(x))
print "x: ", x, "S(x): ", len(checkSubs(x)), checkSubs(x)
print total
#main2(100)
#print factor2(44100)
|
8d3e1765fa316597ec67ff691b91fbf695be8e4b | aa-software2112/SOEN_344 | /uber_sante/utils/date.py | 1,922 | 3.96875 | 4 | import datetime
from enum import Enum
class DateEnum(Enum):
JANUARY = 1
FEBRUARY = 2
MARCH = 3
APRIL = 4
MAY = 5
JUNE = 6
JULY = 7
AUGUST = 8
SEPTEMBER = 9
OCTOBER = 10
NOVEMBER = 11
DECEMBER = 12
"""
Helper class responsible for maintaining date-based functionality, and can
be modified to include greater customization as project progresses and demands it
"""
class Date:
# Index corresponds to that returned by
# datetime.date(yyyy,mm,dd).weekday()
get_day_of_week_name = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
# Month - 1 = index to name of Month
get_month_name = ["January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December"]
def __init__(self, year, month, day = None):
self.day = day
self.month = month.value if type(month) == type(DateEnum.JANUARY) else month
self.year = year
self.day_name = None
self.month_name = Date.get_month_name[int(self.month)-1]
if self.day is not None:
self.day_name = Date.get_day_of_week_name[datetime.date(self.year, self.month, self.day).weekday()]
def get_day(self):
return self.day
def get_day_name(self):
return self.day_name
def get_month(self):
return self.month
def get_year(self):
return self.year
def get_date_string(self):
if self.day_name is not None:
return "{}, {} of {}, {}".format(self.day_name, self.day,
self.month_name, self.year)
else: # Day was not provided - month only
return "{} {}".format(self.month_name, self.year)
if __name__ == "__main__":
print(Date(2019,2,13).get_date_string()) |
c5aabdc995789d0f931a38493b8b6e55013158de | Ravik27280/Algorithms-problems | /Data Structure/rightRotation.py | 355 | 3.84375 | 4 | # def rightRotatio(arr,d,n):
# for i in range(d):
# rightRotatiobyOne(arr,n)
def rightRotatiobyOne(arr,n):
temp=arr[n-1]
for i in range(n-1,0,-1):
arr[i]=arr[i-1]
arr[0]=temp
def printArray(arr,size):
for i in range(size):
print(arr[i],end=' ')
arr=[1,2,3,4,5,6,7]
rightRotatiobyOne(arr,7)
printArray(arr,7) |
7687493b02a7a8921818a88db204909db90fe10e | Urvashi-91/Urvashi_Git_Repo | /Interview/Amazon/primeNumber.py | 909 | 4.3125 | 4 | # A school method based Python3 program
# to check if a number is prime
# function check whether a number
# is prime or not
def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
# Driver Code
if isPrime(11):
print("true")
else:
print("false")
# This code is contributed by Sachin Bisht
'''
Recursion
'''
# Python3 program to check whether a number
# is prime or not using recursion
# Function check whether a number
# is prime or not
def isPrime(n, i):
# Corner cases
if (n == 0 or n == 1):
return False
# Checking Prime
if (n == i):
return True
# Base cases
if (n % i == 0):
return False
i += 1
return isPrime(n, i)
# Driver Code
if (isPrime(35, 2)):
print("true")
else:
print("false")
# This code is contributed by bunnyram19
|
3460e4d606dd6cfb4a55ed56f43caed3ca57a7a8 | skyyalexander/simplecalc | /SimpleCalc.py | 2,182 | 4.3125 | 4 | ###########################################################################
# SimpleCalc Ver. 1.0 - Created by Skyy Alexander #
###########################################################################
# A console application that can be used to perform basic arithmetic #
# On GitHub as salex11 @ https://github.com/salex11 #
###########################################################################
# Asks user for two values and the mathematical operation they want to use
def valueQuery():
value1 = float(input("What is the first value you want to do math with?: "))
operation = str(input("What is the operation you'd like to perform? (+, -, *, /): "))
value2 = float(input("What is the second value you want to do math with?: "))
return value1, operation, value2;
# Performs the desired operation and prints the answer
def calculate():
value1, operation, value2 = valueQuery()
if operation == "+":
answer = value1 + value2
elif operation == "-":
answer = value1 - value2
elif operation == "*":
answer = value1 * value2
elif operation == "/":
answer = value1 / value2
else:
answer = "ERROR - check to make sure your inputs were valid."
print("The answer is: %s" % answer)
return;
# Asks user if they would like to calculate something else
def reset():
resetOption = input("Would you like to calculate something else? (Y/N): ")
if resetOption == "Y" or resetOption == "y":
start = True
elif resetOption == "N" or resetOption == "n":
start = False
print("Thanks for using SimpleCalc!")
else:
start = False
print("Invalid response... quitting SimpleCalc.")
return start;
# Runs the calculator until the user quits
start = True
print("Welcome to SimpleCalc!")
while start == True:
calculate()
start = reset()
######################### THINGS TO ADD/MODIFY #########################
# 1. Spacing between text and calculations
# 2. Removal of decimal place (1.0) w/ whole numbers
# 3. Pressing a key to prompt reset()
# (i.e. "Press ENTER to calculate again or 'Q' to quit.")
|
3666d2f5e56e6f58d512705dabaafbb33041e152 | JakeColtman/Heroclix | /Game/Game/Engine/Units/UnitMap.py | 800 | 3.5 | 4 | class UnitMap:
def __init__(self, size = 5):
max_x, max_y = size, size
self.size = size
self.units = {}
def add_unit(self, id, position):
self.units[id] = position
def get_unit_position(self, id):
return self.units[id]
def is_valid_move(self, movement):
pos = movement.ending_position
unit_poses = [self.units[x] for x in self.units]
print(unit_poses)
success = pos not in unit_poses
if not success:
print("unit map")
return success
def move(self, movement):
self.units[movement.unit.id] = movement.ending_position
print(self.units[movement.unit.id])
return True
def to_json(self):
return {"size": self.size, "unit_positions": self.units} |
318566d7465d27047f18c0300c36d695b49b4cb7 | thbeca-30/Computational_Mathematics | /LabWork3/solutionMethods.py | 4,708 | 3.703125 | 4 | import math
import os
import keyboard
def newtonPolynomial(xy, x):
os.system('cls')
print("Многочлен Ньютона:")
temp = [] # Временные значения
dy = [] # Конечные разности
result = [] # Список результатов
for i in range(len(xy) - 1): # Конечные разности первого порядка заносим во временный список
temp.append(xy[i + 1][1] - xy[i][1]) # Вычисляем сами разности
dy.append(temp) # Временный список заносим в список конечных разностей
for i in range(len(xy) - 2): # На каждом новом шаге вычисляем конечные разности следующих порядков
temp = [] # Очищаем временные значения
for j in range(len(dy[i]) - 1):
temp.append(dy[i][j + 1] - dy[i][j]) # Вычисляем конечные разности
dy.append(temp) # Временный список заносим в список конечных разностей
h = xy[1][0] - xy[0][0] # Вычисляем шаг
middle = (xy[0][0] + xy[len(xy) - 1][0]) / 2 # Считаем середину отрезка иксов
for k in x: # Для каждой точки, в которой нужно найти значение, находим это значение
if k < middle: # Если xi лежит в промежутке от x0 до (x0 + xn) / 2
t = (k - xy[0][0]) / h # Вычисляем t по формуле (x - x0)/h
res = 0 # Интерполяция вперед
res += xy[0][1] # Прибавляем к результату y0 + t * dy0
res += t * dy[0][0]
for i in range(1, len(dy)): # Считаем остальное: (t * (t-1) * ... * (t - n + 1) * dny0) / n!
tmp = 1
for j in range(1, i): # Для удобства отдельно считаем (t - 1)..(t - n+1)
tmp *= (t - j)
res += tmp * t * dy[i][0] / math.factorial(i + 1) # Добавляем (t * (t-1) * ... * (t - n + 1) * dny0) / n!
result.append(res)
else:
t = (k - xy[len(xy) - 1][0]) / h # Вычисляем t по формуле (x - x0)/h
res = 0 # Интерполяция назад
res += xy[len(xy) - 1][1] # Прибавляем к результату y0 + t * dy0
res += t * dy[0][len(dy[0])-1]
for i in range(1, len(dy)): # Считаем остальное: (t * (t-1) * ... * (t - n + 1) * dny0) / n!
tmp = 1
for j in range(1, i): # Для удобства отдельно считаем (t - 1)..(t - n+1)
tmp *= (t + j)
res += t * tmp * dy[i][len(dy[i])-1] / math.factorial(i+1) # Добавляем (t * (t-1) * ... * (t - n + 1) * dny0) / n!
result.append(res)
print(result)
#keyboard.wait('\n')
#os.system('cls')
def lagrangEquitable(xy, x):
print("Лагранж равноотстоящий:")
result = [] # Список результатов
h = xy[1][0] - xy[0][0] # Считаем шаг
for k in x: # Для каждой точки, в которой нужно найти значение, находим это значение
res = 0
for i in range(len(xy)):
tmp = 1 # Временный буфер
for j in range(len(xy)):
if i != j:
tmp *= (k - xy[0][0] - j * h) / (h * (i - j)) # Считаем (Х - Хi - j * h) / (h(i - j))
res += tmp * xy[i][1]
result.append(res) # Заносим в список результатов
print(result)
#keyboard.wait('\n')
#os.system('cls')
def lagrangUnequitable(xy, x):
print("Лагранж неравноотстоящий:")
result = [] # Список результатов
for k in x: # Для каждой точки, в которой нужно найти значение, находим это значение
res = 0
for i in range(len(xy)):
tmp = 1 # Временный буфер
for j in range(len(xy)):
if i != j:
tmp *= (k - xy[j][0]) / (xy[i][0] - xy[j][0]) # Считаем (X - Xj) / (Xi - Xj)
res += tmp * xy[i][1]
result.append(res) # Заносим в список результатов
print(result)
#keyboard.wait('\n')
#os.system('cls') |
f1dabdd1f56646c1d2fa773735d2d63497014a26 | Jimut123/competitive_programming | /Code/HackerRank/InterviewPrep/sherlock_valid_String/valid_Str.py | 977 | 3.828125 | 4 | def isValid(s):
#Create a list containing just counts of each distinct element
freq = [s.count(letter) for letter in set(s) ]
#If all values the same, then return 'YES'
if max(freq)-min(freq) == 0:
return 'YES'
#If difference between highest count and lowest count is 1
#and there is only one letter with highest count,
#then return 'YES' (because we can subtract one of these
#letters and max=min , i.e. all counts are the same)
elif freq.count(max(freq)) == 1 and max(freq) - min(freq) == 1:
return 'YES'
#If the minimum count is 1
#then remove this letter, and check whether all the other
#counts are the same
elif freq.count(min(freq)) == 1:
freq.remove(min(freq))
if max(freq)-min(freq) == 0:
return 'YES'
else:
return 'NO'
else:
return 'NO'# Enter your code here. Read input from STDIN. Print output to STDOUT
s = input()
print(isValid(s))
|
4f2b23cd1b911c2aa166de18c8cd186723d193bb | divarismawan/etl_dwh | /Show_data.py | 6,445 | 3.515625 | 4 | import Connection
import Excels
import SQL
db_dimension = Connection.connect('db_dimensional_perpus')
cursor = db_dimension.cursor()
# ---------------------- Show GUI ---------------------- #
def select_month(month):
if month == "Januari":
return 1
elif month == "Februari":
return 2
elif month == "Maret":
return 3
elif month == "April":
return 4
elif month == "Mei":
return 5
elif month == "Juni":
return 6
elif month == "Juli":
return 7
elif month == "Agustus":
return 8
elif month == "September":
return 9
elif month == "Oktober":
return 10
elif month == "November":
return 11
elif month == "Desember":
return 12
def select_library(library):
if library == "Tianjin Binhai Library":
return 1
elif library == "Seattle Public Library":
return 2
elif library == "Library of Birmingham":
return 3
def select_month_int(month):
if month == 1:
return "Januari"
elif month == 2:
return "Februari"
elif month == 3:
return "Maret"
elif month == 4:
return "April"
elif month == 5:
return "Mei"
elif month == 6:
return "Juni"
elif month == 7:
return "Juli"
elif month == 8:
return "Agustus"
elif month == 9:
return "September"
elif month == 10:
return "Oktober"
elif month == 11:
return "November"
elif month == 12:
return "Desember"
def show_member(self):
member = self.m_text_member.GetValue()
sql = SQL.sql_member(member)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0, x)
y[5] = str(select_month_int(y[5]))
self.m_dataViewList_member.AppendItem(y)
def show_by_month(self):
month = self.m_choice_month.GetStringSelection()
month = select_month(month)
year = self.m_choice_year.GetStringSelection()
sql = SQL.sql_month(month,year)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0,x)
self.m_dataViewList_peminjaman.AppendItem(y)
def show_by_year(self):
year = self.m_choice_tahunan.GetStringSelection()
sql = SQL.sql_year(year)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0,x)
y[3] = str(select_month_int(y[3]))
self.m_dataViewList_tahun.AppendItem(y)
def show_data_perpus(self):
library = self.m_choice_library.GetStringSelection()
library = select_library(library)
year = self.m_choice_tahun.GetStringSelection()
sql = SQL.sql_perpus(year,library)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0,x)
y[3] = str(select_month_int(y[3]))
self.m_dataViewList_perpus.AppendItem(y)
def show_by_title(self):
title = self.m_textCtrl2.GetValue()
year = self.m_choice_bookTitle.GetStringSelection()
sql = SQL.sql_book_title(title,year)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0,x)
y[5] = str(select_month_int(y[5]))
self.m_dataViewListCtrl6.AppendItem(y)
def show_book_month(self):
month = self.m_choice_month_book.GetStringSelection()
month = select_month(month)
year = self.m_choice_year_book.GetStringSelection()
sql = SQL.sql_book_month(month, year)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0, x)
y[5] = str(select_month_int(y[5]))
self.m_dataViewListCtrl9.AppendItem(y)
def show_book_year(self):
year = self.m_choice_allBook.GetStringSelection()
sql = SQL.sql_book_year(year)
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0, x)
y[4] = str(select_month_int(y[4]))
self.m_dataView_allBook.AppendItem(y)
def show_fact(self):
sql = SQL.sql_fact()
cursor.execute(sql)
rows = cursor.fetchall()
for x, item in enumerate(rows, start=1):
y = list(item)
y.insert(0,x)
y[8] = str(y[8])
y[9] = str(y[9])
self.m_dataView_fact.AppendItem(y)
# ---------------------- Save GUI ---------------------- #
def save_member(self):
member = self.m_text_member.GetValue()
sql = SQL.sql_member(member)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_member(rows)
def save_month(self):
month = self.m_choice_month.GetStringSelection()
month = select_month(month)
year = self.m_choice_year.GetStringSelection()
sql = SQL.sql_month(month, year)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_month(rows)
def save_year(self):
year = self.m_choice_tahunan.GetStringSelection()
sql = SQL.sql_year(year)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_year(rows)
def save_perpus(self):
library = self.m_choice_library.GetStringSelection()
library = select_library(library)
year = self.m_choice_tahun.GetStringSelection()
sql = SQL.sql_perpus(year,library)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_perpus(rows)
def save_title_book(self):
title = self.m_text_member.GetValue()
year = self.m_choice_bookTitle.GetStringSelection()
sql = SQL.sql_book_title(title,year)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_by_title(rows)
def save_book_month(self):
month = self.m_choice_month_book.GetStringSelection()
month = select_month(month)
year = self.m_choice_year_book.GetStringSelection()
sql = SQL.sql_book_month(month, year)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_book_month(rows)
def save_book_year(self):
year = self.m_choice_allBook.GetStringSelection()
sql = SQL.sql_book_year(year)
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_book_year(rows)
def save_fact():
sql = SQL.sql_fact()
cursor.execute(sql)
rows = cursor.fetchall()
Excels.excel_fact(rows) |
9d94a45ef3ff4e54a80ff84eb9bdfed0579b4506 | skostic14/PA_vezbe | /vezba09/vertex_example.py | 837 | 3.828125 | 4 | from enum import Enum
class Vertex:
"""
Graph vertex: A graph vertex (node) with data
"""
def __init__(self, c = None, p = None, d1 = None, d2 = None):
"""
Vertex constructor
@param color, parent, auxilary data1, auxilary data2
"""
self.c = c
self.p = p
self.d1 = d1
self.d2 = d2
class Data:
"""
Graph data: Any object which is used as a graph vertex data
"""
def __init__(self, val1, val2):
"""
Data constructor
@param A list of values assigned to object's attributes
"""
self.a1 = val1
self.a2 = val2
class VertexColor(Enum):
BLACK = 0
GRAY = 127
WHITE = 255
u = Vertex(c=VertexColor.WHITE, d1=1, d2=22)
v = Vertex(c=VertexColor.GRAY, p=u, d1=33, d2=4)
|
8ea4ffe77ab5a1bcbfe819bff7d0398cba7a1d52 | adriancast/Custom-ROT | /crypt.py | 897 | 3.5625 | 4 | #!/usr/bin/python
import string # To get abecedary
from utility import *
def main(argv):
data = list(getDataFile())
cripted = []
for item in data:
letterCripted = getCriptedLetter(item,getRot())
if letterCripted != -1:
cripted.append(letterCripted)
else:
cripted.append(item)
cripted = ''.join(cripted)
print "Se ha codificado como: ",cripted
pushDataFile(cripted)
def getCriptedLetter(letter,rot):
ascii_letters = list(string.ascii_letters)
idx = 0
for abec_letter in ascii_letters:
if letter == abec_letter:
result = idx + rot
while result > len(ascii_letters)-1:
result = result % len(ascii_letters)
return ascii_letters[result]
idx = idx + 1
return -1 #if is not in the ascii_letters
if __name__ == "__main__":
main(sys.argv[1:])
|
f4d7ac925c02683563dfbee3081a6d9e7b6effff | mrdudeitsme/Python-Programs | /4.UserInput.py | 210 | 4.03125 | 4 | name = input("Enter Your name")
print("Your name is : " + name)
age = input("Enter your age")
print("Your age is: " + age)
number = input("Enter your phone number")
print ("Your phone number is :" + number)
|
6f28349ebbad196055d164b7eebb01d573809d5e | tmvinoth3/Python | /primeComprehension.py | 394 | 3.921875 | 4 | #code
from math import sqrt
def IsPrime(x):
if x<2:
return False
else:
for i in range(2,int(sqrt(x))+1):
if x%i==0:
return False
return True
def main():
inp = int(input())
print([x for x in range(inp) if IsPrime(x)])#list compreh
if __name__ == '__main__':
main()
print({x:x*x for x in range(101) if IsPrime(x)})#set compreh |
f2f0f9380ac5842438137c618334d04e0a087c08 | trevor-hedges/AA244B_PIC | /helper_functions.py | 836 | 4.375 | 4 | import os
import os.path
def check_make(dirM):
"""
Checks to see if the given directory, or list of directories, exists, and if not, creates it.
:param dirM: Directory, or list of directories
:return: List of booleans corresponding to the directories - returns "True" if the directory already exists or "False" if it did not exist and was created.
"""
# Put dirM in list to iterate (allows function to be able to handle single input or multiple inputs)
if not isinstance(dirM, (list, tuple)):
dirM = [dirM]
output_list = []
for dirm in dirM:
if not os.path.exists(dirm):
# The dir does not exist
os.makedirs(dirm)
output_list.append(False)
else:
# The dir exists
output_list.append(True)
return(output_list)
|
b82aa4f6e009e17ac0976114aa916b3e62dee89c | Purnima124/Bacik | /variable.py | 290 | 3.578125 | 4 | # a="purnima"
# b="19"
# print(a+b)
# print(a+"b")
# # conversion
# var56="20"
# var57=20
# print(type(var57))
# var23=3.0
# var24=int(var23)
# print(type(var24))
# a="@@*************@@"
# print(a,"@@@@@@@@")
# print(a,"@@@@@@@")
# a="purnima"
# b=1997
# b=str(b)
# print(a,b)
|
7c6c31b5cc03c772eac30a884a67bb5f22ad6516 | Langoorlens/PythonBasic | /InsertionSort.py | 250 | 3.84375 | 4 | arr = [122, 131, 153, 25, 64]
def insertionsort(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
insertionsort(arr)
print (arr) |
cc53970a830ae316085c4d6d1287a759a2e8a339 | rpm1995/LeetCode | /75_Sort_Colors.py | 1,544 | 3.71875 | 4 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# zeros = 0
# ones = 0
# twos = len(nums) - 1
# while ones <= twos:
# element = nums[ones]
# if element == 1:
# ones += 1
# elif element == 2:
# temp = nums[ones]
# nums[ones] = nums[twos]
# nums[twos] = temp
# # nums[ones], nums[twos] = nums[twos], nums[ones]
# twos -= 1
# # ones += 1
# elif element == 0:
# temp = nums[ones]
# nums[ones] = nums[zeros]
# nums[zeros] = temp
# # nums[ones], nums[zeros] = nums[zeros], nums[ones]
# zeros += 1
# ones += 1
zeros = 0
twos = len(nums) - 1
curr = 0
while curr <= twos:
num = nums[curr]
if nums[curr] == 0:
nums[zeros], nums[curr] = nums[curr], nums[zeros]
zeros += 1
curr += 1
elif nums[curr] == 2:
nums[twos], nums[curr] = nums[curr], nums[twos]
twos -= 1
# curr += 1
else:
curr += 1
|
97dfde539a3426823b5cd2e3e6ed8e8f7e0dc567 | Yuan-EPAM/Yuan-EPAM | /week-03/day-2/extensions/extension.py | 546 | 3.5625 | 4 | def add(a, b):
return a + b
def max_of_three(a, b, c):
max_num = a
if b > max_num:
max_num = b
if c > max_num:
max_num = c
return max_num
def median(pool):
if not pool:
return
return pool[int((len(pool) - 1) / 2)]
def is_vovel(char):
return char in ['a', 'u', 'o', 'e', 'i']
def translate(hungarian):
if not hungarian:
return ''
teve = hungarian
for char in teve:
if is_vovel(char):
teve = (char+'v'+char).join(teve.split(char))
return teve
|
0bd2ed119ac917af920757a8749a56f83d1e526d | satya121/python | /cubes.py | 43 | 3.5 | 4 | d={i:i**3 for i in range(1,11)}
print(d)
|
81686440bb2deb43ce2930e36ce4c237276ecff4 | egithublizabeth/CIS024-Python-SJCC | /HW_9_11.10.17/main1.py | 451 | 3.859375 | 4 |
# coding: utf-8
# In[7]:
import argparse
#include standard modules
#initialze the parser
parser = argparse.ArgumentParser()
parser.add_argument("x", type = int, help = "Pick a number")
parser.add_argument("y", type = int, help = "Pick another number")
#read arguments from the command line
args = parser.parse_args()
#get the sum
n1 = int(args.x)
n2 = int(args.y)
answer = n1 + n2
#output results
print("The sum is: ", answer)
# In[ ]:
|
9e538512fc575852b99faf6edfd835dc4ec01595 | josealt2197/PP3 | /.Otros Documentos/pruebas.py | 4,603 | 3.71875 | 4 | # from PIL import Image, ImageDraw, ImageFont
# import os
# # if __name__ == '__main__':
# # height = 600
# # width = 600
# # image = Image.new(mode='L', size=(height, width), color=255)
# # # Draw a line
# # draw = ImageDraw.Draw(image)
# # x = image.width / 2
# # y_start = 0
# # y_end = image.height
# # line = ((x, y_start), (x, y_end))
# # draw.line(line, fill=128)
# # del draw
# # image.show()
# # def text_on_img(filename='01.png', text="Hello", size=12, color=(255,255,0), bg='red'):
# # "Draw a text on an Image, saves it, show it"
# # fnt = ImageFont.truetype('arial.ttf', size)
# # # create image
# # image = Image.new(mode = "RGB", size = (int(size/2)*len(text),size+50), color = bg)
# # draw = ImageDraw.Draw(image)
# # # draw text
# # draw.text((10,10), text, font=fnt, fill=(255,255,0))
# # # save file
# # image.save(filename)
# # # show file
# # os.system(filename)
# # text_on_img(text="Text to write on img", size=300, bg='red')
# from PIL import Image, ImageDraw
# # size of image
# canvas = (400, 300)
# # scale ration
# scale = 5
# thumb = canvas[0]/scale, canvas[1]/scale
# # rectangles (width, height, left position, top position)
# frames = [(50, 50, 5, 5), (60, 60, 100, 50), (100, 100, 205, 120)]
# # init canvas
# im = Image.new('RGBA', canvas, (255, 255, 255, 255))
# draw = ImageDraw.Draw(im)
# # draw rectangles
# for frame in frames:
# x1, y1 = frame[2], frame[3]
# x2, y2 = frame[2] + frame[0], frame[3] + frame[1]
# draw.rectangle([x1, y1, x2, y2], outline=(0, 0, 0, 255))
# # make thumbnail
# im.thumbnail(thumb)
# # save image
# im.save('im.png')
# def validarCorreo(correo):
# contador=0
# longitud=len(correo)
# punto=correo.find(".")
# arroba=correo.find("@")
# if(punto==-1 or arroba==-1):
# return False
# for i in range (0,arroba):
# if((correo[i]>='a' and correo[i]<='z') or (correo[i]>='A' and correo[i]<='Z')):
# contador=contador+1
# if(contador>0 and arroba>0 and (punto-arroba)>0 and (punto+1)<longitud):
# return True
# else:
# return False
# # Send an HTML email with an embedded image and a plain text message for
# # email clients that don't want to display the HTML.
# import smtplib, ssl
# from email.mime.text import MIMEText
# from email.mime.multipart import MIMEMultipart
# from email.mime.base import MIMEBase
# from email.mime.image import MIMEImage
# # Define these once; use them twice!
# emisor = 'proyecto3bingo@gmail.com'
# receptor = 'josealt2197@gmail.com'
# # Create the root message and fill in the from, to, and subject headers
# mensaje = MIMEMultipart('related')
# mensaje['Subject'] = 'test message'
# mensaje['From'] = emisor
# mensaje['To'] = receptor
# mensaje.preamble = 'This is a multi-part message in MIME format.'
# # Encapsulate the plain and HTML versions of the message body in an
# # 'alternative' part, so message agents can decide which they want to display.
# msgAlternative = MIMEMultipart('alternative')
# mensaje.attach(msgAlternative)
# msgText = MIMEText('This is the alternative plain text message.')
# msgAlternative.attach(msgText)
# # We reference the image in the IMG SRC attribute by the ID we give it below
# msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
# msgAlternative.attach(msgText)
# # This example assumes the image is in the current directory
# fp = open('imagenCorreoCartones.png', 'rb')
# msgImage = MIMEImage(fp.read())
# fp.close()
# # Define the image's ID as referenced above
# msgImage.add_header('Content-ID', '<image1>')
# mensaje.attach(msgImage)
# # Send the email (this example assumes SMTP authentication is required)
# # smtp = smtplib.SMTP()
# # smtp.connect('smtp.gmail.com')
# # smtp.login('proyecto3taller@gmail.com', 'cursoTEC2020')
# # smtp.sendmail(emisor, receptor, mensaje.as_string())
# # smtp.quit()
# context = ssl.create_default_context()
# with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
# server.login('proyecto3bingo@gmail.com', 'cursoTEC2020')
# server.sendmail(emisor, receptor, mensaje.as_string())
from PIL import Image, ImageDraw, ImageFont
def insertarPremio(premio, numero):
cartonBase = Image.open('imagenCorreoGanador.png')
draw = ImageDraw.Draw(cartonBase)
fuentePremio = ImageFont.truetype('arial.ttf', size=40)
color = 'rgb(185, 18, 27)'
#Anotar el Premio al final de la imagen.
draw.text((170, 580), premio, fill=color, font=fuentePremio)
cartonBase.save(str(numero)+'.png') |
d610afddc3d530eafffa34c1e887671ee9b628ce | daktari01/amity | /src/rooms.py | 849 | 3.859375 | 4 | class Room:
"""Class for general room"""
def __init__(self, room_type, room_name, occupants, max_occupants):
self.room_name = room_name
self.room_type = room_type
self.occupants = occupants
self.max_occupants = max_occupants
def is_full(self, occupants, max_occupants):
return True if self.occupants == self.max_occupants else False
class LivingSpace(Room):
"""Class LivingSpace inherits from class Room"""
def __init__(self, room_type, room_name, occupants=0, max_occupants=4):
super().__init__(room_name, room_type, occupants, max_occupants)
class Office(Room):
"""Class Office inherits from class Room"""
def __init__(self, room_type, room_name, occupants=0, max_occupants=6):
super().__init__(room_name, room_type, occupants, max_occupants) |
6cc1d4c5376582081e1e7ebad76af6070b26d9bd | Sziszka0909/Amoba | /amobavegleges.py | 4,536 | 3.5625 | 4 | import sys
global field
import time
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
FAIL = '\033[91m'
ENDC = '\033[0m'
print("Welcome to Amőba!")
print("In this game your goal is to put 3 'X'' or 3 '0' in a row or a column or a diagonal.")
time.sleep(3)
field = []
def fieldappend():
for x in range(0,3):
field.append(['_'] * 3)
def fieldprint():
for i in field:
print(' '.join(i))
print("")
def hit1():
global field
x = input("Enter in a row! (Choose one of the following number: 1, 2, 3): ")
y = input("Enter in a column! (Choose one of the following number: 1, 2, 3): ")
print("")
try:
x = int(x)
y = int(y)
except ValueError:
print("Give me a " + bcolors.WARNING + "NUMBER! " + bcolors.ENDC + " \n")
hit1()
if (x > 3 or x < 0 or y > 3 or y <0):
print("Out of " + bcolors.FAIL + "range. " + bcolors.ENDC + " \n")
hit1()
x, y = x - 1, y - 1
if (field[x][y] == 'X' or field[x][y] == 'O'):
print("You can't mark " + bcolors.UNDERLINE + "that" + bcolors.ENDC + " spot. \n")
hit1()
else:
field[x][y] = 'X'
fieldprint()
checkgame()
time.sleep(2)
print("Now O turn. \n")
time.sleep(1)
hit2()
fieldprint()
def hit2():
global field
x = input("Enter in a row! (Choose one of the following number: 1, 2, 3): ")
y = input("Enter in a column! (Choose one of the following number: 1, 2, 3): ")
print("")
try:
x = int(x)
y = int(y)
except ValueError:
print("Give me a " + bcolors.WARNING + "NUMBER! " + bcolors.ENDC + " \n")
hit2()
if (x > 3 or x < 0 or y > 3 or y <0):
print("Out of " + bcolors.FAIL + "range. " + bcolors.ENDC + " \n")
hit2()
x, y = x - 1, y - 1
if (field[x][y] == 'X' or field[x][y] == 'O'):
print("You can't mark " + bcolors.UNDERLINE + "that" + bcolors.ENDC + " spot. \n")
hit2()
else:
field[x][y] = 'O'
fieldprint()
checkgame()
time.sleep(2)
print("Now X turn. \n")
time.sleep(1)
hit1()
fieldprint()
def checkgame():
win = False
if ((field[0][0] == 'X' and field[0][1] == 'X' and field[0][2] == 'X') or
(field[1][0] == 'X' and field[1][1] == 'X' and field[1][2] == 'X') or
(field[2][0] == 'X' and field[2][1] == 'X' and field[2][2] == 'X') or
(field[0][0] == 'X' and field[1][1] == 'X' and field[2][2] == 'X') or
(field[0][2] == 'X' and field[1][1] == 'X' and field[2][0] == 'X') or
(field[0][0] == 'X' and field[1][0] == 'X' and field[2][0] == 'X') or
(field[0][1] == 'X' and field[1][1] == 'X' and field[2][1] == 'X') or
(field[0][2] == 'X' and field[1][2] == 'X' and field[2][2] == 'X') or
(field[0][0] == 'X' and field[1][0] == 'X' and field[2][0] == 'X') or
(field[0][1] == 'X' and field[1][1] == 'X' and field[2][1] == 'X') or
(field[0][2] == 'X' and field[1][2] == 'X' and field[2][2] == 'X')):
win = True
print("The X wins!")
sys.exit(0)
elif(field[0][0] != '_' and field[0][2] !='_' and field[2][0] !='_' and field[2][2] !='_' and win == False):
print("Tie.")
sys.exit(0)
elif ((field[0][0] == 'O' and field[0][1] == 'O' and field[0][2] == 'O') or
(field[1][0] == 'O' and field[1][1] == 'O' and field[1][2] == 'O') or
(field[2][0] == 'O' and field[2][1] == 'O' and field[2][2] == 'O') or
(field[0][0] == 'O' and field[1][1] == 'O' and field[2][2] == 'O') or
(field[0][2] == 'O' and field[1][1] == 'O' and field[2][0] == 'O') or
(field[0][0] == 'O' and field[1][0] == 'O' and field[2][0] == 'O') or
(field[0][1] == 'O' and field[1][1] == 'O' and field[2][1] == 'O') or
(field[0][2] == 'O' and field[1][2] == 'O' and field[2][2] == 'O') or
(field[0][0] == 'O' and field[1][0] == 'O' and field[2][0] == 'O') or
(field[0][1] == 'O' and field[1][1] == 'O' and field[2][1] == 'O') or
(field[0][2] == 'O' and field[1][2] == 'O' and field[2][2] == 'O')):
win = True
print("The 0 wins!")
sys.exit(0)
if __name__ == '__main__':
fieldappend()
input("Okay, lets play! Press enter to continue.")
fieldprint()
hit1()
|
c5e09616e11ecec9968344d62c9d3ca1fd15b32f | basvasilich/leet-code | /1160.py | 836 | 3.640625 | 4 | # https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/
from collections import Counter
from typing import List
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
result = 0
chars_c = Counter(chars)
for word in words:
h = {}
flag = True
for char in word:
if char not in chars_c.keys():
flag = False
break
elif char in h.keys() and chars_c[char] < h[char] + 1:
flag = False
break
elif char in h.keys():
h[char] += 1
elif char not in h.keys():
h[char] = 1
if flag:
result += len(word)
return result
|
f40200794fb552644cc2e9a4b577f0c2bcfd6ce1 | purohitdheeraj-svg/python | /array_sort_rtate.py | 1,690 | 3.609375 | 4 | ''' # Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
# Write your code here
T = int(input())
list_1 = []
arr_size_int = 0
arr_rotate_int = 0
while T > 0:
arr_size_rotate = input()
#print(arr_size_rotate)
arr_size = arr_size_rotate[0]
arr_rotate = arr_size_rotate[2]
#print(type(arr_size), type(arr_rotate))
arr_size_int = int(arr_size)
arr_rotate_int = int(arr_rotate)
#print(arr_size_int, arr_rotate_int)
for value in range(1,arr_size_int+1):
list_1.append(value)
#print(value)
result = list_1[-arr_rotate_int:] + list_1[:arr_rotate_int+1]
for value in result:
print(value, end= " ")
#for i in range(len(result)):
#print(list_1[i], end=" ")
T -= 1
# second cases
# Write your code here
T = int(input())
list_1 = []
list_2 = []
while T > 0:
for i in range(2):
list_2.append(input())
arr_size_int = list_2[0][1]
arr_rotate_int = list_2[0][2]
list_1.append(list_2[1])
list_1 = (','.join(list_1)).split()
#print(list_1)
arr = int(arr_rotate_int)
result = list_1[-arr:] + list_1[:arr+1]
#print(result)
for value in result:
print(value, end= " ")
T -= 1
'''
#correct case
for _ in range(int(input())):
n,k = map(int, input().split())
k = k%n
arr = list(map(int,(input().split())))
arr = arr[-k:] + arr[:k+1]
print(arr)
|
a76f14a0f59e90b154e34aa867c8dd6f45727f93 | cs-fullstack-2019-fall/python-basics1-review-ic-Kevin-CodeCrew | /sdk_test.py | 742 | 4.25 | 4 |
# Ask the user to enter a number that's not from -10 to 10. If they enter -10 to 10, ask them to enter another number. If they do NOT enter a number from -10 to 10, quit and print "Good job".
# userNumber = int(input("Enter a number that's NOT -10 to 10"))
# while userNumber > -10 and userNumber < 10:
# userNumber2 = int(input("Try again"))
# print("good job")
# Ask the user to enter a name to invite to their party until they enter 'q' to quit. Save all of the names in a string with hyphens between them.
birthdayGirl = input("Enter a name for the birthday party")
nameList = ""
while(birthdayGirl != 'q'):
nameList = nameList + " - " + birthdayGirl
birthdayGirl = input("Enter a name for the birthday party")
print(nameList)
|
58730063663d9bc6590d60cadc4437f4ea05a4ac | TrellixVulnTeam/CS540-Introduction-To-Artificial-Intelligence_BQ03 | /Selections-Of-Projects/HW3: Hill Climbing/nqueens.py | 6,149 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[26]:
# given a state of the board, return a list of all valid successor states
def succ(state, static_x, static_y):
returned_list = []
n = len(state)
# check if there is no queen on the static point
if not(state[static_x] == static_y):
returned_list = []
else:
for i in range(0,n):
if i == static_x:
continue
else:
if state[i] == n-1:
child1 = move_down(state,i)
returned_list.append(child1)
elif state[i] == 0:
child1 = move_up(state, i)
returned_list.append(child1)
else:
child1 = move_up(state, i)
child2 = move_down(state, i)
returned_list.append(child1)
returned_list.append(child2)
# print(sorted(returned_list))
returned_list = sorted(returned_list)
return returned_list
def move_up(state,i):
child_state = []
child_state = state.copy()
child_state[i] += 1
return child_state
def move_down(state,i):
child_state = []
child_state = state.copy()
child_state[i] -= 1
return child_state
def f(state):
f = 0
# print(state)
n = len(state)
chessboard = state.copy()
for i in range(0,n):
# print(i)
if check_pos_row(state,i, n) or check_neg_row(state, i) or check_up_diagonal(state, i, n) or check_down_diagonal(state, i):
f = f + 1
# print("f=",f)
# print(f)
return f
def check_pos_row(state, i, n):
if_attacted = False
j = i
# print(i)
while j+1 < n:
if state[i] == state[j+1]:
if_attacted = True
# print(state[j],state[j+1])
# print("pos_row")
break
j += 1
return if_attacted
def check_neg_row(state, i):
if_attacted = False
j = i
while j - 1 >= 0:
if state[i] == state[j-1]:
# print(state[j-1],state[i])
if_attacted = True
# print("neg_row")
break
j -= 1
return if_attacted
def check_up_diagonal(state, i, n):
if_attacted = False
j = i
while j < n:
if abs(state[i] - state[j]) == abs(i-j) and i !=j:
# print(state[i],state[j])
if_attacted = True
# print("up_dia")
break
j += 1
return if_attacted
def check_down_diagonal(state, i):
if_attacted = False
j = i
while j >=0:
if abs(state[i] - state[j]) == abs(i-j) and i !=j:
if_attacted = True
# print("down_dia")
break
j -= 1
return if_attacted
# given the current state, use succ() to generate the successors and return the selected next state
def choose_next(curr, static_x, static_y):
state_list = succ(curr, static_x, static_y)
f_state_list = []
returned_state = None
# print(state_list)
# print(len(state_list))
# check if the state list is an empty list
if len(state_list) == 0:
returned_state = None
else:
state_list.append(curr)
f_n = 0
for i in range(0,len(state_list)):
f_n = f(state_list[i])
f_state_list.append((f_n, state_list[i]))
f_state_list = sorted(f_state_list)
returned_state = f_state_list[0][1]
# print(f_state_list)
# print(returned_state)
return returned_state
# run the hill-climbing algorithm from a given initial state, return the convergence state
def n_queens(initial_state, static_x, static_y, print_path=True):
succ_list = []
succ_list.append((f(initial_state), initial_state))
f_prev_state = f(initial_state)
returned_state = []
cur_state = choose_next(initial_state,static_x, static_y)
if not(cur_state == None):
f_cur_state = f(cur_state)
succ_list.append((f_cur_state, cur_state))
while f_cur_state != f_prev_state and f_cur_state != 0:
# print(cur_state)
f_prev_state = f_cur_state
cur_state = choose_next(cur_state,static_x, static_y)
f_cur_state = f(cur_state)
succ_list.append((f_cur_state, cur_state))
# print(cur_state)
succ_list = sorted(succ_list, reverse=True)
if print_path == True:
for i in succ_list:
print(i[1], 'f=%d' %i[0])
returned_state = succ_list[len(succ_list)-1][1]
# for i in succ_list:
# print(i[1], "f=", i[0])
# print(returned_state)
return returned_state
import random
def n_queens_restart(n, k, static_x, static_y):
random.seed(1)
initial_state = []
returned_state = []
returned_f = 0
# generate an initial state by using Python's random module
for i in range(0,n):
if i == static_x:
initial_state.append(static_y)
else:
m = random.randint(0, n-1)
initial_state.append(m)
cur_state = initial_state
# start the for-loop for k times
for j in range(0,k):
# print(cur_state)
cur_state = n_queens(cur_state, static_x, static_y, print_path=False)
f_cur = f(cur_state)
returned_f = f_cur
returned_state = cur_state
# check if the problem is solved with an f() value of 0; if so, break the loop
if f_cur != 0:
# print("a new initial state")
temp_state = []
# print(n)
for i in range(0,n):
# print(i)
if i == static_x:
temp_state.append(static_y)
else:
m = random.randint(0, n-1)
temp_state.append(m)
# print(temp_state)
cur_state = temp_state
else:
break
print(returned_state, 'f=%d' %returned_f)
|
44d2837aaf37ca113439a006c4ae512cc7b78aff | Ahmed201002/python | /challenge/codeQuestion.py | 772 | 3.96875 | 4 | # create a programm that takes IP address entered at the keyboard
# and prints out the number of segments it contains,and the length of each segment
# An IP Address consists of 4 numbers,seperated from each other with a full stop.But your program should just count many are entered
# Exampel of the input you may get are:
# 127.0.0.1
# .192.168.0.1
# 10.0.123456.255
# 172.16
# # 255
# so your program should work even with Invalid ip Addresses.We are just interested in the number of segments and how long each one is.
# once your have a working program ,here are some more for invalid input to test:
# .123.45.678.91
# 123.4567.8.9.
# 123.156.289.10123456
# 10.10t.10.10
# 12.9.34.6.12.90
# ''_that is ,press enter without typing anything
#
|
03d3bace1f0cf8b45ffdb7641265e507d3a83e4e | Seinu/MIT-6.00-OCW | /Problem-Set-3/ps3b.py | 3,540 | 4.21875 | 4 | from ps3a import *
import time
from perm import *
n = 0
#
#
# Problem #6A: Computer chooses a word
#
#
def comp_choose_word(hand, word_list):
"""
Given a hand and a word_dict, find the word that gives the maximum value score, and return it.
This word should be calculated by considering all possible permutations of lengths 1 to HAND_SIZE.
hand: dictionary (string -> int)
word_list: list (string)
"""
words = []
for i in range(1, len(hand)):
x = get_perms(hand, i)
words.extend(x)
score = 0
maxscore = 0
bestword = ''
for word in words:
if word in word_list:
score = get_word_score(word, len(hand))
if score > maxscore:
bestword = word
maxscore = score
if maxscore == 0:
return
return bestword
#
# Problem #6B: Computer plays a hand
#
def comp_play_hand(hand, word_list):
"""
Allows the computer to play the given hand, as follows:
* The hand is displayed.
* The computer chooses a word using comp_choose_words(hand, word_dict).
* After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the computer
chooses another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when the computer has exhausted its possible choices (i.e. comp_play_hand returns None).
hand: dictionary (string -> int)
word_list: list (string)
"""
word = ''
score = 0
while word != None:
print display_hand(hand)
word = comp_choose_word(hand, word_list)
if is_valid_word(word,hand,word_list):
print word
hand = update_hand(hand, word)
score = score + get_word_score(word, n)
print score
#
# Problem #6C: Playing a game
#
#
def play_game(word_list):
"""Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', play a new (random) hand.
* If the user inputs 'r', play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, ask them again.
2) Ask the user to input a 'u' or a 'c'.
* If the user inputs 'u', let the user play the game as before using play_hand.
* If the user inputs 'c', let the computer play the game using comp_play_hand (created above).
* If the user inputs anything else, ask them again.
3) After the computer or user has played the hand, repeat from step 1
word_list: list (string)
"""
opt = ''
opt2 = ''
while opt != 'e':
opt = raw_input('input e to exit, n for new hand, r to replay hand: ')
opt2 = raw_input("Input u to play as user, input c for cpu to play. ")
if opt == 'n':
n = int(raw_input('input hand size. '))
if opt2 == 'u':
hand = deal_hand(n)
play_hand(hand, word_list)
elif opt2 == 'c':
hand = deal_hand(n)
comp_play_hand(hand, word_list)
elif opt == 'r':
if opt2 == 'u':
play_hand(hand, word_list)
elif opt2 == 'c':
comp_play_hand(hand, word_list)
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
word_list = load_words()
play_game(word_list)
|
b942fb60fcf1c01c47dd843c52e7002555e4184b | JuanMacias07x/Trabajos-faltantes | /23 de abril/12.py | 1,525 | 3.921875 | 4 | #Creación cuenta
user = input("Ingrese el nombre de usuario que quiera usar para esta cuenta = ")
add = input("¿Desea Crear una contraseña segura? si o no = ")
if add == "si":
#creacion de un cotraseña aleatoria
import random #Importan la librería para generar números aleatorios
lista=[]
cond="si"
numero=random.randint(1,100) #Generar números aleatorios.
while cond=="si":
cadena=input("Ingrese por favor una frase o letra para tu contraseña aleatoria = ")
lista.append(cadena) #Se agrega a la lista predeterminada con el .append
cond=input("¿Quieres ingresar otra frase o letra para tu contraseña? = ")
lisy= random.sample(lista,1) #Se genera de manera aleatoria.
print("".join(lisy) + str(numero)) #Se retira los paréntesis
else:
password_new = input("Ingrese la contraseña = ")
#Validación de datos
user_Inicio = input("Ingrese su nombre de Usuario = ")
password_Incion = input("Ingrese su contraseña = ")
if password_Incion == ("".join(lisy) + str(numero)) and user==user_Inicio: #Se determina una condición para así poder evaluar si los datos ingresados son iguales a los creados anteriorimente.
print("Datos son correctos, será redirigido a la pantalla principal en pocos minutos.")
elif password_Incion== ("".join(lisy) + str(numero)) and user==user_Inicio:
print("Datos son correctos, será redirigido a la pantalla principal en pocos minutos.")
else:
print("Los datos son incorrectos.")
|
59f2db54c3e6434414564d169ffcceb0a48fd826 | Naim08/python-chess | /king.py | 643 | 3.9375 | 4 | """ Definition of king class and its movement. """
from .piece import Piece
class King(Piece):
""" King model. """
symbol = '♚'
@property
def movements(self):
""" King moves one square in any direction.
Don't mind out-of-bounds relative positions: forbidden ones will be
silently discarded within the ``Piece.territory()`` method above.
"""
return set([
# Horizontal movements.
(+1, 0), (-1, 0),
# Vertical movements.
(0, +1), (0, -1),
# Diagonal movements.
(+1, +1), (-1, -1), (-1, +1), (+1, -1),
])
|
e25fc3262cb551f725cc7010edcbb383fed6d802 | Tiiaraa1907/machineLearningPath | /transformChar.py | 3,097 | 4 | 4 | # upper
# kata = 'dicoding'
# kata = kata.upper()
# print(kata)
# lower
# kata = 'DICODING'
# kata = kata.lower()
# print(kata)
# # rstrip (hapus spasi belakang)
# print('Dicoding '.rstrip())
# # lstrip (hapus spasi depan)\
# print(' Dicoding'.lstrip())
# # strip (hapus spasi depan belakang, dan menghapus kata)
# print(' Dicoding '.strip())
# kata = 'CodeCodeDicodingCodeCode'
# print(kata.strip('Code'))
# # startswith(boolean)
# print('Dicoding Indonesia'.startswith('Dicoding'))
# # ends with()
# print('Dicoding Indonesia'.endswith('Indonesia'))
# # MENGGABUNGKAN STRING
# print(' '.join(['Dicoding', 'Indonesia', '!']))
# print('123'.join(['Dicoding', 'Indonesia', '!']))
# # MEMISAHKAN STRING
# print('Dicoding Indonesia !'.split())
# # BISA DIGUNAKAN PADA MULTILINE
# print('''Halo,
# aku ikan,
# aku suka sekali menyelam
# aku tinggal di perairan.
# Badanku licin dan renangku cepat.
# Senang berkenalan denganmu.'''.split('\n'))
# # MENGGANTI STRING
# string = "Ayo belajar Coding di Dicoding"
# print(string.replace("Coding", "Pemrograman"))
# # JIKA ADA 2 KATA YANG SAMA
# string = "Ayo belajar Coding di Dicoding karena Coding adalah bahasa masa depan"
# print(string.replace("Coding", "Pemrograman", 1))
# ISUPPER (isupper() akan mengembalikan nilai True jika semua huruf dalam string adalah huruf besar,
# dan akan mengembalikan nilai False jika terdapat satu saja huruf kecil di dalam string tersebut.)
# kata = 'DICODING'
# kata.isupper() #HASILNYA TRUE
# kata = 'dicoding'
# kata.isupper() #HASILNYA FALSE
# # ISLOWER (kebalikan dari metode isupper())
# kata = 'DICODING'
# kata.islower() #HASILNYA FALSE
# kata = 'dicoding'
# kata.islower() #HASILNYA TRUE
# # ISALPHA (semuanya alphabet)
# 'dicoding'.isalpha()
# # ISALNUM(ada semua/salah satu alphabet number)
# 'dicoding123'.isalnum()
# # ISDECIMAL (semuanya angka)
# ‘12345’.isdecimal()
# # ISSPACE(spasi)
# ' ' .isspace()
# # ISTITLE (jika huruf besar setiap kata)
# 'Dicoding Idn' .istitle()
# # ZFILL (zero fill,, jika kita type zfill(5), maka ada 0 sebanyak 4 kali)
# # Contoh 1: Penggunaan zfill 5 pada angka satuan
# angka = 5
# print (str(angka).zfill(5))
# # Contoh 2: Penggunaan zfill 5 pada angka ratusan
# angka = 300
# print (str(angka).zfill(5))
# # Contoh 3: Penggunaan zfill 5 pada angka desimal negatif (memiliki koma)
# angka = -0.45
# print (str(angka).zfill(5))
# # Contoh 4: Penggunaan zfill 7 pada angka desimal negatif (memiliki koma)
# angka = -0.45
# print (str(angka).zfill(7))
# # Contoh 1
# kata = 'aku'
# print (kata.zfill(5))
# # Contoh 2
# kata = 'kamu'
# print (kata.zfill(5))
# # Contoh 3
# kata = 'dirinya'
# print (kata.zfill(5))
# rjust(rata kanan)
'Dicoding'.rjust(20)
# ljust(rata kiri)
'Dicoding'.ljust(20)
# center
'Dicoding'.center(20,'-')
# STRING LITERAL
# \' Single quote
# \" Double quote
# \t Tab
# \n Newline (line break)
# \\ Backslash
# berikut adalah multiline
multi_line = """Halo!
Kapan terakhir kali kita bertemu?
Kita bertemu hari Jum’at yang lalu."""
print(multi_line)
# RAW STRING (sesuai syntax)
print(r'Dicoding\tIndonesia') |
7f3bc4a49b6b7bf4908d6bc78ae9a3fd4ee69e18 | bonezaux/GEProject2 | /beamIO.py | 2,094 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 22:03:29 2018
@author: Carl
"""
import numpy as np
import pandas as pd
import os.path
def saveFile(beam, loads):
"""
Saves the beam and loads to a file with filename given by the user.
Uses pandas for saving to csv.
"""
if beam==None:
print("Cannot save data without beam!")
return
#Get a valid filename
while(True):
filename = input("Write file name to save as:")
if not filename.isalnum():
print ("Illegal filename! Please only enter alphanumerical characters.")
return
else:
break
#Create a matrix, 0th row is the beam, other rows are the loads.
result = np.array([beam[0], beam[1]])
for load in loads:
result = np.vstack((result, np.array([load[0], load[1]])))
#Save matrix as <filename>.csv
with open(filename+".csv", "w") as file:
pd.DataFrame(result).to_csv(file, index=False)
print("Wrote data to file " + filename + ".csv")
def loadFile():
"""
Loads beam and loads from a csv file, as saved by the program previously.
Uses pandas for loading from csv.
"""
#Get a valid filename
while(True):
filename = input("Write file name to load from:")
if not filename.isalnum():
print ("Illegal filename! Please only enter alphanumerical characters.")
return None
else:
break
#Check whether it is a file
if not os.path.isfile(filename+".csv"):
print ("File does not exist. Notice that the program loads .csv files if you supplied your own data file.")
return None
#Load data from file
data = None
with open(filename+".csv") as file:
data = pd.read_csv(file)
data = data.values.reshape(-1, 2)
beam = (float(data[0,0]), data[0,1])
loads = []
for r in data[1:,:]:
loads.append(r.astype(float))
print("Loaded " + filename + ".csv!");
return (beam, loads)
return None
|
1a76c34f2134bd17ada17222403b45adc369c9c6 | maryeleanor/cs50-assignments | /dna.py | 1,917 | 4.09375 | 4 |
import re
import csv
from sys import argv
def main():
if len(argv) != 3:
print("Usage: dna.py [csv file] [DNA sequence txt file]")
# open CSV file and write to list
file = open(argv[1], "r")
csv_file = csv.reader(file)
row = next(csv_file)
# open txt and write to memory
text = open(argv[2], "r")
sequence = text.read()
# create lists for STR counts and potential match
STR_counts = [0]*(len(row)-1)
match = [0]*(len(row)-1)
# run functions
dna_count(row, sequence, STR_counts)
dna_match = compare(row, csv_file, STR_counts, match)
print(dna_match)
# close files
file.close()
text.close()
# iterate through DNA and count sequence occurences
def dna_count(row, sequence, STR_counts):
for i in range(1, len(row)):
substring = row[i]
cursor = 0
counter = 0
max = 0
# s[i:j] in python takes the string s, and returns the substring with all of the characters from i'th character up to (but not including) the j'th
# for each STR, compute the longest run of consecuutive repeats in the DNA sequence
while(cursor+len(substring) <= len(sequence)):
if(sequence[cursor:cursor+len(substring)] == substring):
counter += 1
cursor = cursor+len(substring)
if(max < counter):
max = counter
else:
counter = 0
cursor += 1
STR_counts[i-1] = max
return STR_counts
# compare the STR couunts against each row in the CSV file
def compare(row, csv_file, STR_counts, match):
for row in csv_file:
for j in range(1, len(row)):
match[j-1] = int(row[j])
if(match == STR_counts):
dna_match = row[0]
# print(match)
return dna_match
dna_match = "No Match"
return dna_match
main() |
5273e07ef3344535714d68d790d94f1ed6bb8da5 | r-tran/advent-of-code | /aoc-2019/day1/day1.py | 374 | 3.625 | 4 | masses = map(int, open('data.txt', 'r').readlines())
# part 1
def calc_fuel(mass):
return mass // 3 - 2
print(sum(calc_fuel(m) for m in masses))
# part 2
def calc_additional_fuel(mass):
total, fuel = 0, calc_fuel(mass)
while fuel > 0:
total += fuel
fuel = calc_fuel(fuel)
return total
print(sum(calc_additional_fuel(m) for m in masses))
|
bfc8907440859b88fcc4eb7228af1429661cfe86 | yksoon/Python2 | /2020_04_22_Beautifulsoup.py | 1,506 | 3.921875 | 4 | html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
# title 태그를 반환
# soup.title
print(soup.title)
# title 태그의 이름('title')을 반환
# soup.title.name
print(soup.title.name)
# title 태그의 문자열을 반환
# soup.title.string
print(soup.title.string)
# title 태그의 부모 태그의 이름을 반환
# soup.title.parent.name
print(soup.title.parent.name)
# 첫 p태그를 반환
# soup.p
print(soup.p)
# 'class' 속성이 있는 첫 p태그를 반환
print(soup.p['class'])
# a 태그를 반환
# soup.a
print(soup.a)
# 모든 a 태그를 리스트 형태로 반환
# soup.find_all()
print(soup.find_all('a'))
# soup.find() : 설정한 값에 해당하는 태그를 반환
# id가 'link3'인 태그를 반환
soup.find(id = 'link3')
# get() : href 속성을 반환
for link in soup.find_all('a'):
print(link.get('href'))
# get_text() : html 문서 안에 있는 텍스트를 반환
print(soup.get_text()) |
018369e8fafa571f06f5fc483c1d811df63e3340 | bugmark-trial/funder1 | /Python/remove_duplicate_sort_23002225.py | 679 | 4.125 | 4 | # Question:
# Write a Python program that accepts a sequence of whitespace separated words as
# input and prints the words after removing all duplicate words and
# sorting them alphanumerically.
#
# Suppose the following input is supplied to the program:
# hello world and practice makes perfect and hello world again
# Then, the output should be:
# again and hello makes perfect practice world
#
# Hints:
# In case of input data being supplied to the question, it should be
# assumed to be a console input. We use set container to remove duplicated
# data automatically and then use sorted() to sort the data.
#
#
# Solution:
print(" ".join(sorted(list(set(input().split())))))
|
f20a8438c0850e3a99a22aaee09eb45891b66941 | Miloloaf/Daily-Programmer | /Python/Easy/372 | 519 | 3.578125 | 4 | #! python3
# [2019-01-14] Challenge #372 [Easy] Perfectly balanced
# https://www.reddit.com/r/dailyprogrammer/comments/afxxca/20190114_challenge_372_easy_perfectly_balanced/
foo = ""
matches = {}
matches_reorder = {}
for letter in foo:
matches.setdefault(letter, 0)
matches[letter] += 1
for (letter, value) in matches.items():
matches_reorder[value] = letter
if len(matches_reorder) == 1 or len(matches_reorder) == 0:
print ("True")
else:
print("False")
#print(matches)
#print(matches_reorder)
|
5bdcb72cb9841e2e35c4e14e888f4d1e4b71c877 | Vincent105/python | /04_The_Path_of_Python/T-resource_Python_201904/ex/ex7_13.py | 571 | 3.765625 | 4 | # ex7_13.py
num = 2
prime = []
primeNum = 0
while primeNum < 20:
if num == 2: # 2是質數所以直接輸出
prime.append(num)
primeNum += 1
else:
for n in range(2, num): # 用2 .. num-1當除數測試
if num % n == 0: # 如果整除則不是質數
break # 離開迴圈
else: # 否則是質數
primeNum += 1
prime.append(num)
num += 1
print(prime)
|
79d6b6b39556721939b9f4ebc0bf0250f7478fe3 | bkyoung/bioinfo-utils | /extractor.py | 8,911 | 4.1875 | 4 | #!/usr/bin/env python
import csv, sys, re
from optparse import OptionParser
def listify(r):
'''
Convert a comma delimited string into a list
Accepts:
r: a string containing commas
Returns: a list
'''
return r.split(',')
def find_column_by_name(line, column_name):
'''
Return the index + 1 for a given column header name
Accepts:
line: a list
column_name: a string to search for in line
Returns: a string representing the index of the column being searched for
'''
i = 0
col_found = False
for l in line:
if l.lower() == column_name.lower():
col_found = True
column_index = i
else:
i += 1
if col_found == True:
return str(column_index + 1)
if not col_found:
raise Exception(
'Column name "' + column_name + '" was not found. Please check your spelling.')
def get_columns(line, spec):
'''
Returns the specified columns of the line
Accepts:
line: a list
spec: a string containing a column index or : separated range of columns
Returns: a list containing the specified columns
'''
if ":" in spec:
try:
b = int(spec.split(':')[0]) - 1
except:
raise Exception(
"When specifying column numbers, they must be integers: '"
+ spec + "' contains '" + spec.split(':')[0]
+ "', which violates this rule.")
try:
e = int(spec.split(':')[1])
except:
raise Exception(
"When specifying column numbers, they must be integers: '"
+ spec + "' contains '" + spec.split(':')[1]
+ "', which violates this rule.")
return line[b:e]
else:
try:
c = int(spec) - 1
except:
raise Exception(
"When specifying column numbers, they must be integers: '"
+ spec + "' violates this rule.")
try:
line[c]
except IndexError:
raise Exception(
"You specified a column number that doesn't exist: "
+ str(c + 1) + " (out of range 0 - " + str(len(line)) + ")")
return [line[c]]
def match_line_and(line, match_list):
'''
Returns True if all match criteria matched
Accepts:
line: a list
match_list: a string of , separated column:value pairs to match on
Returns: True or False
'''
matches = listify(match_list)
matched = False
for match in matches:
if ":" in match:
try:
c = int(match.split(':')[0]) - 1
except:
raise Exception(
"When specifying column numbers, they must be integers: '"
+ match + "' contains '" + match.split(":")[0] +
"', which violates this rule.")
s = match.split(':')[1]
try:
if line[c] == s:
matched = True
else:
matched = False
break
except IndexError:
raise Exception(
"You specified a column number that doesn't exist: "
+ str(c + 1))
else:
if match in line:
matched = True
else:
matched = False
break
return matched
def match_line_or(line, match_list):
'''
Returns True if any match criteria matched
Accepts:
line: a list
match_list: a string of , separated column:value pairs to attempt to match on
Returns: True or False
'''
matches = listify(match_list)
matched = False
for match in matches:
if ":" in match:
try:
c = int(match.split(':')[0]) - 1
except:
raise Exception(
"When specifying column numbers, they must be integers: '"
+ match + "' contains '" + match.split(":")[0] +
"', which violates this rule.")
s = match.split(':')[1]
try:
if line[c] == s:
matched = True
break
except IndexError:
raise Exception(
"You specified a column number that doesn't exist: "
+ str(c + 1))
else:
if match in line:
matched = True
break
return matched
def extracted_line(line, cl, delimiter):
'''
Return the string we will write to file, derived from the specified
columns of the supplied line.
Accepts:
line: a list
cl: a string containing a delimited list of desired columns
delimiter: delimiter to split line on
Returns: a string
'''
if cl == None:
return "{0}\n".format(delimiter.join(line))
l = []
column_list = listify(cl)
for c in column_list:
l += get_columns(line, c)
return "{0}\n".format(delimiter.join(l))
if __name__ == '__main__':
'''
A simple utility that grabs the specified columns of a TSV file. If you
specify match patterns, only lines that match the string in the specified
column will be written to the output file.
'''
parser = OptionParser()
parser.add_option("-d", "--delimiter", dest="delimiter", default="\t",
help="alternate delimiter (must be a single character. DEFAULT is a TAB.)")
parser.add_option("-i", "--infile", dest="inputfile", help="input file name")
parser.add_option("-o", "--outfile", dest="outputfile", help="output file name")
parser.add_option("-c", "--columns", dest="columns",
help="column numbers to select. If not specified, all columns will be selected. "
"EX: 1:6 to select the first 6 columns, or 2:8,15 to select columns 2 - 8 and 15. "
"You can also say 1:3,9,4:7 to reorder columns in the output file.")
parser.add_option("-n", "--column-names", dest="columns_by_name",
help="columns to select by column header name instead of column number. "
"This requires that the first line in the file be column headers. "
"Columns in the output file will apear in the order listed here.")
parser.add_option("-m", "--match", dest="match",
help="(optional) column and string to match on. EX: 2:chr1 to match "
"all lines where column 2 contains 'chr1', or 'chr1' to match any column "
"containing 'chr1'. "
"NOTE: multiple values listed together are ANDed together unless "
"--match-mode is used also")
parser.add_option("-r", "--match-or", action="store_true", dest="mode",
help="Changes matching to OR mode instead of default AND mode")
(options, args) = parser.parse_args()
if not options.inputfile:
parser.error('Input filename not given')
if not options.outputfile:
parser.error('Output filename not given')
csv.field_size_limit(sys.maxsize)
with open(options.inputfile, 'r') as infile:
with open(options.outputfile, 'w') as outfile:
i = 0
for line in csv.reader(infile, delimiter=options.delimiter, quoting=csv.QUOTE_NONE ):
# Always write the first line of the file (column names)
if i == 0:
# First, let's convert named columns to their column number(s)
if options.columns_by_name:
cbn = options.columns_by_name.split(',')
for col in cbn:
index = find_column_by_name(line, col)
if options.columns:
options.columns += ',{}'.format(index)
else:
options.columns = index
outfile.write(extracted_line(line, options.columns, options.delimiter))
i += 1
# If we specified match criteria, only write lines that match
elif options.match:
if options.mode:
if match_line_or(line, options.match):
outfile.write(extracted_line(line, options.columns, options.delimiter))
else:
if match_line_and(line, options.match):
outfile.write(extracted_line(line, options.columns, options.delimiter))
# If we didn't specify a match criteria, write specified columns for all lines
elif not options.match:
outfile.write(extracted_line(line, options.columns, options.delimiter))
outfile.close()
infile.close() |
e75505e267956a17672010a7492c99d8aa466a35 | ottokrivenko99/RTR105 | /test1.py | 1,935 | 4.09375 | 4 | ##n = 5
##while n > 0 :
## print(n)
## n = n - 1
## print('Blastoff!')
## print(n)
##An infinite loop
##n = 5
##while n > 0
##print('Lather')
##print('Rinse')
##print('Dry off!')
##n = 0
##while n > 0 :
## print('Lather')
## print('Rinse')
## print('Dry off!')
##Breaking out of a loop
##while True:
## line = input('>hello there')
## if line == 'done' :
## break
## print(line)
## print('Done!')
##Finishing an iteration with continue
##while True:
## line = input('>hello there')
## if line[0] == '#' :
## continue
## if line == 'done' :
## break
## print(line)
## print('Done!')
##
##A Simple definite loop
##for i in [5, 4, 3, 2, 1] :
## print(i)
## print('Blastoff!')
##Looping through a Set
##print('Before')
##for thing in [9, 41, 12, 3, 74, 15] :
## print(thing)
## print('After')
##Finding the larges value
##largest_so_far = -1
##print('Before',largest_so_far)
##for the_num in [9, 41, 12, 3, 74, 15] :
## if the_num > largest_so_far :
## largest_so_far = the_num
## print(largest_so_far,the_num)
##
## print('After',largest_so_far)
##
##Counting in a loop
##zork = 0
##print('Before', zork)
##for thing in :
## zork = zork + 1
## print (zork, thing)
## print('After', zork)
##Filtering in a loop
##print('Before')
##for value in [9, 41, 12, 3, 74, 15]:
## if value > 20:
## print('Large number',value)
##print('After')
##Search using a boolean variable
##found = False
##print('Before',found)
##for value in [9, 41, 12, 3, 74, 15]:
## if value == 3:
## found = True
## print(found, value)
##print('After',found)
##Finding the Average in loop
##count = 0
##sum = 0
##print('Before', count, sum)
##for value in [9, 41, 12, 3, 74, 15]:
## count = count + 1
## sum = sum + value
## print(count,sum,value)
##print('After',count,sum,sum/count)
|
65cb2cd10efe8959462e1e86361584d060147c3d | bhupendrabhoir/PYTHON-3 | /12. GUI/CALCULATOR.py | 997 | 3.6875 | 4 | from tkinter import *
def add():
num1=int(e1.get())
num2=int(e2.get())
result=num1+num2
l3["text"]=result
def sub():
num1=int(e1.get())
num2=int(e2.get())
result=num1-num2
l3["text"]=result
def mul():
num1=int(e1.get())
num2=int(e2.get())
result=num1*num2
l3["text"]=result
def div():
num1=int(e1.get())
num2=int(e2.get())
result=num1/num2
l3["text"]=result
app = Tk()
app.geometry("1000x500")
l1=Label(app,text="Num1")
l2=Label(app,text="Num2")
l3=Label(app)
e1=Entry(app)
e2=Entry(app)
b1=Button(app,text="ADD",command=add)
b2=Button(app,text="SUB",command=sub)
b3=Button(app,text="MUL",command=mul)
b4=Button(app,text="DIV",command=div)
l1.place(x=40,y=40)
l2.place(x=40,y=70)
e1.place(x=120,y=40,width=200)
e2.place(x=120,y=70,width=200)
b1.place(x=40,y=110)
b2.place(x=120,y=110)
b3.place(x=200,y=110)
b4.place(x=280,y=110)
l3.place(x=50,y=150)
app.mainloop()
|
1329a3cf17230424c07ac99c9ce93167c0025b33 | blegloannec/CodeProblems | /HackerRank/Contests/101Hack0616/easy_gcd.py | 620 | 3.5625 | 4 | #!/usr/bin/env python
import sys
from fractions import gcd
from math import sqrt
# consider g = gcd(A) > 1 (by "awesome" hyp)
# for any d | g, d>1, let l = d*(k/d) the largest multiple
# of d to be <= k, then A + l is awesome
# to maximize l, simply minimize d
def main():
n,k = map(int,sys.stdin.readline().split())
A = map(int,sys.stdin.readline().split())
g = reduce(gcd,A)
if g%2==0:
print 2*(k/2)
return
s = 0
for d in xrange(3,int(sqrt(g))+1,2):
if g%d==0:
s = d*(k/d)
print s
return
# g is prime
print g*(k/g)
main()
|
429cbc0aa8e397798a1bf20de6eb8e45065fc13f | adslchen/leetcode | /E39/lc150.py | 708 | 3.5 | 4 | class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for item in tokens:
if item in "+-/*":
b = stack.pop()
a = stack.pop()
stack.append(int(self.operator(item, a,b)))
else:
stack.append(int(item))
print(stack)
return stack.pop()
def operator(self, item, a,b):
if item == '+':
return a+b
elif item == '-':
return a-b
elif item == '*':
return a*b
elif item == '/':
return a/b
|
70922a1f7a3732546f3d6cc7966ee6d7953446a0 | umadevic/uma.py | /p2.py | 101 | 3.75 | 4 | kkk=int(input())
factorial1=1
for i in range(1,kkk+1):
factorial1=factorial1*i
print(factorial1)
|
7b13caac3e46b36ad02c8099f5967da648c8e9c1 | pzmrzy/LeetCode | /python/three_sum_smaller.py | 551 | 3.515625 | 4 | class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
res = 0
nums.sort()
n = len(nums)
if n < 3:
return 0
for i in range(n - 2):
l = i + 1
r = n - 1
while l < r:
if nums[i] + nums[l] + nums[r] < target:
res += r - l
l += 1
else:
r -= 1
return res
|
23195a6496bc08c9d14d6b17bc8cb8a6d9e40d31 | Bharanij27/bharanirep | /PyproS33.py | 146 | 3.6875 | 4 | n=input()
m=0
for i in range(1,len(n)):
if n[0]<n[i]:
m=n.index(n[i])
break
for i in range(m,len(n)):
print(n[i],end="")
|
a99421ef65ad42a5a7e99e470efadbf0f6adc5ff | abryazgin/coalesce | /tests.py | 1,128 | 3.640625 | 4 | from coalesce import coalesce, empty, first, UniqueValue
def test_unique_value():
val = UniqueValue()
assert val == val
assert val is val
assert UniqueValue() != UniqueValue()
assert UniqueValue() is not UniqueValue()
def test_empty():
assert empty == empty
assert empty is empty
assert not bool(empty)
def test_coalesce():
assert coalesce([None, 1]) is None
assert coalesce((empty, 'string', 1)) is 'string'
assert coalesce((empty, None)) is None
assert coalesce((empty, None)) is None
assert coalesce((empty, empty)) is empty
assert coalesce((empty, empty), default=1) is 1
assert coalesce((1, 1), ignore=1) is empty
assert coalesce((1, 1), ignore=1, default=-4) is -4
assert coalesce((), default=8) is 8
def test_first():
array = [0, 2, 7, None]
assert first(lambda x: x > 3, array) is 7
assert first(lambda x: x >= 0, array) is 0
assert first(lambda x: x, array) is 2
assert first(lambda x: x is None, array, default='default') is None
assert first(lambda x: x is not None and x > 10, array, default='default') is 'default'
|
bfdc1b57bc299063086672029f395539453e0c7a | eugennix/python | /Mix/St050 - translate distance.py | 1,110 | 3.890625 | 4 | '''
осуществляющую преобразование из одних единиц измерения длины в другие.
мили (1 'mile' = 1609 m), ярды (1 yard = 0.9144 m),
футы (1 foot = 30.48 cm), дюймы (1 inch = 2.54 cm),
километры (1 km = 1000 m), метры (m),
сантиметры (1 cm = 0.01 m) миллиметры (1 mm = 0.001 m)
Используйте указанные единицы измерения с указанной точностью.
<number> <unit_from> in <unit_to>
"15.5 mile in km", требуется перевести 15.5 миль в километры.
Дробное число в научном формате (экспоненциальном),
с точностью ровно два знака после запятой.
'''
trans = {'mile': 1609, 'yard': 0.9144, 'foot': 0.3048, 'inch': 0.0254,
'km': 1000, 'm': 1, 'cm': 0.01, 'mm': 0.001}
x, unit_from, _, unit_to = input().split()
x_in_m = trans[unit_from] * float(x)
x_in_unit_to = x_in_m / trans[unit_to]
print(f'{x_in_unit_to:.2e}')
|
dc88e7729578f7553f9e9e086af69ee7bbd84b73 | monkeybuzinis/Python | /3.number/1.py | 84 | 3.640625 | 4 | #1
from random import randint
for i in range(0,50):
x= randint(3,6)
print(x) |
865b2940d77dfd6bd4297ee9a27b1d63e5e89a92 | L200170155/Prak_ASD | /2_D_155.py | 11,010 | 3.6875 | 4 | Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> class Pesan(object):
"""
Sebuah class bernama Pesan.
Untuk memahami konsep Class dan Object.
"""
def __init__(self, sebuahString):
self.teks = sebuahString
def cetakIni(self):
print(self.teks)
def cetakKapital(self):
print(str.upper(self.teks))
def cetakKecil(self):
print(str.lower(self.teks))
def jumKar(self):
return len(self.teks)
def cetakJumlah(self):
print("Kalimatku mempunyai: ",len(self.teks),"karakter")
def perbarui(self, strBaru):
self.teks = strBaru
def apaTerkandung(self, isi):
if str(isi) in self.teks:
print("true")
else:
print("false")
def hitungV(self):
v = "aiueoAIUEO"
n = 0
for i in self.teks:
if i in v:
n+=1
return n
def hitungK(self):
v = "aiueoAIUEO"
n = 0
for i in self.teks:
if i not in v:
n+=1
return n
>>> kataku = Pesan("Salatiga")
>>> kataku.apaTerkandung("apa")
false
>>> kataku.apaTerkandung("iga")
true
>>> print(kataku.hitungV())
4
>>> print(kataku.hitungK())
4
>>>
>>> class Manusia(object):
"""Class manusia dengan inisiasi 'nama'"""
keadaan='lapar'
def __init__(self,nama):
self.nama = nama
def ucapSalam(self):
print("halo namaku: ", self.nama)
def makan(self,s):
print("saya baru saja makan ", s)
self.keadaan = 'kenyang'
def olah(self,k):
print('saya baru saja latihan', k)
self.keadaan='lapar'
def kali(self,n):
return n*2
>>> from nomor2 import Manusia
class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
SyntaxError: multiple statements found while compiling a single statement
>>>
= RESTART: C:/Users/TYA/AppData/Local/Programs/Python/Python36-32/nomor2.py =
>>> from nomor2 import Manusia
class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
SyntaxError: multiple statements found while compiling a single statement
>>>
= RESTART: C:/Users/TYA/AppData/Local/Programs/Python/Python36-32/nomor2.py =
>>> from nomor2 import Manusia
class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
SyntaxError: multiple statements found while compiling a single statement
>>>
= RESTART: C:/Users/TYA/AppData/Local/Programs/Python/Python36-32/nomor2.py =
>>> class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
>>> ms1=Mahasiswa('Sengkuni',420,'Solo',420000)
>>> print(ms1.ambilKota())
Solo
>>> ms1.perbaruiKota('Jogja')
>>> print(ms1.ambilKota())
Jogja
>>> print(ms1.ambilUang())
420000
>>> ms1.tambahUang(420)
>>> print(ms1.ambilUang())
420420
>>>
>>> class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
>>> nama = input("Masukkan Nama Anda : ")
Masukkan Nama Anda : Yarin Nanditya A
>>> NIM = input("Masukkan NIM Anda :")
Masukkan NIM Anda :L200170155
>>> kota = input("Masukkan Kota Asal Anda :")
Masukkan Kota Asal Anda :Madiun
>>> us = input("Masukkan Uang Saku Anda :")
Masukkan Uang Saku Anda :1000000
>>>
>>> ms2 = Mahasiswa(nama,NIM,kota,us)
>>>
>>> class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
matkul=[]
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
def ambilMK(self, mk):
self.matkul.append(mk)
def listKuliah(self):
print(self.matkul)
>>> mh3 = Mahasiswa("aa","aa","aa","aa")
>>> mh3.ambilMK("cek")
>>> mh3.listKuliah()
['cek']
>>> mh3.ambilMK("cek2")
>>> mh3.listKuliah()
['cek', 'cek2']
>>>
>>> class Mahasiswa(Manusia):
"""Class Mahasiswa yang dibangun dai class Manusia"""
matkul=[]
def __init__(self,nama,NIM,kota,us):
self.nama=nama
self.NIM=NIM
self.kota=kota
self.uang=us
def __str__(self):
s=self.nama+',NIM '+str(self.NIM)\
+'. tinggal di '+self.kota\
+'. uang saku Rp '+str(self.uang)\
+'. tiap bulan'
return s
def ambilNama(self):
return self.nama
def ambilNIM(self):
return self.NIM
def ambilUang(self):
return self.uang
def makan(self,s):
print ("saya baru saja makan",s,"sambil belajar")
self.keadaan='kenyang'
def ambilKota(self):
return self.kota
def perbaruiKota(self,k):
self.kota=k
def tambahUang(self,n):
self.uang+=n
def ambilMK(self, mk):
return self.matkul.append(mk)
def listKuliah(self):
print(self.matkul)
def hapusKuliah(self, mk):
return self.matkul.remove(mk)
>>> mh3 = Mahasiswa("aa","aa","aa","aa")
mh3.ambilMK("cek")
mh3.listKuliah()
SyntaxError: multiple statements found while compiling a single statement
>>> mh3 = Mahasiswa("aa","aa","aa","aa")
>>> mh3.ambilMK("cek")
>>> mh3.listKuliah()
['cek']
>>> mh3.ambilMK("cek2")
>>> mh3.listKuliah()
['cek', 'cek2']
>>> mh3.hapusKuliah("cek")
>>> mh3.listKuliah()
['cek2']
>>>
>>> class SiswaSMA(Manusia):
jurusan = "Belum Ditentukan"
univ = "Belum Ditentukan"
def __init__(self, nama, nisn, sma):
self.nama = nama
self.nisn = nisn
self.sma = sma
def __str__(self):
return "\n\nData Diri\n"\
+"Nama : "+self.nama\
+"\nNISN : "+str(self.nisn)\
+"\nSMA : "+self.sma\
+"\nUniv Pilihan : "+self.univ\
+"\nJurusan Pilihan : "+self.jurusan
def ambil(self):
print("\n\nUpdate Data Universitas Pilihan...")
self.univ = input("Pilih Univ : ")
self.jurusan = input("Ambil Jurusan : ")
>>> sis = SiswaSMA("a","a","aa")
>>> print(sis)
Data Diri
Nama : a
NISN : a
SMA : aa
Univ Pilihan : Belum Ditentukan
Jurusan Pilihan : Belum Ditentukan
>>> sis.ambil()
Update Data Universitas Pilihan...
Pilih Univ : Universitas Muhammadiyah Surakarta
Ambil Jurusan : Informatika
>>> print(sis)
Data Diri
Nama : a
NISN : a
SMA : aa
Univ Pilihan : Universitas Muhammadiyah Surakarta
Jurusan Pilihan : Informatika
>>>
|
c3cd45347911708291d4cd12c85f5e5568235f61 | kevin7lou/dsml-learning-roadmap-x | /01_Python Elementary/零基础学Python语言-嵩天-北理/【第6周 第二部分】交互式图形编程/ColorShapes.py | 1,201 | 3.859375 | 4 | import turtle
def main():
turtle.pensize(3)
turtle.penup()
turtle.goto(-200,-50)
turtle.pendown()
turtle.begin_fill()
turtle.color("red")
turtle.circle(40, steps=3)
turtle.end_fill()
turtle.penup()
turtle.goto(-100,-50)
turtle.pendown()
turtle.begin_fill()
turtle.color("blue")
turtle.circle(40, steps=4)
turtle.end_fill()
turtle.penup()
turtle.goto(0,-50)
turtle.pendown()
turtle.begin_fill()
turtle.color("green")
turtle.circle(40, steps=5)
turtle.end_fill()
turtle.penup()
turtle.goto(100,-50)
turtle.pendown()
turtle.begin_fill()
turtle.color("yellow")
turtle.circle(40, steps=6)
turtle.end_fill()
turtle.penup()
turtle.goto(200,-50)
turtle.pendown()
turtle.begin_fill()
turtle.color("purple")
turtle.circle(40)
turtle.end_fill()
turtle.color("green")
turtle.penup()
turtle.goto(-100,50)
turtle.pendown()
turtle.write(("Cool Colorful shapes"),
font = ("Times", 18, "bold"))
turtle.hideturtle()
turtle.done
if __name__ == '__main__':
main() |
de2a8c0487a5d88075e6021716328a89ef69a6bd | Allegheny-Computer-Science-102-F2018/classDocs | /lessons/12_week_stats/sandbox/applicationCorrelation.py | 1,180 | 3.734375 | 4 | def find_corr_x_y(x,y):
n = len(x)
# Find the sum of the products
prod = []
for xi,yi in zip(x,y): # the zip function
prod.append(xi*yi)
sum_prod_x_y = sum(prod)
sum_x = sum(x)
sum_y = sum(y)
squared_sum_x = sum_x**2
squared_sum_y = sum_y**2
x_square = []
for xi in x:
x_square.append(xi**2)
# Find the sum
x_square_sum = sum(x_square)
y_square=[]
for yi in y:
y_square.append(yi**2)
# Find the sum
y_square_sum = sum(y_square)
# Use formula to calculate correlation
numerator = n*sum_prod_x_y - sum_x*sum_y
denominator_term1 = n*x_square_sum - squared_sum_x
denominator_term2 = n*y_square_sum - squared_sum_y
denominator = (denominator_term1*denominator_term2)**0.5
correlation = numerator/denominator
return correlation
#end of find_corr_x_y(x,y)
#High_School_Grades_list
x = [90, 92, 95, 96, 87, 87, 90, 95, 98, 96]
#College_Admin_Tests_list
y = [85, 87, 86, 97, 96, 88, 89, 98, 98, 87]
result = find_corr_x_y(x,y)
print(" Set1:",x)
print(" Set2:",y)
print(" Correlation :",result)
|
f0c4ef42688af8eaa59fb59189650c4f354d5529 | jagadeshwarrao/programming | /euclideanAlgo.py | 273 | 3.890625 | 4 |
def gcd(a, b):
if a == 0 :
return b
return gcd(b%a, a)
a = 10
b = 15
print("gcd(", a , "," , b, ") = ", gcd(a, b))
a = 35
b = 10
print("gcd(", a , "," , b, ") = ", gcd(a, b))
a = 31
b = 2
print("gcd(", a , "," , b, ") = ", gcd(a, b))
|
c01e0c6f9e4f26c6392038ca2e53925db7390f5b | chaoowang/CP1404practicals | /prac_05/word_occurrences.py | 429 | 4.03125 | 4 | def main():
word_to_count = {}
text = input("Text:")
words = text.split()
for word in words:
times = word_to_count.get(word, 0)
word_to_count[word] = times + 1
words = list(word_to_count.keys())
words.sort()
max_len = max(len(word) for word in words)
for word in words:
print("{:{}} : {}".format(word, max_len, word_to_count[word]))
if __name__ == '__main__':
main()
|
117e5fc34091e519c0356e179d160ab1b94083aa | ravijaya/june08 | /psfp1.py | 173 | 3.96875 | 4 | items = [2, 1, 3, 2, 4, 5, 8]
m = map(bin, items) # functional programming
print(m)
print()
for item in m:
print(item)
print()
m = map(ord, 'peter pan')
print(list(m)) |
82d802fc25cae527dc9998188c23d93c9ca657df | candi955/Binarytree_Project | /BinaryTreeProject-master/10,000Nums_Phase3.py | 1,190 | 3.8125 | 4 | # 10,000 Numbers
# This page is part of phase 2 of the Binary Search Tree (BST) project, in which I will time various BST functions for time
# duration concerning the implementation of 100, 1000, 10000, and 100000 random numbers within a BST.
from binarytree import build
import numpy as np
import random
import time
# 10,000 Random Numbers
print("\nStarting a binary tree with 10,000 random numbers.\n\n")
randNums10000 = np.array(random.sample(range(1, 10001), 10000))
print(randNums10000)
# Putting 10,000 numbers in the tree
start10000 = time.time()
root = build(randNums10000)
end10000 = time.time()
duration10000 = end10000 - start10000
print(root)
# Deleting 10,000 numbers from the tree
deleteStart10000 = time.time()
root = build([])
endDeleteStart10000 = time.time()
durationDelete10000 = endDeleteStart10000 - deleteStart10000
print("\nPrinting the binary tree after emptying the list of/deleting 10,000 numbers: \n", root)
print("\nThe time duration to enter 10,000 random numbers into the Binary Search Tree is: ", duration10000, "seconds.")
print("\nThe time duration to delete 10,000 random numbers from the Binary Search Tree is: ", durationDelete10000, "seconds.") |
cd226c3602611964ea261c8be77bc501e356d782 | Siahnide/All_Projects | /Back-End Projects/Python/Python Fundamentals/FooandBar.py | 139 | 3.703125 | 4 | for x in range(0,25):
for y in range(2,x):
if y*y == x:
print "foo"
if
|
9349b9eb38ee2e92bfca1e91cc8a13cea897d50b | yanyiyi-yi/eval-runner-docker | /factutils/hislicing/calc_correlation.py | 750 | 3.71875 | 4 | #!/usr/bin/env python3
from scipy.stats.stats import pearsonr
data = [
[2.51, 2.75, 136, 7328],
[0.66, 0.11, 50, 1856],
[1.42, 6.05, 101, 17839],
[2.38, 4.72, 269, 9238],
[2.41, 5.31, 100, 25528],
[1.10, 2.69, 51, 2529],
[4.00, 10.7, 262, 8817],
[1.24, 0.89, 97, 8575],
[1.47, 1.05, 79, 2353]
]
def main():
cor_lof = pearsonr([x[0] for x in data], [x[1] for x in data])
cor_history_len = pearsonr([x[0] for x in data], [x[2] for x in data])
cor_loc = pearsonr([x[0] for x in data], [x[3] for x in data])
print(f"correlation coefficient: {cor_lof}")
print(f"correlation coefficient: {cor_history_len}")
print(f"correlation coefficient: {cor_loc}")
if __name__ == "__main__":
main()
|
32a1f65329f46f64b560c3f6dea2b6a4e067309e | Gwinew/To-Lern-Python-Beginner | /Pluralsight/Beginner/Core_Python_Getting_started/Module_9/3_Generator_funcions.py | 1,091 | 3.9375 | 4 | # Generator functions
#
# - Iterables defined by functions
# - Lazy evaluation
# - Can model sequences with no definite end
# - Composable into pipelines
#
###################
# yield:
#
# Generator functions must include at least one yield statement.
#
# They may also include return statements.
###################
#
#
def gen123():
yield 1
yield 2
yield 3
g = gen123()
print(g) # <generator object gen123 at ....>
print(next(g))
print(next(g))
print(next(g))
# print(next(g)) # StopIteration
for v in gen123():
print(v)
h = gen123()
i = gen123()
print(h)
print(i)
print(h is i) # False
next(h) # 1
next(h) # 2
next(i) # 1
def gen246():
print('About to yield 2')
yield 2
print('About to yield 4')
yield 4
print('About to yield 6')
yield 6
print('About to return')
g=gen246()
print(next(g)) # 2
print(next(g)) # 4
print(next(g)) # 6
# print(next(g)) # StopIteration
#
#######################################
#
# Maintaining State in Generators:
#
#
|
ae8240d908e149074978fff024de155e17b1f61e | anovacap/holbertonschool-low_level_programming | /0x1B-makefiles/5-island_perimeter.py | 486 | 3.828125 | 4 | #!/usr/bin/python3
"""island_perimeter - grid - returns the perimeter of the island described
in grid"""
def island_perimeter(grid):
"""return island perimeter"""
h = len(grid)
w = len(grid[0])
ans = 0
for i in range(h):
for j in range(w):
if grid[i][j] == 1:
if (i == 0) or (grid[i - 1][j] == 0):
ans += 2
if (j == 0) or (grid[i][j - 1] == 0):
ans += 2
return (ans)
|
6d6c9f8cde3bbbea264ec5e3aa97f5c88a7eda59 | imtengyi/oldboy | /Day1/loop_continue.py | 185 | 3.828125 | 4 | #!/usr/bin/env python3
#coding:utf-8
for i in range(5):
for j in range(10):
if j<5:
continue
if i>3:
break
print ("i=%s,j=%s"%(i,j)) |
bcef01f934a77fb94e8209d3113946d53615992e | ittakes1/test | /TrueNFalse.py | 171 | 3.78125 | 4 | a = True
print(a)
a = 2 == 2
print(a)
print("apple" == "Apple")
print("good" in "good morning")
print("專門結合運算", True or False)
print(5 > 3 - 1 and True)
|
a3308a83c4ba14c897df56d81dd3a35cbbfca020 | andyc1997/Data-Structures-and-Algorithms | /Algorithmic-Toolbox/Week3/fractional_knapsack.py | 3,069 | 3.890625 | 4 | # Uses python3
import sys
# Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
# Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
# The next n lines define the values and weights of the items. The i-th line contains integers v[i] and w[i]—the
# value and the weight of i-th item, respectively.
# Output Format. Output the maximal value of fractions of items that fit into the knapsack.
# Greedy algorithm: Take the items with maximum v[j] to w[j] ratio until the capacity is full
# If we have capacity W and j-th item has maximum ratio of values to weights. Either w[j] >= W or w[j] < W.
# Case 1: w[j] >= W
# Let i != j, i' != i and i' != j.
# If w[i] > W, then v[j]/w[j] * W > v[i]/w[i]*W implies picking j-th item as optimal.
# Otherwise, v[i] + v[i']/w[i']*(W - w[i]) < v[i]/w[i]*w[i] + v[i]/w[i]*(W - w[i]) = v[i]/w[i]*W < v[j]/w[j]*W. So, it's optimal to pick j-th item.
# Case 2: w[j] < W
# As v[j] > v[i]*w[j]/w[i], we should pick j-th item.
# In both cases, pick j-th item is a safe move.
def avoid_zero(v, w):
if w == 0: # v[j]/w[j] is undefined mathematically when w[j] = 0. Let assume the item does not exist, so return value 0
return 0
else: # Otherwise, do division
return v / w
def linear_search(weights, values):
values_per_weights = [avoid_zero(v, w) for (w, v) in zip(weights, values)] # A list with j-th index = v[j]/w[j], 0 if w[j] == 0. This procedure takes O(n)
index = 0
while weights[index] <= 0: # If the first item has 0 weights, shift by ignore it and proceed to the next item until weights[j] > 0
index += 1
for i in range(len(weights)): # Basic linear search with time complexity O(n)
if values_per_weights[i] > values_per_weights[index]:
index = i
return index
def get_optimal_value(capacity, weights, values):
value = 0 # The original value of Knapsack problem is 0 because no items
for i in range(len(weights)): # The outer loop takes O(n) and do linear search at cost O(n) at each loop, so total cost = O(n^2)
if capacity == 0: # If capacity is 0, return default value which is 0
return value
j = linear_search(weights, values) # A linear search for j-th item which has maximum ratio of values to weights
a = min(weights[j], capacity) # Check if capacity is available for the entire j-th item, if not let take the part of j-th item for the remaining capacity
value += a * values[j]/weights[j] # Accumulate the value
weights[j] -= a # Reduce the current amount of j-th item by the amount taken
capacity -= a # Reduce the current capacity of knapsacck as j-th item is included
return value
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
cc8b34bb227e365a5a2d09650fee4052cd93ccea | chettyharish/Assignments | /python-programming/oldimdb/imdb_ratings.py | 3,036 | 3.796875 | 4 | #! /bin/env/python3.4
"""
Holds movie objects and functions to create movie objects
Match user required moves and Levenshtein distance
>>> get_lvdist("Abcd","bcdr")
2
>>> Movie("Secrets of the City","1994","1.4","5").get_votes()
'5'
>>> Movie("Secrets of the City","1994","1.4","5").get_title()
'Secrets of the City'
>>> Movie("Secrets of the City","1994","1.4","5").get_year()
'1994'
>>> Movie("Secrets of the City","1994","1.4","5").get_rating()
'1.4'
>>> x = GroupMovieByElements("Atlantic\\t1952\\t70\\t5.4\\t8\\t0\\t0\\n")
>>> x.get_title()
'Atlantic'
>>> line = open("needed_movies.txt", "r").readline()
>>> record = Movie(line, 0, 0, 0)
>>> condition(Movie(line, 0, 0, 0))
True
"""
class Movie:
"""
Creates movie object
"""
def __init__(self, title, year, rating, votes):
"""
Function initialized Movie object
"""
self.votes = votes
self.rating = rating
self.year = year
self.title = title
def get_votes(self):
"""
Function returns movie votes
"""
return self.votes
def get_rating(self):
"""
Function returns movie rating
"""
return self.rating
def get_year(self):
"""
Function returns movie year
"""
return self.year
def get_title(self):
"""
Function returns movie title
"""
return self.title
def get_lvdist(name1, name2):
"""
Function calculates Levenshtein distance between two strings
"""
if len(name1) < len(name2):
name1, name2 = name2, name1
lv_mat = [[0 for i in range(len(name2) + 1)]
for j in range(len(name1) + 1)]
for i in range(len(name2) + 1):
lv_mat[0][i] = i
for j in range(len(name1) + 1):
lv_mat[j][0] = j
for in1, char1 in enumerate(list(name1)):
for in2, char2 in enumerate(list(name2)):
if char1 == char2:
lv_mat[in1 + 1][in2 + 1] = lv_mat[in1][in2]
else:
lv_mat[in1 + 1][in2 + 1] = min(lv_mat[in1][in2],
lv_mat[in1][in2 + 1],
lv_mat[in1 + 1][in2]) + 1
return lv_mat[-1][-1]
def condition(record):
"""
Function to find the min Levenshtein distance
between all movies and user named movies
"""
dist = 999
for line in open("needed_movies.txt"):
name1 = str(line).strip().lower().replace(" ", "")
name2 = record.get_title().lower().replace(" ", "")
curr_dist = get_lvdist(name1, name2)
if curr_dist < dist:
dist = curr_dist
if dist <= 3:
break
return dist <= 3
def GroupMovieByElements(line):
"""
Function creates Movie objects from the
complete file
"""
temp = line.split("\t")
new_movie = Movie(temp[0], temp[1], temp[4], temp[5])
return new_movie
|
1584f868627f808f30d450bea1332e6e71d747d8 | alvolyntsev/Python_HW_lesson4 | /hw04e03.py | 536 | 4 | 4 | # Задание-3:
# Дан список, заполненный произвольными числами.
# Получить список из элементов исходного, удовлетворяющих следующим условиям:
# + Элемент кратен 3
# + Элемент положительный
# + Элемент не кратен 4
import random
list1= [(random.randint(-1000,1000)) for _ in range(20)]
print(list1)
list2=[_ for _ in list1 if _%3==0 and _>0 and not _%4==0]
print(list2) |
09cd1d18317625546e5c6ec4c93ed169676e1e1a | schmidi/Euler | /p20.py | 257 | 3.953125 | 4 | #!/usr/bin/env python
def factorial(n):
assert n > 1
result = 1
for i in range(2, n+1):
result *= i
return result
result = factorial(100)
i = 0
sum = 0
while i < len(str(result)):
sum += int(str(result)[i])
i += 1
print sum
|
9fb608b324a8da4870bbe91b7221b3deb2e72c87 | greengrass516/test1 | /day01/demo1.py | 585 | 3.734375 | 4 | import random
print(random.randint(1,5))
a = 10
def add(x,y):
print(x+y)
class Father():
def __init__(self,name):
print("__init__",id(self))
# self代表当前对象
self.name = name
def __del__(self):
print("__del__")
def show(self):
print("name:",self.name)
class Son(Father,object):
def __init__(self,name,age):
super().__init__(name)
self.age = age
def show(self):
print(f"name:{self.name}age:{self.age}")
#print(__name__)
if __name__ == "__main__":
s = Son("AAA",18)
s.show() |
902abb37f8b344341b998f8df16deaeccf696136 | robintux/python_intro | /docs/src/chapter7/poly_repr.py | 1,144 | 4.28125 | 4 | """
The three functions here do exactly the same thing, but
use slightly different datastructures and implementation.
"""
def eval_poly_dict(poly, x):
"""
Thhe argument poly is here a dict containing
the non-zero polynomial coefficients.
"""
sum = 0.0
for power in poly:
sum += poly[power]*x**power
return sum
def eval_poly_list(poly, x):
"""
poly is here a list containing all coefficients
"""
sum = 0
for power in range(len(poly)):
sum += poly[power]*x**power
return sum
def eval_poly_list_enum(poly, x):
"""
same as above, but uses the convenient enum
function to traverse the list.
"""
sum = 0
for power, coeff in enumerate(poly):
sum += coeff*x**power
return sum
#the same polynomial represented as list and dict:
p_dict = {0: -1, 2: 1, 7: 3}
p_list = [-1, 0, 1, 0, 0, 0, 0, 3]
#evaluate polynomial for x = 2.5
x = 2.5
print(f'For x={x}:')
print(f'eval_poly_dict gives {eval_poly_dict(p_dict,x):g}')
print(f'eval_poly_list gives {eval_poly_list(p_list,x):g}')
print(f'eval_poly_list_enum gives {eval_poly_list_enum(p_list,x):g}')
|
f4a6acd2b071e928f3ec97ef83a616f5e03913ce | Python-x/Python-x | /面向对象/王者荣耀.py | 1,307 | 3.9375 | 4 | import time
p = "欢迎来到召唤师峡谷\n"
print(p)
first_name ="潘"
last_name ="志伟"
full_name = first_name+last_name
print(full_name)
age = int(input("输入你的年龄"))
if age <11:
print("你只能玩一个小时哦")
else:
print("正在进入游戏...")
q = 2
print("尊敬的召唤师,您在这局游戏中的的综合排名是%d,继续努力哦\n"%q)
list1 = ["安其拉","孙悟空","杨戬","貂蝉","扁鹊"]
print(list1)
print(list1[3])
print(list1[1])
time.sleep(2)
print("马化腾你的安其拉太菜了,换个吧")
list1[0]="狄仁杰"
print(list1)
time.sleep(2)
del list1[2]
print("杨戬的哮天犬叫他回去撒狗粮了....\n杨戬退出了组队")
time.sleep(2)
print(list1)
list1.insert(0,"兰陵王")
print(list1,"\n准备好,游戏开始")
list1.pop()
time.sleep(2)
print("您的队友扁鹊退出了游戏")
print(list1)
list1.append("扁鹊")
time.sleep(2)
print(list1)
print("第二局开始,换队长")
list1.sort()
time.sleep(2)
print(list1)
print("妈卖批,不行,还得换,他太菜")
list1.sort(reverse = True)
time.sleep(2)
print(list1)
print(sorted(list1))
list1.reverse()
print(list1)
print("就这样吧")
print(len(list1))
for i in list1:
if i == "貂蝉":
print("忍奥义之瞎JB秀--%s"%i)
else:
print("%s是一个优秀的英雄"%i)
|
1fdbc0d9e6e37ad6b172aa312b60ec142f0697db | NiuYao0033/chujizhishi | /58.py | 122 | 3.734375 | 4 | ny_info = [1,2,3,4,5]
ny_info.reverse()
print(ny_info)
print('-------------')
ny_info.sort(reverse = True)
print(ny_info)
|
ee5dba56c22b423a9d03d83905dbb9acd5c05aed | bhernan2/python-challenge | /PyBank/main.py | 2,791 | 4.09375 | 4 |
# Your task is to create a Python script that analyzes the records to calculate each of the following:
# The total number of months included in the dataset
# The net total amount of "Profit/Losses" over the entire period
# The average of the changes in "Profit/Losses" over the entire period
# The greatest increase in profits (date and amount) over the entire period
# The greatest decrease in losses (date and amount) over the entire period
#libraries needed
import os
import csv
# file location
budget_df=os.path.join("..", "PyBank", "budget_data.csv")
budget_df
#create lists
total_months = []
total_profit = []
monthly_change = []
with open("budget_data.csv", "r") as csvfile:
#create a path
csvreader = csv.reader(csvfile, delimiter = ",")
#skip column labels
header = next(csvreader, None)
#iterate through rows in budget data
for row in csvreader:
#append months and profit lists
total_months.append(row[0])
total_profit.append(int(row[1]))
#iterate through profits to get monthly changes
for i in range(len(total_profit)-1):
monthly_change.append(total_profit[i+1]-total_profit[i])
#calculate min and max values for monthly changes
max_decrease_val = min(monthly_change)
max_increase_val = max(monthly_change)
#calculate the greatest increase and decrease in profits (date and amount) over the entire period
max_increase_month = monthly_change.index(max(monthly_change)) + 1
max_decrease_month = monthly_change.index(min(monthly_change)) + 1
#print statements
print("Financial Analysis")
print(f"----------------------------")
print(f"Total Months: {len(total_months)}git ")
print(f"Total: ${sum(total_profit)}")
print(f"Average Change: ${round(sum(monthly_change)/len(monthly_change),2)}")
print(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_val))})")
print(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_val))})")
#export a text file with the results
output_path = os.path.join("Budget_Results.txt")
output_path
with open("Budget_Results.txt","w") as file:
file.write("Financial Analysis")
file.write("\n")
file.write(f"----------------------------")
file.write("\n")
file.write(f"Total Months: {len(total_months)}")
file.write("\n")
file.write(f"Total: ${sum(total_profit)}")
file.write("\n")
file.write(f"Average Change: ${round(sum(monthly_change)/len(monthly_change),2)}")
file.write("\n")
file.write(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_val))})")
file.write("\n")
file.write(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_val))})")
|
300b0c608d76b2aa2613effa6f5643f0c16d9be7 | Pawel9903/python1 | /zajecia1/zadanie9_dodatkowe.py | 533 | 3.8125 | 4 | print("Podaj współrzędne pierwszego wektora: ")
x1 = float(input("Podaj x: "))
y1 = float(input("Podaj y: "))
z1 = float(input("Podaj z: "))
t1 = float(input("Podaj t: "))
print("Podaj współrzędne drugiego wektora: ")
x2 = float(input("Podaj x: "))
y2 = float(input("Podaj y: "))
z2 = float(input("Podaj z: "))
t2 = float(input("Podaj t: "))
print("W1 = [{}, {}, {}, {}]".format(x1, y1, z1, t1))
print("W2 = [{}, {}, {}, {}]".format(x2, y2, z2, t1))
wynik = x1*x2 + y1*y2 + z1*z2 + t1*t2
print("W1 * W2 = {}".format(wynik))
|
dab06c77f271abae5c6e651f4a9aba019bbf7a60 | Carrot97/LeetCodeClassic | /fast&slow_point/876_middleNode.py | 795 | 4.09375 | 4 | """
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def middleNode(head: ListNode) -> ListNode:
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if fast.next:
return slow.next
return slow
|
19f4f420f963cdde444015fb43007abac586ea0e | sunilmummadi/Array-2 | /disappearingNums.py | 1,641 | 3.546875 | 4 | # Leetcode 448. Find All Numbers Disappeared in an Array
# Time Complexity : Hashmap & in place: O(n) where n is the size of the array
# Space Complexity : O(1) for inplace and O(n) for hashmap
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Iterate over array with high and low pointers from the ends. If area is greater than maxx
# replace it.
# Your code here along with comments explaining your approach
class Solution:
# Using additional hashmap for counting the elements Space Complexity O(n) length of hashmap
def findDisappearedNumbers2(self, nums: List[int]) -> List[int]:
size = len(nums)
result = []
counter = dict()
# Adding the values into hashmap and ignoring duplicates
for i in nums:
counter[i] = 1
# Checking the hashmap for every number in the range and appending them to result if absent
for i in range(1, size+1):
if i not in counter:
result.append(i)
return result
# Using -1 as a way to mark a value as visited
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
size = len(nums)
result = []
# Getting index from the value and marking the value at that index as visited
for i in range(size):
index = abs(nums[i])-1
nums[index] = abs(nums[index])*-1
print(nums)
# If the value is not marked as visited then return that index
for i in range(size):
if nums[i] > 0:
result.append(i+1)
return result
|
19a4d6f4fb2b9f743c0205e48222010b63cee150 | liulxin/python3-demos | /micr/01.print.py | 305 | 3.734375 | 4 | print('hello world')
print("hello world")
name = input('Please enter your name: ')
print(name)
print()
print('Did you see that blank line?')
print('Blank line \nin the middle of string')
print('Adding numbers')
x = 42 + 206
print('Perforing division')
y = x / 0
print('Math complete') |
7becb1af1bbf1f1078f30c72936209982ba0ac96 | pearsonlab/penaltyshot_task | /utils.py | 2,592 | 3.984375 | 4 | from psychopy import core, visual
from psychopy.visual.circle import Circle
class Flicker(Circle):
"""
Creates a flickering circle in the upper right corner of the screen.
This is to be used as a timing marker by a photodiode.
The presence or absence of the circle marks out an 8-bit binary pattern,
flanked at the beginning and end by a 1 (e.g., 5 is 1000001011).
"""
def __init__(self, win, radius=0.04, pos=(0.84, 0.44), **kwargs):
self.win = win
self.bitpattern = None
self.counter = None
self.timer = core.MonotonicClock()
kwargs['radius'] = radius
kwargs['pos'] = pos
# we want to override these
kwargs['fillColorSpace'] = 'rgb255'
kwargs['lineColorSpace'] = 'rgb255'
kwargs['lineColor'] = None
kwargs['units'] = 'height'
kwargs['autoDraw'] = True
super(Flicker, self).__init__(win, **kwargs)
def flicker(self, code):
"""
Start the flicker. code is an integer between 0 and 255 (=2^8).
Calling this again before the sequence has finished will
restart the flicker.
"""
# convert to binary, zero pad to 8 bits, and add stop and start bits
self.bitpattern = '1{:08b}1'.format(code)
self.counter = 0
def flicker_block(self, code):
"""
Blocking version of flicker. The entire task will pause until the flicker is done. Returns the time of execution of the function.
This is not best practice, but can be used in code that does not
run a single event loop where flicker can be used.
"""
start_time = self.timer.getTime()
self.flicker(code)
while self.bitpattern:
self.win.flip()
end_time = self.timer.getTime()
return end_time - start_time
def draw(self):
"""
Draw the circle. Change its color based on the bitpattern and forward
to the draw method for the circle.
"""
if self.bitpattern:
# if we've reached the end of the pattern
if self.counter >= len(self.bitpattern):
self.bitpattern = None
self.setFillColor(self.win.color, log=False)
else:
if self.bitpattern[self.counter] == '1':
self.setFillColor((255, 255, 255), log=False)
else:
self.setFillColor((0, 0, 0), log=False)
# increment position in bit pattern
self.counter += 1
super(Flicker, self).draw()
|
410f613c9436205bf578656b451422efc8b62bc1 | brianhuey/Netflix | /baseline/user_center_time/user_center_time_reducer.py | 2,054 | 3.640625 | 4 | #!/usr/bin/env python
import sys, math
""" Calculates the average and centers the user sqrt(time) value around the mean
Output: Data input with centered sqrt(time last rated)"""
current_user = None
user_list = []
total = 0
count = 0
for line in sys.stdin:
user, movie, rating, date, movie_avg, user_avg, centered_movie_time, user_time = line.strip().split("\t", 7)
if current_user == user:
user_list.append([movie, user, rating, date, movie_avg, user_avg,
centered_movie_time, user_time])
count += 1
else:
if current_user:
for i in range(0, len(user_list)):
total += float(user_list[i][7])
for j in range(0, len(user_list)):
movieid = user_list[j][0]
rating = user_list[j][2]
date = user_list[j][3]
movie_avg = user_list[j][4]
user_avg = user_list[j][5]
centered_movie_time = user_list[j][6]
user_time = float(user_list[j][7])
centered_user_time = user_time - (total/count)
print '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (movieid, current_user, rating,
date, movie_avg, user_avg, centered_movie_time, centered_user_time)
user_list = [[movie, user, rating, date, movie_avg, user_avg, centered_movie_time, user_time]]
count = 1
total = 0
current_user = user
if user == current_user:
for i in range(0, len(user_list)):
total += float(user_list[i][7])
for j in range(0, len(user_list)):
movieid = user_list[j][0]
rating = user_list[j][2]
date = user_list[j][3]
movie_avg = user_list[j][4]
user_avg = user_list[j][5]
centered_movie_time = user_list[j][6]
user_time = float(user_list[j][7])
centered_user_time = user_time - (total/count)
print '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s' % (movieid, current_user, rating, date,
movie_avg, user_avg, centered_movie_time, centered_user_time) |
2ed6e071ac5e6c37ca1bb30e65fe15deb843f041 | NightDriveraa/Python-100-Days | /Days11/plus.py | 322 | 4.0625 | 4 | print('Enter two number')
while(True):
try:
num1 = input('first_number: ')
number1 = int(num1)
num2 = input('second_number: ')
number2 = int(num2)
except ValueError:
print('请输入数字')
continue
else:
answer = number1 + number2
print(answer) |
446a2304dc6ddc1496c5a4e4a9f1aed8931ea4c4 | 55is666/python20210201 | /1-6.py | 350 | 3.875 | 4 | point=int(input('學生分數'))
if point>100 or point<0:
print("別亂打行不行")
elif point>=90:
print("A?你作弊!!")
elif point>=80:
print("B?你抄錯了吧?(答案)")
elif point>=70:
print("C!笑你")
elif point>=60:
print("D!你有臉看我嗎?")
else:
print("E!重新投胎分數比較高啦!")
|
66e1eeff9ef129f73180dee8721fcb331336ee1f | fmarculino/CursoEmVideo | /ExMundo2/Ex049.py | 258 | 4.09375 | 4 | """
Refaça o desafio 009, mostrando a tabuada de um número que o usuário
esolhe, só que agora utilizando um laço for.
"""
n = int(input('Digite um número: '))
print('-' * 12)
for c in range(1, 11):
print(f'{n} x {c:2} = {n * c:3}')
print('-' * 12)
|
0ef27a330bd68e178e31f41eafb22e1f0059afeb | haodongxi/leetCode | /19.py | 1,110 | 3.8125 | 4 | from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
j = n-1
twoHead = head
temphead = head
lastNode = None
while j > 0:
twoHead = twoHead.next
j = j-1
while True and twoHead!=None:
if twoHead.next == None:
if lastNode == None:
if head.next!=None:
head = head.next
break
else:
return None
lastNode.next = temphead.next
break
else:
twoHead = twoHead.next
lastNode = temphead
temphead = temphead.next
return head
if __name__ == "__main__":
s = Solution()
alist = [1]
head = ListNode(1)
first = head
for a in alist[1:]:
head.next = ListNode(a)
head = head.next
print(s.removeNthFromEnd(first,0))
|
0f05d7f17da213ea6d6c26436d705772454addb2 | 0112nga/hw | /Week2/pr2.py | 1,042 | 4.0625 | 4 |
date=input('Enter a date(mm/dd/yyyy): ')
replace=date.replace('/',' ')
convert=replace.split()
if convert[0]=='01':
print('January '+convert[1]+', '+convert[2] )
elif convert[0]=='02':
print('February '+convert[1]+', '+convert[2] )
elif convert[0]=='03':
print('March '+convert[1]+', '+convert[2] )
elif convert[0]=='04':
print('April '+convert[1]+', '+convert[2] )
elif convert[0]=='05':
print('May '+convert[1]+', '+convert[2] )
elif convert[0]=='06':
print('June '+convert[1]+', '+convert[2] )
elif convert[0]=='07':
print('July '+convert[1]+', '+convert[2] )
elif convert[0]=='08':
print('August '+convert[1]+', '+convert[2] )
elif convert[0]=='09':
print('September '+convert[1]+', '+convert[2] )
elif convert[0]=='10':
print('October '+convert[1]+', '+convert[2] )
elif convert[0]=='11':
print('November '+convert[1]+', '+convert[2] )
elif convert[0]=='12':
print('December '+convert[1]+', '+convert[2] )
|
d3d57e422784400c6775a0d43c445f2ceb80706f | spycc/AccountManagement | /Flow.py | 2,300 | 3.671875 | 4 | from Func import Func
from Proving import Proving
class Flow():
'''
系统流程控制器
1.查询分支
2.添加分支
3.修改分支
4.删除分支
5.退出分支
'''
@classmethod
def flowmain(cls):
flowlist = {'1': cls.__flowquery, '2': cls.__flowadd,
'3': cls.__flowrevise, '4': cls.__flowdel, '5': cls.__flowout}
print('欢迎来到帐号管理系统:\n查询帐号(1)\n添加帐号(2)\n修改帐号(3)\n删除帐号(4)\n退出(5)')
user = input()
flowlist.get(user, cls.__errmaininput)()
@classmethod
def __flowquery(cls):
'''
查询流程分支
'''
print('选择查询方式:\n查询全部(1)\n信息搜索(2)')
a = Proving.prtwochoose()
if a == '1':
Func.funcqueryall() #查询全部数据
cls.flowmain()
else:
print('请输入搜索信息')
seach = input()
Func.funcqueryone(seach) # 搜索数据
cls.flowmain()
@classmethod
def __flowadd(cls):
'''
添加流程分支
'''
a = '1'
while a == '1':
Func.funcadd()
print('按1继续添加,按2返回')
a = Proving.prtwochoose()
else:
cls.flowmain()
@classmethod
def __flowrevise(cls):
'''
修改流程分支
'''
a = '1'
while a == '1':
Func.funcrevise()
print('按1继续修改,按2返回')
a = Proving.prtwochoose()
else:
cls.flowmain()
@classmethod
def __flowdel(cls):
'''
删除流程分支
'''
a = '1'
while a == '1':
Func.funcdel()
print('按1继续删除,按2返回')
a = Proving.prtwochoose()
else:
cls.flowmain()
@classmethod
def __flowout(cls):
'''
退出流程分支
'''
print('感谢您的使用,再见!')
@classmethod
def __errmaininput(cls):
'''
主流程输入错误提示
'''
print('您输入的指令有误,请重新输入')
cls.flowmain()
|
517d839fbbe4ad585393953f97487e2e34faedf1 | gouyanzhan/daily-learnling | /class_08/class_03.py | 1,627 | 4.15625 | 4 | #继承
class RobotOne:
def __init__(self,year,name):
self.year = year
self.name = name
def walking_on_ground(self):
print(self.name + "只能在平地上行走")
def robot_info(self):
print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name))
#继承
class RobotTwo(RobotOne):
def walking_on_ground(self): #子类里面的函数名和父类函数名重复的时候,就叫重写
print(self.name + "可以在平地平稳地上行走")
def walking_avoid_block(self): #拓展
#我想在子类的函数里面调用父类的一个函数
self.robot_info()
print(self.name + "可以避开障碍物")
#继承的类 是否要用到初始化函数 请看是否从父类里面继承了
#1:父类有的,继承后,我都可以直接拿来用
#2:父类有,子类也有重名的函数,那么子类的实例就优先调用子类的函数
#3:父类没有,子类
r2= RobotTwo("1990","小王")
r2.robot_info()
r2.walking_on_ground()
r2.walking_avoid_block()
class RobotThree(RobotTwo,RobotOne): #第三代机器人继承第一代和第二代
def __init__(self,year,name):
self.year = year
self.name = name
def jump(self):
print(self.name + "可以单膝跳跃")
r3 = RobotThree("2000","大王")
r3.robot_info()
#多继承的子类具有两个父类的属性和方法,
# 如果两个父类具有同名方法的时候,子类调用函数就近原则,谁在前就继承谁的
# 初始化函数也包括在内(就近父类无,子类可以重写初始化函数)
|
c86498ed6a5db366bae53c342f92fb1d1d749db7 | shuaiqixiaopingge/leetcode | /145_binaryTreePostorderTraversal.py | 1,334 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 21:57:05 2019
@author: LiuZiping
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root):
"""
param: root treeNode
return: List[int]
"""
"""
后序遍历的方法:
首先把各个父节点和其左右子节点都压入栈中
注意出栈时,要判断其是否满足两个条件之一:
1.为子叶节点
2.其左右子节点都已经出栈
"""
if not root:
return []
stack = [root]
res = []
p = root
"""
若栈中的最后一个节点的左子节点或者右子节点已经出栈
那么这个节点应该出栈(其左右子节点都已经出栈了)
"""
while stack:
top = stack[-1]
if top.left == p or top.right == p or (top.left == None and top.right == None):
p = stack.pop()
res.append(p.val)
else:
if top.right:
stack.append(top.right)
if top.left:
stack.append(top.left)
return res |
f74f0cccc970089cb9219e011418c5194edc5387 | AlexLymar/itstep | /lesson14/intersect.py | 208 | 3.78125 | 4 | def intersect(tup):
e = set.intersection(*map(set, tup))
e = tuple(e)
print('Rezult: ',e)
tup1 = (4, 2, 6, 7)
tup2 = (1, 2, 7, 2, 9)
tup3 = (2, 2, 2, 7, 1)
tup = tup1, tup2, tup3
intersect(tup)
|
c7b7eb4d770948ed3bd53980657a0b0327f745c1 | mralimov/Guess-my-number-python | /main.py | 1,239 | 4.21875 | 4 | from art import logo
import random
print(logo)
print("Welcome to Guess My Number Game!\n")
print("I'm thinking of a number between 1 and 100.")
game_level = input("Choose a difficulty. Type 'easy' or 'hard': ").lower()
def level_choice(choice):
if choice == "easy":
easy_life = 10
return easy_life
else:
hard_life = 5
return hard_life
level_choosen = level_choice(game_level)
def random_num(length):
random_number = random.randint(1, int(length * 10))
return random_number
random_guess = random_num(level_choosen)
print(random_guess)
correct_answer = False
while not correct_answer:
if level_choosen == 0:
correct_answer = True
print("You run out attempts to guess a number")
else:
print(f"You have {level_choosen} attempts to guess the number")
user_guess = int(input("Make a guess. "))
if user_guess > random_guess:
print(' "Too high."')
print('"Guess again"')
level_choosen -= 1
elif user_guess == random_guess:
print(f"You WIN!!! Answer was {random_guess}")
correct_answer = True
else:
print('"Too low"')
level_choosen -= 1
|
447472cda92404e744dd0d479aef48860db6c30c | seeprybyrun/project_euler | /problem0072.py | 6,711 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# Consider the fraction, n/d, where n and d are positive integers. If n<d and
# HCF(n,d)=1, it is called a reduced proper fraction.
#
# If we list the set of reduced proper fractions for d ≤ 8 in ascending order
# of size, we get:
#
# 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3,
# 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
#
# It can be seen that there are 21 elements in this set.
#
# How many elements would be contained in the set of reduced proper fractions
# for d ≤ 1,000,000?
import time
import math
import numbertheory as nt
import itertools as it
import operator
from fractions import gcd
from copy import copy
from math import floor,sqrt,log
def prod(iterable):
return reduce(operator.mul, iterable, 1)
t0 = time.clock()
answer = -1
# answer should be:
# \sum_{k=2}^n \phi(k) = \frac{1}{2}((\sum_{k=1}^n \mu(k) \floor{n/k}^2) - 1)
# where \mu(k) = 0 if k isn't squarefree and otherwise (-1)^{\# of distinct prime factors of k}
# so this reduces to computing the sum over all products of distinct prime factors such that the product is
# at most n
# a prime greater than n/2 must appear by itself
# note that no two primes greater than sqrt(n) can be multiplied together
# no three primes greater than cbrt(n) can be multiplied together
# no four primes greater than n**(0.25) can be multiplied together
# etc
# since 7# (seven primorial) < 10**6 and 8# > 10**6, only need to consider products of 7 or fewer primes
MAX = 10**6
#unchecked = set(range(2,MAX+1))
primes = nt.allPrimesLessThan2(MAX+1)
t1 = time.clock()
smallerThan7thRoot = [p for p in primes if p <= MAX**(1./7)]
primes7 = smallerThan7thRoot
n7 = len(primes7)
smallerThan6thRoot = [p for p in primes[n7:] if p <= MAX**(1./6)]
primes6 = primes7 + smallerThan6thRoot
n6 = len(primes6)
smallerThan5thRoot = [p for p in primes[n6:] if p <= MAX**(1./5)]
primes5 = primes6 + smallerThan5thRoot
n5 = len(primes5)
smallerThan4thRoot = [p for p in primes[n5:] if p <= MAX**(1./4)]
primes4 = primes5 + smallerThan4thRoot
n4 = len(primes4)
smallerThan3rdRoot = [p for p in primes[n4:] if p <= MAX**(1./3)]
primes3 = primes4 + smallerThan3rdRoot
n3 = len(primes3)
smallerThan2ndRoot = [p for p in primes[n3:] if p <= sqrt(MAX)]
primes2 = primes3 + smallerThan2ndRoot
n2 = len(primes2)
smallerThanHalf = [p for p in primes[n2:] if p <= MAX/2]
primesHalf = primes2 + smallerThanHalf
smallerThanSixth = [p for p in primes[n2:] if p <= MAX/6]
primesSixth = primes2 + smallerThanSixth
smallerThan30th = [p for p in primes[n2:] if p <= MAX/30]
primes30th = primes2 + smallerThan30th
smallerThan210th = [p for p in primes[n2:] if p <= MAX/210]
primes210th = primes2 + smallerThan210th
smallerThan2310th = [p for p in primes[n2:] if p <= MAX/2310]
primes2310th = primes2 + smallerThan2310th
smallerThan30030th = [p for p in primes[n2:] if p <= MAX/30030]
primes30030th = primes2 + smallerThan30030th
print '0 primes: 1'
print '1 prime: {}'.format(len(primes))
print '2 primes: {}*{}'.format(n2,len(primesHalf))
print '3 primes: {}*{}*{}'.format(n3,n2,len(primesSixth))
print '4 primes: {}*{}*{}*{}'.format(n4,n3,n2,len(primes30th))
print '5 primes: {}*{}*{}*{}*{}'.format(n5,n4,n3,n2,len(primes210th))
print '6 primes: {}*{}*{}*{}*{}*{}'.format(n6,n5,n4,n3,n2,len(primes2310th))
print '7 primes: {}*{}*{}*{}*{}*{}*{}'.format(n7,n6,n5,n4,n3,n2,len(primes30030th))
# first do mu(1)
answer += MAX**2
# single primes (ALL the primes, not just primes1)
for p in primes:
x = p
## print x
answer -= (MAX/x)**2
# double primes (at least one must be <= n**1/2 in size)
for i2,p2 in enumerate(primes2):
for p1 in primesHalf[i2+1:]:
x = p2*p1
if x > MAX: break
## print x
answer += (MAX/x)**2
# triple primes (at least one must be <= small, at least two must be <= large)
for i3,p3 in enumerate(primes3):
for i2,p2 in enumerate(primes2[i3+1:]):
if p3*p2 > MAX: break
for p1 in primesSixth[i3+i2+2:]:
x = p3*p2*p1
if x > MAX: break
## print x
answer -= (MAX/x)**2
# quad primes (at least one must be <= smaller, two <= medium, three <= large):
for i4,p4 in enumerate(primes4):
for i3,p3 in enumerate(primes3[i4+1:]):
if p4*p3 > MAX: break
for i2,p2 in enumerate(primes2[i4+i3+2:]):
if p4*p3*p2 > MAX: break
for p1 in primes30th[i4+i3+i2+3:]:
x = p4*p3*p2*p1
if x > MAX: break
## print x
answer += (MAX/x)**2
# five primes
for i5,p5 in enumerate(primes5):
for i4,p4 in enumerate(primes4[i5+1:]):
if p5*p4 > MAX: break
for i3,p3 in enumerate(primes3[i5+i4+2:]):
if p5*p4*p3 > MAX: break
for i2,p2 in enumerate(primes2[i5+i4+i3+3:]):
if p5*p4*p3*p2 > MAX: break
for p1 in primes210th[i5+i4+i3+i2+4:]:
x = p5*p4*p3*p2*p1
if x > MAX: break
## print x
answer -= (MAX/x)**2
# six primes
for i6,p6 in enumerate(primes6):
for i5,p5 in enumerate(primes5[i6+1:]):
if p6*p5 > MAX: break
for i4,p4 in enumerate(primes4[i6+i5+2:]):
if p6*p5*p4 > MAX: break
for i3,p3 in enumerate(primes3[i6+i5+i4+3:]):
if p6*p5*p4*p3 > MAX: break
for i2,p2 in enumerate(primes2[i6+i5+i4+i3+4:]):
if p6*p5*p4*p3*p2 > MAX: break
for p1 in primes2310th[i6+i5+i4+i3+i2+5:]:
x = p6*p5*p4*p3*p2*p1
if x > MAX: break
## print x
answer += (MAX/x)**2
# seven primes
for i7,p7 in enumerate(primes7):
for i6,p6 in enumerate(primes6[i7+1:]):
if p7*p6 > MAX: break
for i5,p5 in enumerate(primes5[i7+i6+2:]):
if p7*p6*p5 > MAX: break
for i4,p4 in enumerate(primes4[i7+i6+i5+3:]):
if p7*p6*p5*p4 > MAX: break
for i3,p3 in enumerate(primes3[i7+i6+i5+i4+4:]):
if p7*p6*p5*p4*p3 > MAX: break
for i2,p2 in enumerate(primes2[i7+i6+i5+i4+i3+5:]):
if p7*p6*p5*p4*p3*p2 > MAX: break
for p1 in primes30030th[i7+i6+i5+i4+i3+i2+6:]:
x = p7*p6*p5*p4*p3*p2*p1
if x > MAX: break
## print x
answer -= (MAX/x)**2
answer /= 2
t2 = time.clock()
print 'answer: {}'.format(answer)
print 'seconds elapsed: {}'.format(t2-t0)
print '(not including sieve): {}'.format(t2-t1)
|
db50cc89638ab3761d2fb18f56384fdc06c75a88 | SumanthRH/EE5120_Linear_Algebra | /gaussian_elimination.py | 3,790 | 3.953125 | 4 | import numpy as np
import argparse
import sys
''' Lets put down the algorithm first!
1) Start at (0,0) look for a non zero element in 0th column, swap rows if neccessary
2) normalize to make the (0,0)th element = 1. Now, subtract row1 from other rows so that the
0th column is = e1 (ie. it looks like 1,0,0.....)
3) Move to (1,1). Repeat above procedure. Similarly for the rest
4) If no nonzero elemment is present at and below the (i,i)th element, skip the column
'''
def swap_rows(M,a_ind,b_ind):
'''' Swaps two rows of a numpy array'''
M[[a_ind,b_ind]] = M[[b_ind,a_ind]]
return M
def check_zero_rows(M):
''' Check if any row is a zero vector '''
row_inds = []
for row_ind in range(M.shape[0]):
row = M[row_ind]
if np.count_nonzero(row) == 0:
row_inds.append(row_ind)
return row_inds
def check_nz_col(M, col_ind,row_ind):
''' Checks if column col indexed with col_ind of matrix M has a non zero value at index row_ind
Swaps rows from below incase col[row_ind] = 0
Skips a column if no non zero value exists at and below row_ind. If such a column is the last one,
then it returns the matrix unchanged.
Else, returns M with entry 1 at desired index and the corresponding column index
'''
col = M[:,col_ind]
if col[row_ind] != 0 :
#Normalize by diving by the value at row_ind
M[row_ind] = M[row_ind]/col[row_ind]
return M,col_ind
elif col[row_ind:].any() != 0:
#If any non zero value exists below given index row_ind, swap rows
nz_inds = np.asarray(np.nonzero(col))
nz_ind = nz_inds[nz_inds > row_ind][0]
M = swap_rows(M,row_ind,nz_ind)
M[row_ind] = M[row_ind]/M[row_ind,col_ind]
return M,col_ind
else :
#Case when the col has no non zero entry at and beyond row_ind
if col_ind == M.shape[1]-1:
return M,None # case when no further simplification is possible
# Skip one column
return check_nz_col(M,col_ind+1,row_ind)
def reduce_rows_below(M,col_ind,row_ind):
M[row_ind+1:,:] = M[row_ind+1:,:] - (np.expand_dims(M[row_ind+1:,col_ind],axis=1))*M[row_ind]
return M
def GE(M):
'''
Performs gaussian elimination for a matrix M.
It is assumed that the columns of the transformation matrix
have been transposed so that row reduction can be performed.
returns : array in Row Reduced Echelon Form
'''
col_ind = 0
row_ind = 0
while row_ind < M.shape[0] :
z_inds = check_zero_rows(M)
if len(z_inds) > 0:
# This means M[z_ind] is a zero vector
rows = [n for n in range(M.shape[0]) if n not in z_inds]
M = M[rows,:]
if row_ind >= M.shape[1] or row_ind >= M.shape[0]:
return M
M,col_ind = check_nz_col(M,col_ind,row_ind)
# print('After column choosing :\n' ,M)
if col_ind == None :
return M
M = reduce_rows_below(M,col_ind,row_ind)
# print('Row reduction : \n',M)
col_ind +=1
row_ind += 1
return M
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--array',default = '1,2,3.2,3,4',type = str,
help = 'Input Matrix to be reduced in a11,a12,a13.a21,a22,a23.... format')
args = parser.parse_args()
array = args.array
array = array.split('.')
array = [a.split(',') for a in array]
# M = [[0,1,-1,2,0],[1,0,1,2,-1],[0,0,0,1,0],[1,1,0,5,-1]]
# M = [[1,2,-1,0],[0,3,1,4],[-1,1,2,4],[2,3,1,5]]
# M = [[2,2,3]]
M = np.asarray(array,dtype=np.float32)
print('Input matrix :\n {}'.format(M))
print('Matrix after Gaussian Elimination :\n {}' .format(GE(M)))
|
b08e2d4d87938594f3be11f6a16f5c66459e3dc6 | lgonline/mp | /src/practices/github/scripts/load_json_without_dupes.py | 637 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: v1.0
@author: 330mlcc
@Software: PyCharm
@license: Apache Licence
@Email : mlcc330@hotmail.com
@contact: 3323202070@qq.com
@site:
@software: PyCharm
@file: load_json_without_dupes.py
@time: 18-6-12 下午11:46
Description:
"""
ordered_pairs = {'1':'111','2':'222','3':'333'}
def main(ordered_pairs):
my_dict = dict()
for key,value in ordered_pairs:
if key in my_dict:
raise ValueError("Duplicate key:{}".format(key,))
else:
my_dict[key] = values
return my_dict
pass
if __name__ == '__main__':
main()
pass
|
9f7497e7e0d38e4316eef1ec1ec834c92a531024 | cucy/learnlanguage | /python/并发编程/29_阻碍.py | 1,948 | 3.609375 | 4 | import threading
import time
import random
class myThread(threading.Thread):
def __init__(self, barrier):
threading.Thread.__init__(self)
self.barrier = barrier
def run(self):
print("Thread {} working on something".format(threading.current_thread()))
time.sleep(random.randint(1, 10))
print("Thread {} is joining {} waiting on Barrier".format(threading.current_thread(),
self.barrier.n_waiting))
self.barrier.wait()
print("Barrier has been lifted, continuing with work")
barrier = threading.Barrier(4)
threads = []
for i in range(4):
thread = myThread(barrier)
thread.start()
threads.append(thread)
for t in threads:
t.join()
"""
把它分解
如果我们看一下前面的代码,我们已经定义了一个自定义类myThread,它继承了thread . thread。在这个类中,
我们定义了标准__init__函数和run函数。我们的__init__函数接受我们的barrier对象,以便以后可以引用它。
在我们的运行函数中,我们模拟我们的线程在1到10秒之间随机地做一些工作,然后我们开始在barrier上等待。
根据我们的类定义,我们首先通过调用barrier = thread . barrier(4)来创建barrier对象。
我们将其作为一个参数传递的4表示在它将被取消之前必须在barrier上等待的线程数。然后我们继续定义四个不同的线程,并将它们全部连接起来。
输出
如果您在您的系统上运行前面的程序,您应该希望看到类似如下的输出。
你会看到我们的四个线程打印出它们正在处理某个东西,然后,一个接一个地,它们会随机地开始等待我们的barrier对象。一旦第4个线程开始等待,程序几乎立即完成,因为所有的四个线程都完成了最后的打印声明,现在这个屏障已经被解除了。
""" |
7efae363eff1c1510c6ae17672b041d3297d17bc | ATUL786pandey/python_prac_codewithharry | /tuple_method.py | 197 | 4.03125 | 4 | t = (1,2,3,3,5,"apple")
#print(t)
#print(type(t))
print(t.index("apple"))#it will return the index no of the parameter
print(t.count(3))#it will give the no of times 3 occur in the tuple
|
0e68d4769e93c18f83e68b16e49e7c28fa727d98 | haiduowad/BlackJack | /CapstoneProject2.py | 6,161 | 3.53125 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,'Queen':10, 'King':10, 'Ace':11}
playing = True
class Card():
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return "{} of {}".format(self.rank,self.suit)
class Deck():
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit,rank))
def __str__(self):
self.deckdisplay = ""
for card in self.deck:
self.deckdisplay +="{} of {}\n".format(card.rank,card.suit)
return self.deckdisplay
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
dealed_card = self.deck.pop()
return dealed_card
class Hand():
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self,deck):
self.added_card = deck.deal()
self.cards.append(self.added_card)
self.value += values[self.added_card.rank]
def adjust_for_ace(self):
if self.added_card.rank == "Ace" and self.value > 21:
self.value -= -10
class Chips():
def __init__(self):
self.total = 100
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
taken_bet = int(input("Please enter the amount you want to bet:"))
except:
print("Please enter an integer only")
continue
else:
if taken_bet > player_chips.total:
print("You cannot exceed your total number of chips")
continue
elif taken_bet == 0:
print("You cannot bet 0")
continue
chips.bet = taken_bet
break
def hit(deck,hand):
hand.add_card(game_deck)
hand.adjust_for_ace()
def hit_or_stand(deck,hand):
global playing
while playing:
option = str(input("Do you want to hit(h) or stand(s)?"))
if option.lower() == "h":
hit(deck,hand)
print("You recived {} of {}".format(hand.added_card.rank,hand.added_card.suit))
print("Your hand value is {}".format(hand.value))
continue
elif option.lower() == "s":
playing = False
else:
print("Please enter h or s")
continue
def show_some(player,dealer):
print("The dealer's card is:")
print("{} of {}".format(dealer.cards[0].rank,dealer.cards[0].suit))
print("The player's cards are:")
for card in player.cards:
print("{} of {}".format(card.rank,card.suit))
print("The player's hand value is {}".format(player.value))
def show_all(player,dealer):
print("The dealer's card are:")
for card in dealer.cards:
print("{} of {}".format(card.rank,card.suit))
print("The player's cards are:")
for card in player.cards:
print("{} of {}".format(card.rank,card.suit))
def player_busts(player):
if player.value > 21:
return True
else:
return False
def player_wins(player,dealer):
if player_busts(player) == False and (player.value > dealer.value or dealer_busts(dealer) == True):
return True
else:
return False
def dealer_busts(dealer):
if dealer.value > 21:
return True
else:
return False
def dealer_wins(player,dealer):
if dealer_busts(dealer) == False and (dealer.value > player.value or player_busts(player) == True):
return True
else:
return False
def push(player,dealer,chips):
if player_wins(player,dealer) == True or dealer_busts(dealer) == True:
print("The player has won!")
chips.win_bet()
else:
print("The dealer has won!")
chips.lose_bet()
print("Welcome to Tareq's Black Jack Game!")
player_chips = Chips()
while True:
game_deck = Deck()
game_deck.shuffle()
player_hand = Hand()
dealer_hand = Hand()
player_hand.add_card(game_deck)
player_hand.adjust_for_ace()
player_hand.add_card(game_deck)
player_hand.adjust_for_ace()
dealer_hand.add_card(game_deck)
dealer_hand.adjust_for_ace()
dealer_hand.add_card(game_deck)
dealer_hand.adjust_for_ace()
# Set up the Player's chips
take_bet(player_chips)
show_some(player_hand,dealer_hand)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
hit_or_stand(game_deck,player_hand)
# Show cards (but keep one dealer card hidden)
#show_some(player_hand,dealer_hand)
# If player's hand exceeds 21, run player_busts() and break out of loop
if player_busts(player_hand) == True:
print("The player has busted!")
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
while dealer_hand.value < 17:
dealer_hand.add_card(game_deck)
dealer_hand.adjust_for_ace()
show_all(player_hand,dealer_hand)
print("The dealer's hand value is "+str(dealer_hand.value))
print("The player's hand value is "+str(player_hand.value))
if dealer_busts(dealer_hand) == True:
print("The dealer has busted!")
break
# Show all cards
# Run different winning scenarios
player_wins(player_hand,dealer_hand)
dealer_wins(player_hand,dealer_hand)
push(player_hand,dealer_hand,player_chips)
# Inform Player of their chips total
print("The player's chips total is "+str(player_chips.total))
# Ask to play again
while True:
again = str(input("Do you want to play again (y/n):"))
if again.lower() == "y":
playing = True
break
elif again.lower() == "n":
playing = False
exit()
else:
print("Please enter y or n")
continue
|
4372b49ff2023aeedb0b4efcde9d98c9b7c1f68a | ahmedsaeed-dev/PracticePythonExercieses | /ListLessThanTen.py | 414 | 4.21875 | 4 | """
https://www.practicepython.org/exercise/2014/02/15/03-list-less-than-ten.html
Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
value = int(input("Enter number to search for values in list less than it: "))
print([b for b in a if b < value])
|
5327b92cebace076fbc7501978bbb51b0ee78333 | PolonaS/pubmed-abstracts | /lib/schwartz_test.py | 1,411 | 3.578125 | 4 | import unittest
from schwartz import is_valid_short_form, has_letter, has_capital, extract_pairs
class SchwartzTest(unittest.TestCase):
def test_is_valid_short_form(self):
self.assertTrue(is_valid_short_form("abc"))
self.assertTrue(is_valid_short_form("1abc"))
self.assertTrue(is_valid_short_form("(abc"))
self.assertTrue(is_valid_short_form("abc"))
self.assertFalse(is_valid_short_form("123"))
self.assertFalse(is_valid_short_form("(123"))
def test_has_letter(self):
self.assertTrue(has_letter("abc"))
self.assertTrue(has_letter("123a"))
self.assertFalse(has_letter("123"))
def test_has_capital(self):
self.assertTrue(has_capital("Abc"))
self.assertTrue(has_capital("ABC"))
self.assertFalse(has_capital("abc"))
self.assertFalse(has_capital("123"))
def test_extract_pairs(self):
sentence = """
Three aspects of the involvement of tumor necrosis factor
in human immunodeficiency virus (HIV) pathogenesis were examined.
"""
pairs = extract_pairs(sentence)
self.assertListEqual(pairs, [{"acronym": "HIV", "definition": "human immunodeficiency virus"}])
def test_best_long_form(self):
self.assertTrue(True)
def test_match_pair(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
|
1095f7cbdfec448baa8bb17eaa5860f065c16164 | ndthanhdev/a2 | /mine/tools.py | 341 | 3.578125 | 4 | import vnTokenizer
def tokenize(sent):
'''Return the tokens of a sentence including punctuation.
>>> tokenize('Bob dropped the apple. Where is the apple?')
['bob', 'dropped', 'the', 'apple', '.', 'where', 'is', 'the', 'apple', '?']
'''
return [x.strip().lower() for x in vnTokenizer.tokenize(sent).split() if x.strip()] |
934e858f10444b163ffd0e34d98adf536aa0e259 | JinYeJin/algorithm-study | /Programmers/predict_match.py | 2,817 | 3.859375 | 4 | def solution(n,a,b):
answer = 0
while (a!=b):
if a % 2 != 0:
a += 1
if b % 2 != 0:
b += 1
a /= 2
b /= 2
answer += 1
return answer
n, a, b = 8, 4, 7
print(solution(n,a,b))
'''
def log_binary_search(target, two_powers):
begin = 0
end = len(two_powers)-1
print(f"{target=}")
while (begin <= end):
print(f"{begin=}")
print(f"{end=}")
mid = (begin+end)//2
if two_powers[mid] == target:
return mid
elif two_powers[mid] < target:
begin = mid+1
else:
end = mid-1
return mid+1
def solution(n,a,b):
if n == 0:
return 1
two_powers =[ 2 ** power for power in range(1, n+1) ]
print("two_powers : ", two_powers)
print("a : ", a)
print("b : ", b)
first_log = log_binary_search(a, two_powers)
second_log = log_binary_search(b, two_powers)
print(f"{first_log=}")
print(f"{second_log=}")
if first_log != second_log:
return max(first_log, second_log)
else:
# diff = abs(a-b)
# diff_log = int(math.log(diff, 2))
# if diff not in two_powers:
# diff_log += 1
# return diff_log
a -= 2 ** (first_log-1)
b -= 2 ** (first_log-1)
return solution(first_log-1,a,b)
# 6 7 (2 3)
# 257 380
# 1 124
# 1 7
# 510 511 (254 255 ) 126 127 (62 63) 30 31 (14 15) 6 7 (2 3)
# 512 - 256
# 2 ** 8
# 258 259
'''
'''
1. log_2_x 했을때 어떤 범위에 들어가는지 확인
-1 binary search로 탐색
512, 513
최대 범위 2 ** N
2. 둘(x,y)이 같은 범위(range)에 있으면
-1 둘의 차이가 2의 제곱이 아니라면.
return log_2_|x - y| + 1
-2 2의 제곱이라면
return log_2_|x - y|
3. 둘(x,y)이 다른 범위(range)에 있으면
return max(x_range, y_range)
15 (4), 27 (5)
log를 쓰는거 자체가 속도를 많이 느리게 만든다.
다른 방법으로 log_2를 취했을때의 범위를 알아야한다.
방법은
twO_powers 리스트에서 어떤 범위에 속하는지 알아내는것이다.
two_powers : [2, 4, 8, 16, 32, 64, 128, 256, 512]
first_log, second_log : 9 9
a, b : 255 254
two_powers : [2, 4, 8, 16, 32, 64, 128, 256]
first_log, second_log : 8 8
a, b : 127 126
two_powers : [2, 4, 8, 16, 32, 64, 128]
first_log, second_log : 7 7
a, b : 63 62
two_powers : [2, 4, 8, 16, 32, 64]
first_log, second_log : 6 6
a, b : 31 30
two_powers : [2, 4, 8, 16, 32]
first_log, second_log : 5 5
a, b : 15 14
two_powers : [2, 4, 8, 16]
first_log, second_log : 4 4
a, b : 7 6
two_powers : [2, 4, 8]
first_log, second_log : 3 3
a, b : 3 2
two_powers : [2, 4]
first_log, second_log : 2 1
2
---
log로 풀 필요도 없다.
시간초과가 발생한다.
짝수로 만들고 둘이 다른동안 나누기만한다
나눌때마다 카운팅하면
최종적으로 몇번의 단계가 지나야하는지 알 수 있다.
''' |
4b9214c5291c8694008e81e4af1f058f6acfd0b7 | ada-borowa/AoC2017 | /day18.py | 1,965 | 3.578125 | 4 | """
http://adventofcode.com/2017/day/18
"""
from typing import List
INPUT = open('input_18.txt', 'r').read()[:-1]
TEST_INPUT = """set a 1
add a 2
mul a a
mod a 5
snd a
set a 0
rcv a
jgz a -1
set a 1
jgz a -2"""
def operations_list(stream: str) -> List[List[str]]:
return [x.split() for x in stream.split('\n')]
def duet(operations: str) -> int:
operations = operations_list(operations)
register = {}
curr_position = 0
last_played = None
while 0 <= curr_position < len(operations):
# print(operations[curr_position])
if len(operations[curr_position]) == 3:
operation, letter, argument = operations[curr_position]
if argument.isalpha():
try:
argument = register[argument][-1]
except ValueError:
argument = 0
else:
argument = int(argument)
else:
operation, letter = operations[curr_position]
if letter.isalpha() and letter not in register:
register[letter] = [0]
if operation == 'set':
register[letter].append(argument)
elif operation == 'add':
register[letter].append(register[letter][-1] + argument)
elif operation == 'mul':
register[letter].append(register[letter][-1] * argument)
elif operation == 'mod':
register[letter].append(register[letter][-1] % argument)
elif operation == 'rcv' and register[letter][-1] > 0:
return last_played
elif operation == 'snd':
last_played = register[letter][-1]
elif operation == 'jgz':
if letter.isalpha():
letter = register[letter][-1]
if letter > 0:
curr_position += argument
continue
curr_position += 1
return -1
assert duet(TEST_INPUT) == 4
if __name__ == '__main__':
print(duet(INPUT))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.