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 |
|---|---|---|---|---|---|---|
bd862f5281e03dd6ae25aba9ff37846e1d8b1c90 | grapess/python_eleven_2019 | /35.py | 276 | 3.6875 | 4 | from math import *
num = float( input(" Enter Any Number : "))
result = ceil( num )
print(" Result : " , result )
result = floor( num )
print(" Result : " , result )
result = log10( num )
print(" Result : " , result )
result = log2( num )
print(" Result : " , result ) |
0deb2f9aa929810edb86a01bce516e39bedf5a24 | warleyken42/estrutura-de-dados | /Primeira_Lista/Questao8.py | 188 | 3.8125 | 4 | Valor_Hora = float(input("Quanto voce ganha por hora: "))
Horas_Trabalhada = float(input("Numero de horas trabalhadas no mes: "))
print("Você ganha = R$",(Valor_Hora * Horas_Trabalhada)) |
03b414198e924dd1369869018fad555cef95bc4c | jose-brenis-lanegra/Brenis.Lanegra.T06 | /doble.nro05.py | 544 | 3.828125 | 4 | import os
ciudad,clima="",""
#input
ciudad=(os.sys.argv[1])
clima=(os.sys.argv[2])
#outpout
print("##########################")
print("#el clima de una ciudad")
print("##########################")
print("#")
print("##########################")
print("#ciudad :", ciudad)
print("#clima :", clima)
print("##########################")
#condicional doble
#si la ciudad es ferreñafe su clima es caluroso, de lo contrario es falso
if (ciudad=="ferreñafe"):
a=clima=="caluroso"
print(a)
else:
print("no es ferreñafe")
|
2c556ce86b249edd39b830f1ed647f87bbf405fd | ACLoong/LeetCode | /src/118-Pascal-Triangle/118._Pascal_Triangle.py | 532 | 3.796875 | 4 | class Solution:
def generate(self, numRows):
"""
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Args:
numRows(int): the given non-negative integer
Returns:
the first numRows of Pascal's triangle(List[List[int]])
"""
result = [[1]*(i+1) for i in range(numRows)]
for i in range(numRows):
for j in range(1,i):
result[i][j] = result[i-1][j-1] + result[i-1][j]
return result
|
7c76336b1ef009854fa3616fb1e00513b488bdf5 | rlhernandezch/code | /python/basics/typeconv.py | 187 | 3.609375 | 4 | #!/user/bin/python
import random
import math
x=3
#int(x)
#long(x)
#float(x)
#complex(x)
#complex(x,y)
print(random.random())
list=[1,2,3,4,5,6,7,8,9]
random.shuffle(list)
print (list) |
075ac604b6dbcc38e52a1b0061fb4edc06e74842 | Pyk017/Python | /OOPs/Question02.py | 1,282 | 4.21875 | 4 | # 2. Write a class to implement the following:
# Create a class Employee
#
# The Employee class contain properties to store the following
# o ID
# o Name
# o Designation o Department
# o Basic Salary
# o HRA (House Rent Allowance)
# o VA (Vehicle Allowance)
# o NetSalary
# The Employee class contain methods to perform the following job
# o Store the value of all the properties individually
# o Get the value of all the properties individually
# o Calculate HRA and VA after assigning the value of Basic Salary o Calculate Net Salary after allowances calculations
# o Display all the properties of an employee.
class Employee:
def __init__(self,id,name,designation,basicSal,hra,va):
self.id = id
self.name = name
self.designation = designation
self.basicSal = basicSal
self.hra = hra
self.va = va
# self.netSal = netSal
def calculate(self):
return (self.basicSal + self.hra + self.va)
name = input("Enter Name = ")
id = int(input("Enter ID = "))
desig = input("Designation = ")
basicSal = int(input("Basic Salary = "))
hra = int(input("HRA :- "))
va = int(input("VA :- "))
emp = Employee(id,name,desig,basicSal,hra,va)
print ("Net Salary is :- {}".format(emp.calculate()))
|
c5cabe62f2aceab70d10fbcee668cf4a2adc431e | me6edi/Python_Practice | /B.Code Hunter/30. Python Bangla Tutorial -- For Loop - 02 -- Code Hunter/30. Python Bangla Tutorial -- For Loop - 02 -- Code Hunter.py | 221 | 3.671875 | 4 | #for loop
p = [1,2,3,4,5] # 1++2+3+4+5 = 15
s = 0
for i in p:
s = s + i
print("Sum of elements: ",s)
q = ["apple","banana","orange","pine allple"]
c = ''
for i in q:
c = c + i
print("concanate of fruits: ",c)
|
a556e74f8bc7e2ef2960f9bcd277110e28c06b1d | p-render/fizzbuzz | /fizzbuzz_simple.py | 386 | 3.65625 | 4 |
def fizz_buzz(i):
mapping = {
3: 'Fizz',
5: 'Buzz',
}
result = ""
for key in sorted(mapping.keys()):
value = mapping[key]
if not i % key:
result += value
if not result:
result = str(i)
return result
if __name__ == '__main__':
for i in range(1, 101):
print fizz_buzz(i)
|
32834792239e73ee76c3cc5f5508f93836c03cfd | claudiordgz/udacity--data-structures-and-algorithms | /notes/trees/depth3.py | 354 | 3.953125 | 4 | def print_tree_postorder(tree):
"""
Implement a post-order traversal here
Args:
tree(object): A binary tree input
Returns:
None
"""
if tree == None: return
print_tree_postorder(tree.left)
print_tree_postorder(tree.right)
print(tree, end=' ')
print("Post-order:", end=' ')
print_tree_postorder(my_tree)
|
29a6ba34939a3a25c7338220464d4fad8035e106 | sharondsza26/python-Technology | /proceduralParadigm.py | 1,096 | 4.03125 | 4 | # Stage 1
print("Namaste")
print("Namaste")
print("Namaste")
# Stage 2 -while
i = 0
while i < 5 :
print("Namaste")
i = i + 1
# Stage 3 -function
def greeting() :
i = 0
while i < 5 :
print("Namaste")
i = i + 1
print("Welcome")
greeting()
print("Bye")
# Stage 4 -parameters
print("Welcome")
def greeting(v) :
i = 0
while i < v :
print("Namaste")
i = i + 1
greeting(3)
print("Once Again")
greeting(5)
# Stage 5 -2 param
print("Welcome")
def greeting(message, times) :
i = 0
while i < times :
print(message)
i = i + 1
greeting("Namaste",3)
print("Once Again")
greeting("Hello World",5)
#
print("Welcome")
def greeting(message,times) :
i = 0
while i < times :
print(message)
i = i + 1
# greeting("Namaste",3)
# print("Once Again")
# greeting("Hello World",5)
# greeting("oh","ok",4)
# greeting(7,"ok")
# greeting(times)
# Stage 6 - return val of a function
print("Welcome")
def f1(a,b) :
r1 = 2 * a
r2 = 2 + b
r = r1 + r2
return r
i = f1(1,2)
j = f1(3,4)
k = f1(5,6)
|
17a4fbdc7532bb19c653af78f9e4ded20eaa05ab | AntonioReyesE/ProyectoMetodosFinal | /MétodosFinal/dist/sourcecode/newton.py | 4,076 | 4.03125 | 4 | # -*- encoding: utf-8 -*-
import math
#Clase que implementa los métodos necesarios para solucionar por el método de Newton
class newton:
k = 0 #El orden
lista = [] #La lista que guarda los valores iniciales y los generados a partir de ellos
intervalo = 0 #La diferencia general entre los valores de x
xAnterior = 0 #La x0 de la formula de Newton
#Contructor de la clase que inicializa la matriz
def __init__(self, matriz):
#Matriz que recibe a partir de archivo leido
self.matriz = matriz
self.intervalo()
#self.DiferenciasFinitas()
#Primera forma de calcular las diferencias finitas de la función tabular
#Regresa el orden de la función
def DiferenciasFinitas(self):
lista = []
y = self.matriz[1] #Obtenr el valor de la tabulación en y
lista.append(self.matriz[0])
lista.append(y)
igual = self.iguales(y) #Para la primera comparación
if igual != False:
print "false"
return False
else:
#Hasta que todos los valores del arreglo sean iguales
k = 0
while igual != True:
k = k + 1
i = 0
j = 1
resultado = []
#resta de los valores de y
while j < len(y):
resta = float(y[j]) - float(y[i])
i = i + 1
j = j + 1
resultado.append(resta)
igual = self.iguales(resultado)
y = resultado
lista.append(resultado)
self.k = k
self.lista = lista
print "true"
return True
#Función que identifica si todos los elementos de un arreglo son iguales
def iguales(self,resultado):
f = resultado[0]
for x in xrange(0,len(resultado)):
if resultado[x] != f:
return False
return True
#La primera función a llamar para hacer la validación principal
#Función que detecta si h es constante, y si lo es regresa la distancia, sino regresa -1
def intervalo(self):
i = 0
j = 1
resta = abs(abs(float(self.matriz[0][j])) - abs(float(self.matriz[0][i])))
while j < len(self.matriz[0]):
resta2 = abs(abs(float(self.matriz[0][j])) - abs(float(self.matriz[0][i])))
i = i + 1
j = j + 1
if(resta != resta2):
self.intervalo = -1
return -1
self.intervalo = resta
return resta
#Función que calcula la k y pone xAnterior
def fraccionIntervalo(self,x0):
valor = float(self.matriz[0][0])
if valor == x0:
valor = x0
elif x0 % self.intervalo == 0:
valor = x0
elif x0 > valor:
while valor < x0:
valor = valor + self.intervalo
valor = valor - self.intervalo
elif x0 < valor:
while x0 < valor:
valor = valor - self.intervalo
valor = valor + self.intervalo
fraccIn = (x0 - valor) / self.intervalo
self.xAnterior = valor
return fraccIn
#Función que resuleve la interpolacion ya generada de newton
def formula(self, xUsuario, orden):
k = self.fraccionIntervalo(xUsuario)
if(orden<self.k):
self.k = orden
self.extrapolacion(self.xAnterior) #aqui ta extrapolacion
indice = self.lista[0].index(self.xAnterior)
res = 1
y0 = self.lista[1][indice]
for i in range (self.k,0,-1):
for j in range(0, i):
res = res * (k - j)
res = (res * self.lista[j+2][indice]) / math.factorial(j+1)
y0 = y0 + res
res = 1
print ""
print " El orden del Polinomio que más se ajusta " + str(self.k)
print " El metodo para extrapolar/interpolar usado fue Newton"
print " El resultado de la aproximación es " + str(y0)
#Función que extrapola según un valor dado válido de acuerdo al intervalo
def extrapolacion(self, xDeseado):
xDeseado = (3 * self.intervalo) + xDeseado
if xDeseado < self.lista[0][0]:
while not xDeseado in self.lista[0]:
self.lista[-1].insert(0,self.lista[-1][0])
for i in range(self.k, 0, -1):
self.lista[i].insert(0, self.lista[i][0] - self.lista[i + 1][0])
self.lista[0].insert(0, self.lista[0][0] - self.intervalo)
else:
while not xDeseado in self.lista[0]:
self.lista[-1].append(self.lista[-1][-1])
for i in range(self.k, 0, -1):
self.lista[i].append(self.lista[i][-1] + self.lista[i + 1][-1])
self.lista[0].append(self.lista[0][-1] + self.intervalo)
print self.lista
def kill(self):
del self
|
a7f2d27d425038f8e634c67369f4c6cd9e3e8a9d | Rlyslata/DataStauct-And-Algorithm | /数组排序算法/BubbleSort/__init__.py | 1,217 | 3.9375 | 4 | """
冒泡排序:
算法思想:
未排序的序列,必然存在两个不符合排序规则的相邻元素。
array 长度 为 n
一轮排序过程:
对array[i],将之array[i+1]比较,并交换他们的值,然后i++,直到i = n-1-i(n-i~n-1是已经排好序的,再参与比较无意义)
一轮排序结果:
经过一轮排序后,会将0~n-i-1中的最大值放到后面n-i-1的位置
(从大到小排序以从n-1~0的顺序执行,每轮排序会将未参与排序的序列中的最小值放到前面)
"""
def bubbleSort(array):
values = list(array)
for i in range(0, len(values)):
for j in range(0, len(values) - i - 1):
if values[j] > values[j + 1]:
# 此处j == j+1 恒为假,可以放心使用异或 或 加减排序
values[j] = values[j] ^ values[j + 1]
values[j + 1] = values[j] ^ values[j + 1]
values[j] = values[j] ^ values[j + 1]
return type(array)(values)
if __name__ == "__main__":
seq = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]
print(set(seq))
print(bubbleSort(tuple(seq)))
print(bubbleSort(seq))
|
ea10cf4b05d17d57f2b2111161302e5f68199151 | seattlegirl/jianzhioffer | /fibonacci.py | 403 | 3.84375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
result=[0]*(n+1)
if n==0:
return 0
if n==1:
return 1
result[0]=0
result[1]=1
for i in range(2,n+1):
result[i]=result[i-1]+result[i-2]
return result[n]
if __name__ == "__main__":
print(Solution().Fibonacci(0))
|
ebd02939cd2caaa1f6c3f9dc6bb179d6f3dc9a83 | bartoszp1992/kicad-coil-generator | /spiral.py | 4,832 | 3.953125 | 4 | import math
import collections
from math import pi
import KicadModTree as kmt
def polar2cartesian(r, theta):
x, y = r * math.cos(theta), r * math.sin(theta)
return (x, y)
def cartesian2polar(x, y):
r, theta = math.sqrt(x**2 + y**2), math.atan2(y, x)
return (r, theta)
def arc_through_3_points(A, B, C):
"""
Calculate arc through 3 subsequent points (B is between A and B!).
Algorithm:
- find slopes of segments AB and BC
- find slopes of lines perpendicular to AB and BC (slope_perp = -1 / slope)
- find mid points of segments AB and BC
- find 'b' of line equations (y = a*x + b) through those mid points
- solve for the intersection point
Returns:
(D, angle_rad)
D -- center point of the arc (x, y)
angle_rad -- angle of the arc in radians
"""
# data type for easier access
Point = collections.namedtuple('Point', ['x', 'y'])
A = Point(*A)
B = Point(*B)
C = Point(*C)
# slopes of the segments perpendicular to AB and BC
slope_AB = (A.y - B.y) / (A.x - B.x)
slope_BC = (B.y - C.y) / (B.x - C.x)
slope_perp_AB = -1 / slope_AB
slope_perp_BC = -1 / slope_BC
# mid points
mid_AB = Point(x=(A.x + B.x) / 2, y=(A.y + B.y) / 2)
mid_BC = Point(x=(B.x + C.x) / 2, y=(B.y + C.y) / 2)
# calculate line equation b parameters (b = y - a*x)
b_AB = mid_AB.y - slope_perp_AB * mid_AB.x
b_BC = mid_BC.y - slope_perp_BC * mid_BC.x
# solve for intersection (x, y) given the two equations y = a*x + b
x = (b_AB - b_BC) / (slope_perp_BC - slope_perp_AB)
y = slope_perp_AB * x + b_AB
# let's call the center point D
D = Point(x, y)
# now find the angle of the arc,
# this is the difference of angles of segments AD and CD
angle_AD = math.atan2(A.y - D.y, A.x - D.x)
angle_CD = math.atan2(C.y - D.y, C.x - D.x)
angle_rad = angle_CD - angle_AD
return tuple(D), angle_rad
def coil_arcs(params, points_per_turn=4, direction=+1):
"""
Approximates Archimedean spiral by a sequence of arcs.
For each spiral revolution 'points_per_turn' are taken and an arc
for each pair is drawn.
The coordinates of start and end points of the line are returned as (x, y).
Archimedean spiral is defined in polar coordinates by equation:
r = a + b*theta
where 'a' is the inner radius.
We can calculate the outer radius as:
R = a + b*total_theta
And solve for b:
b = (R - a) / total_theta
We first define the spiral as if it had 0 line width,
only when generating footprint we draw with the actual width.
"""
total_angle = 360 * params.n_turns
b = (params.r_outer - params.r_inner) / math.radians(total_angle) * direction
# calculate all the angles at which we evaluate points
angle_increment = 360.0 / points_per_turn
n_increments = int(total_angle / angle_increment)
angles = [angle_increment * i for i in range(n_increments)]
if angles[-1] < total_angle:
angles += [total_angle]
def cartesian_coords_for_angle(angle_deg):
theta = math.radians(angle_deg)
r = params.r_inner + b * theta
x, y = polar2cartesian(r, theta)
return x, y
arcs = []
for i in range(len(angles) - 1):
start_angle = angles[i]
end_angle = angles[i + 1]
mid_angle = (start_angle + end_angle) / 2
start = cartesian_coords_for_angle(start_angle)
mid = cartesian_coords_for_angle(mid_angle)
end = cartesian_coords_for_angle(end_angle)
# calculate the center and angle of the arc
center, angle_rad = arc_through_3_points(start, mid, end)
if direction > 0:
if angle_rad < 0:
angle_rad += 2 * pi
else:
if angle_rad > 0:
angle_rad -= 2 * pi
# just draw everything on front copper layer
layer = 'F.Cu'
arcs.append(kmt.Arc(center=center, start=start, angle=math.degrees(angle_rad),
layer=layer, width=params.line_width))
start_point = cartesian_coords_for_angle(angles[0])
end_point = cartesian_coords_for_angle(angles[-1])
return arcs, start_point, end_point
def line_spacing(params):
"""
Calculates the space left between subsequent lines of the spiral
for the given 'line_width'.
This is effectively the space between copper paths, so it should
be high enough to avoid electrical interference.
Negative spacing is...too small.
"""
total_angle = 360 * params.n_turns
b = (params.r_outer - params.r_inner) / math.radians(total_angle)
r0 = params.r_inner + b * 0
r1 = params.r_inner + b * 2 * pi
delta_r = abs(r1 - r0)
spacing = delta_r - params.line_width
return spacing
|
0f1f498427dff673390ffbd80652075499029751 | AoifeFlanagan/Blackjack | /Blackjack.py | 8,645 | 4.125 | 4 | """Program for a game of Blackjack."""
import random
from IPython.display import clear_output
class Card:
"""A class to represent each card in the deck, using two attributes, suit and rank."""
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit
class Deck:
"""A class to build out each card and store all 52 card objects which can later be shuffled."""
def __init__(self):
self.deck_list = []
for suit in suits:
for rank in ranks:
any_card = Card(suit, rank)
self.deck_list.append(any_card)
def shuffle(self):
"""A method to randomise the cards in the deck."""
random.shuffle(self.deck_list)
def deal(self):
"""A method to remove a single card from the deck list."""
return self.deck_list.pop()
def __str__(self):
print(len(self.deck_list))
new = []
for item in self.deck_list:
new.append(str(item))
return "\n".join(new)
class Hand:
"""A class to represent each player's hand and adjust the Ace value as neccessary."""
def __init__(self):
self.card_list = []
self.sum = 0
self.aces = 0
def add_card(self, card):
"""A method that adds the dealt card to the hand and adds its value to the hand total."""
self.card_list.append(card)
self.sum += card.value
def adjust_for_ace(self):
"""A method that adjusts the ace value to 1 if the hand total remains less than 21."""
self.sum = 0
for card in self.card_list:
self.sum += card.value
if self.card_list[-1].rank == "Ace":
self.aces += 1
if self.sum > 21:
self.sum -= self.aces*10
def __str__(self):
new_list = []
for card in self.card_list:
new_list.append(str(card))
return "\n".join(new_list)
def __getitem__(self, index):
return str(self.card_list[index])
class Chips:
"""A class to keep track of a player's starting chips, bets and ongoing winnings."""
def __init__(self, total = 100):
self.total = total
def win_bet(self, bet):
"""A method adding the bet amount to the player's chips in a win-game scenario."""
self.total += bet
def lose_bet(self, bet):
"""A method subtracting the bet amount from the player's chips in a lose-game scenario."""
self.total -= bet
def __str__(self):
if self.total > 1:
return f"{self.total} chips"
else:
return f"{self.total} chip"
def welcome():
"""Function that prints out a welcome message to the game."""
print("Welcome to Blackjack!\n")
def take_bet():
"""Function that asks the player how much they would like to bet."""
global bet
while True:
try:
bet = int(input("How much would you like to bet? "))
except:
clear_output()
print(f"Invalid bet! Please try again.\n\nYou have {player_chips}.")
else:
break
def hit(deck, hand):
"""Function that adds a new card to the dealers hand and adjusts the value of Aces."""
new_card = deck.deal()
hand.add_card(new_card)
hand.adjust_for_ace()
def hit_or_stand(deck, hand):
"""Function that asks the player if they would like to hit or stand."""
global playing
acceptable_values = ["YES", "NO"]
while True:
answer = input("Would you like to hit? (Yes or No) ").upper()
if answer not in acceptable_values:
clear_output()
print("Invalid input! Enter 'Yes' or 'No'.")
show_some(player, dealer)
elif answer == "YES":
clear_output()
return True
break
else:
clear_output()
playing = False
break
def show_some(player, dealer):
"""Function that reveals each of the players hands, keeping one dealer card hidden."""
print(f"\nDealer's first card:\n{dealer[0]}\n")
print(f"Card value: {dealer.card_list[0].value}\n")
print(f"You have: \n{player}")
print(f"\nYour hand total is: {player.sum}")
def show_all(player, dealer):
"""Function that reveals each of the player's hands."""
print(f"\nHere are the dealer's cards: \n{dealer}\n")
print(f"Dealer hand total: {dealer.sum}\n")
print(f"Here is what you had: \n{player}\n")
print(f"Player hand total: {player.sum}\n")
def replay():
"""Function that asks the player if they would like to continue playing."""
ask = True
acceptable_values = ["yes", "no"]
while ask:
choice = input("Would you like to continue? (Yes or No) ").lower()
if choice not in acceptable_values:
clear_output()
print("Type 'Yes' or 'No'.")
else:
break
if choice == "yes":
clear_output()
return True
else:
clear_output()
print("\nThank you for playing!")
return False
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King')
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
game_on = True
dealer_turn = True
player_chips = Chips()
welcome()
while game_on:
new_deck = Deck()
new_deck.shuffle()
dealer = Hand()
hit(new_deck, dealer)
hit(new_deck, dealer)
player = Hand()
hit(new_deck, player)
hit(new_deck, player)
while True:
print(f"You have {player_chips}.")
take_bet()
if 0 < bet <= player_chips.total:
clear_output()
print(f"You bet: {bet}\nRemaining chips: {player_chips.total-bet}")
break
else:
clear_output()
print(f"You can only bet between 0 and {player_chips.total}.\n")
show_some(player, dealer)
while playing:
if player.sum == 21:
clear_output()
print(f"\nCongratulations! You scored 21 and won the game!\n")
print(f"Chips won: {bet}\n")
player_chips.win_bet(bet)
playing = False
dealer_turn = False
elif player.sum > 21:
clear_output()
print(f"\nPlayer went bust, the dealer wins!\n")
print(f"Chips lost: {bet}\n")
player_chips.lose_bet(bet)
playing = False
dealer_turn = False
elif hit_or_stand(new_deck, player):
hit(new_deck, player)
clear_output()
show_some(player, dealer)
if dealer_turn == True:
print("The dealer played his turn...")
while dealer.sum < 17:
hit(new_deck, dealer)
if dealer.sum > 21:
player_chips.win_bet(bet)
print("\nThe dealer went bust, player wins the game!\n")
print(f"Chips won: {bet}\n")
elif dealer.sum == 21:
player_chips.lose_bet(bet)
print("\nThe dealer scored 21 and won!\n")
print(f"Chips lost: {bet}\n")
elif dealer.sum > player.sum and dealer.sum < 21:
player_chips.lose_bet(bet)
print("\nThe dealer won!\n")
print(f"Chips lost: {bet}\n")
elif dealer.sum < player.sum and dealer.sum < 21:
player_chips.win_bet(bet)
print("\nThe dealer lost!\n")
print(f"Chips won: {bet}\n")
elif dealer.sum == player.sum:
print("\nTie game! The amount you bet has been returned to your chips total.\n")
elif dealer.sum > 21 and player.sum > 21:
print("\nTie game! The amount you bet has been returned to your chips total.\n")
show_all(player, dealer)
if player_chips.total > 0:
print(f"\nYou have {player_chips} remaining.")
else:
print("\nYou have no more chips remaining!")
player_chips = Chips()
if replay():
dealer_turn = True
playing = True
continue
else:
game_on = False
|
f4e9a1b5e1a04f64957f33166c93d2b0ead7aa3b | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/288_Unique_Word_Abbreviation.py | 956 | 3.703125 | 4 | c_ ValidWordAbbr o..
___ - dictionary
"""
initialize your data structure here.
:type dictionary: List[str]
"""
dictionary = s..(dictionary)
abb_dic # dict
___ s __ dictionary:
curr = getAbb(s)
__ curr __ abb_dic:
abb_dic[curr] = F..
____
abb_dic[curr] = T..
___ isUnique word
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
abb = getAbb(word)
hasAbbr = abb_dic.get(abb, N..)
r_ hasAbbr __ N.. or (hasAbbr a.. word __ dictionary)
___ getAbb word
__ l.. word) <= 2:
r_ word
r_ word[0] + s..(l.. word) - 2) + word[-1]
# Your ValidWordAbbr object will be instantiated and called as such:
# vwa = ValidWordAbbr(dictionary)
# vwa.isUnique("word")
# vwa.isUnique("anotherWord") |
5d62c2a178b417bb1f0a9196e2b8072f1b0e436a | spacetime314/python3_ios | /extraPackages/matplotlib-3.0.2/examples/subplots_axes_and_figures/colorbar_placement.py | 1,766 | 3.78125 | 4 | """
=================
Placing Colorbars
=================
Colorbars indicate the quantitative extent of image data. Placing in
a figure is non-trivial because room needs to be made for them.
The simplest case is just attaching a colorbar to each axes:
"""
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(2, 2)
cm = ['RdBu_r', 'viridis']
for col in range(2):
for row in range(2):
ax = axs[row, col]
pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
cmap=cm[col])
fig.colorbar(pcm, ax=ax)
plt.show()
######################################################################
# The first column has the same type of data in both rows, so it may
# be desirable to combine the colorbar which we do by calling
# `.Figure.colorbar` with a list of axes instead of a single axes.
fig, axs = plt.subplots(2, 2)
cm = ['RdBu_r', 'viridis']
for col in range(2):
for row in range(2):
ax = axs[row, col]
pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
cmap=cm[col])
fig.colorbar(pcm, ax=axs[:, col], shrink=0.6)
plt.show()
######################################################################
# Relatively complicated colorbar layouts are possible using this
# paradigm. Note that this example works far better with
# ``constrained_layout=True``
fig, axs = plt.subplots(3, 3, constrained_layout=True)
for ax in axs.flat:
pcm = ax.pcolormesh(np.random.random((20, 20)))
fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom')
fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom')
fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6)
fig.colorbar(pcm, ax=[axs[2, 1]], location='left')
plt.show()
|
40301a240890eb8d414712c3e4da59d1cf891686 | Legend0300/Codingandbeyond | /Ahmed's stuff/hello.py | 315 | 3.515625 | 4 | prive_of_house = 1000000
down_payment = (prive_of_house - 200000)
goof_credit = ()
bad_credit = ()
if goof_credit == True:
print("your payment is; ", (prive_of_house - 100000))
elif bad_credit == True:
print("Yuor down payment will be:", down_payment)
else:
print("you dont ahve enough credit") |
62cba7b2453bd574aaf7d3097d7f75ae110eaf94 | yousstone/python3_learning_note | /reduce_prod.py | 161 | 3.53125 | 4 | #!/usr/bin/python3
from functools import reduce
def prod(L):
return reduce(lambda x,y : x*y,L)
print(prod([1,2,3,4]))
print(prod([x for x in range(1,11)]))
|
f94352f5ff55bd248bac7f0d9cf844085fc85e28 | BDunk/ME303_Project_01 | /Project_01/bonus.py | 3,926 | 3.859375 | 4 | import random
import numpy as np
# number of agents
n = 20
agents = []
for ii in range(n):
# create an agent, who starts with no cash, and as an active trader
agents.append({'money': 0})
if ii < n - 1:
# assign the first n-1 agents the fruit corresponding to their id
# this doesn't bias anything, since the values are random, and no agent is preferred
agents[ii]['fruit'] = ii
else:
# leftover agents are assigned a none fruit
agents[ii]['fruit'] = None
# agents are assigned a random value between 1 and 0 for each fruit
# the assumption is made that the distribution of fruit utilities is uniform
# and that that values of the good have no relationship to eachother
# i.e. a person who things a banana is worth $10 might also overvalue other fruit in the real world
agents[ii]['values'] = []
for jj in range(n - 1):
agents[ii]['values'].append(random.random())
unsteady = True
Alice = n-1
trades_count = 0
starting_value = 0
for agent in agents:
if agent['fruit'] is not None:
starting_value += agent['values'][agent['fruit']]
while unsteady:
shuffled = list(range(len(agents)))
random.shuffle(shuffled)
# We are only going three people deep, and the example is this:
# Alice buys from Bob, who buys from carol
# Alice makes the first transaction she can find,
# allowing bob to check with Carol before deciding if its worth it
# I do not endorse the premise that economic activity generates real value
# Eat the rich.
unsteady = False
for Bob in shuffled:
if not Bob == Alice:
fruit = agents[Bob]['fruit']
alice_value = agents[Alice]['values'][fruit]
bob_value_1 = agents[Bob]['values'][fruit]
sale_price_1 = (alice_value + bob_value_1) / 2
if alice_value > bob_value_1:
print(f"{Alice} traded with {Bob}")
agents[Alice]['money'] -= sale_price_1
agents[Bob]['money'] += sale_price_1
agents[Alice]['fruit'] = agents[Bob]['fruit']
agents[Bob]['fruit'] = None
Alice = Bob
unsteady = True
trades_count +=1
break
elif alice_value < bob_value_1:
bob_loss = bob_value_1 - sale_price_1
for Carol in shuffled:
if (not Carol == Alice) and (not Carol == Bob):
fruit_2 = agents[Carol]['fruit']
bob_value_2 = agents[Bob]['values'][fruit_2]
carol_value = agents[Carol]['values'][fruit_2]
sale_price_2 = (bob_value_2 +carol_value)/2
bob_gain = bob_value_2 - sale_price_2
if bob_gain + bob_loss > 0:
print(f"{Alice} traded with {Bob} who traded with {Carol}")
agents[Alice]['money'] -= sale_price_1
agents[Bob]['money'] += sale_price_1
agents[Alice]['fruit'] = agents[Bob]['fruit']
agents[Bob]['fruit'] = None
agents[Bob]['money'] -= sale_price_2
agents[Carol]['money'] += sale_price_2
agents[Bob]['fruit'] = agents[Carol]['fruit']
agents[Carol]['fruit'] = None
Alice = Carol
unsteady = True
trades_count += 2
break
break
final_value = 0
for agent in agents:
if agent['fruit'] is not None:
final_value += agent['values'][agent['fruit']]
print(f"Trades: {trades_count}")
print(f"Starting value: {starting_value}")
print(f"Final value: {final_value}")
print('Done.')
|
017e709b0c9b722dfba154276b4bedcf146d7269 | ksu-is/Sport-Score-Tracker | /SportScoreTracker.py | 1,159 | 3.9375 | 4 | import sports
def main():
print('Introducing the Sport Tracker Application!\n')
print('I can provide you with scores from soccer, basketball, football, and baseball that occured today!\n')
print('What sport scores would you like to read? (enter a digit)\n')
print('1. Soccer\n2. Basketball\n3. Football\n4. Baseball')
sport = input('Please enter a digit from 1-4: ')
while True:
if sport.isdigit():
sport = int(sport)
if sport == "X":
print('Thank you for using the Sport Tracker Application.')
break
else:
get_scores(sport)
sport = str(input('Please enter a new digit or X to quit this application: '))
def get_scores(sport):
if sport == 1:
scores = sports.get_sport(sports.SOCCER)
elif sport == 2:
scores = sports.get_sport(sports.BASKETBALL)
elif sport == 3:
scores = sports.get_sport(sports.FOOTBALL)
elif sport == 4:
scores = sports.get_sport(sports.BASEBALL)
if sport < 5:
for score in scores:
print(score)
if __name__ == '__main__':
main()
|
e6ac8c8d7ec264f8906ca7391e45f1fc92e2be4c | Dessdi/python-simple-projects | /CountWordsInString.py | 110 | 3.5 | 4 | path = input("set file path")
with open(path) as file:
words = file.read().split()
print(len(words))
|
85688ae2dfeb727702d88055619aed97e9f915d0 | pawanpatil636/sorting-algorithms | /quicksort.py | 399 | 3.703125 | 4 | #-----------------------------quick sort---------------------------------
def quick(seq):
n=len(seq)
if n<=1:
return seq
else:
pivot=seq.pop()
greater=[]
lower=[]
for i in seq:
if pivot > i:
greater.append(i)
else:
lower.append(i)
return quick(greater)+[pivot]+quick(lower)
print(quick([5,6,7,8,3,4,2,90,23])) |
06d3f54eb6c422bdf878452866ce7c8a944bd9b6 | nick-fang/pynetwork | /pynetwork/python异步_同步非阻塞方式.py | 2,001 | 3.984375 | 4 | """深入理解python异步编程-非阻塞方式"""
import socket
import time
def nonblocking_way():
"""非阻塞的socket连接和传输"""
sock = socket.socket()
sock.setblocking(False) #将该sock对象的所有方法设置为非阻塞
try:
sock.connect(('example.com', 80))
except BlockingIOError: #无论阻塞(比如设置了超时)还是非阻塞模式,只要连接未完成就被强制返回,操作系统低层就会抛出该异常;所以非阻塞模式下几乎肯定辉抛出该异常
pass
request = 'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n'
data = request.encode('ascii')
while True: #不知道socket何时就绪/连接完毕,所以这里不断尝试发送请求报文
try:
sock.send(data) #如果未连接成功就发出数据,会触发OSError异常,于是进入下面的except子句
break #直到send不抛出异常,则发送完毕,跳出循环
except OSError:
pass
response = b''
while True:
try:
chunk = sock.recv(4096) #recv调用也不会再阻塞,如果不能立即接收到响应报文(可能时连接还未成功,也可能是服务器端发送的响应报文还在路上,还可能是该响应报文丢包了),则强制返回并触发OSError异常
while chunk:
response += chunk
chunk = sock.recv(4096) #接收完响应报文后,再次调用recv会发现连接的远程端关闭,于是返回一个空字节串赋值给chunk,从而退出内层while循环
break #这个break语句,用于跳出最外层的while循环,然后函数return
except OSError:
pass
return response
def sync_way():
res = []
for i in range(10):
res.append(nonblocking_way())
print(f'task {i}: completed.')
return len(res)
start = time.time()
print(sync_way())
end = time.time()
print('consumed {:.2f} secs'.format(end - start))
|
de187b3c586af46b6899e47371234a47b840f351 | LordBao666/MITLecture6.0002_introduction_to_computational_thinking_and_data_science | /practice/14random_walks_and_more_about_data_visualization/random_walk/random_walk.py | 5,527 | 3.53125 | 4 | """
@Author : Lord_Bao
@Date : 2021/3/21
"""
from entity import *
import pylab
def walk(drunk, field, num_steps):
"""
:param drunk: Drunk实例
:param field: Field实例,假设drunk 处在 field中
:param num_steps: 走的步数
:return: 返回初始点到走了num_steps的距离
"""
start_loc = field.get_location(drunk)
for n in range(num_steps):
field.move_drunk(drunk)
end_loc = field.get_location(drunk)
return start_loc.distance_from(end_loc)
def sim_walk(num_steps, num_trials, d_class):
"""
:param num_steps: 测试步数
:param num_trials: 测试次数
:param d_class: Drunk的种类 是一个构造函数
:return: 一个list,存储num_trials次的distance
"""
f = Field()
start = Location(0.0, 0.0)
d = d_class()
f.add_drunk(d, start)
distances = []
for n in range(num_trials):
dist = walk(d, f, num_steps)
distances.append(round(dist, 1)) # 精度为1
return distances
def drunk_test(walk_length, num_trials, d_class):
"""
:param walk_length: 测试步数 是个列表
:param num_trials: 测试次数
:param d_class: Drunk的种类 是一个构造函数
"""
for i in walk_length:
distances = sim_walk(i, num_trials, d_class)
print(d_class.__name__, "random walk of", i, "steps")
print("Mean = ", round(sum(distances) / len(distances), 4))
print("Max = ", max(distances), "Min = ", min(distances))
def drunk_test_with_graph(walk_length, num_trials, d_class_list):
"""
:param walk_length: 测试步数 是个列表
:param num_trials: 测试次数
:param d_class_list: Drunk的种类 若干构造函数
"""
# https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
styles = StyleIterator([".-b", ".-.g", ".:r"])
for d_class in d_class_list:
cur_style = styles.next_style()
mean_distance = []
for num_step in walk_length:
distances = sim_walk(num_step, num_trials, d_class)
mean_distance.append(round(sum(distances) / len(distances), 4))
pylab.plot(walk_length, mean_distance, cur_style, label=d_class.__name__)
pylab.title("Distance from origin(" + str(num_trials) + ")trials")
pylab.xlabel("Num of steps")
pylab.ylabel("Distance from origin")
pylab.legend(loc="best") # 将图例放在最好的位置。问题不是很大,可以不设置。可选的还有如
# =============== =============
# Location String Location Code
# =============== =============
# 'best' 0
# 'upper right' 1
# 'upper left' 2
# 'lower left' 3
# 'lower right' 4
# 'right' 5
# 'center left' 6
# 'center right' 7
# 'lower center' 8
# 'upper center' 9
# 'center' 10
pylab.semilogx() # Base 默认是10 。简单来说就是将你的 x 取对数展。比如x =1000 ,那么在图上展示的 log1000 = 3 。但是图上户表明是 10^3
pylab.semilogy()
pylab.show()
def get_final_locs(num_steps, num_trials, d_class):
"""
:param num_steps: 走几步
:param num_trials: 试验次数
:param d_class: Drunk的构造函数
:return: 记录num_trials 的最终location
"""
locs = []
for trial in range(num_trials):
drunk = d_class()
start = Location(0.0, 0.0)
field = Field()
field.add_drunk(drunk, start)
for step in range(num_steps):
field.move_drunk(drunk)
locs.append(field.get_location(drunk))
return locs
def plot_locs(drunk_kinds, num_steps, num_trials):
styles = StyleIterator(["ob", "xg", "^r"])
for drunk_kind in drunk_kinds:
final_locs = get_final_locs(num_steps, num_trials, drunk_kind)
x_locs = []
y_locs = []
for loc in final_locs:
x_locs.append(loc.get_x())
y_locs.append(loc.get_y())
mean_x = sum(x_locs) / len(x_locs)
mean_y = sum(y_locs) / len(y_locs)
label_str = drunk_kind.__name__ + "mean loc : <" + str(mean_x) + "," + str(mean_y) + ">"
pylab.plot(x_locs, y_locs, styles.next_style(), label=label_str)
pylab.title('Location at End of Walks (' + str(num_steps) + ' steps)')
pylab.xlabel('Steps East/West of Origin')
pylab.ylabel('Steps North/South of Origin')
pylab.legend(loc='lower left')
pylab.show()
def trace_walk(drunk_kinds, num_steps):
styles = StyleIterator(["ob", "xg", "^r", "+m"])
# field = Field()
field = OddField(1500,200,200)
for drunk_kind in drunk_kinds:
start = Location(0.0, 0.0)
drunk = drunk_kind()
field.add_drunk(drunk, start)
x_walk = [0.0]
y_walk = [0.0]
for step in range(num_steps):
field.move_drunk(drunk)
loc = field.get_location(drunk)
x_loc = loc.get_x()
y_loc = loc.get_y()
x_walk.append(x_loc)
y_walk.append(y_loc)
pylab.plot(x_walk, y_walk, styles.next_style(), label=drunk_kind.__name__)
pylab.title('Spots Visited on Walk ('
+ str(num_steps) + ' steps)')
pylab.xlabel('Steps East/West of Origin')
pylab.ylabel('Steps North/South of Origin')
pylab.legend(loc='best')
pylab.show()
|
ddd8abad67d7db2f910740717fd51876c346c677 | arpita-lataye14/NESTED_LIST | /calculator.py | 588 | 4.3125 | 4 | print('what operation do you want?')
operator=input('either +,-,*,/,//,%,**:')
n1=float(input('enter first number:'))
n2=float(input('enter second number:'))
if operator=='+':
print(n1,operator,n2,'=',n1+n2)
elif operator=='-':
print(n1,operator,n2,'=',n1-n2)
elif operator=='*':
print(n1,operator,n2,'=',n1*n2)
elif operator=="/":
print(n1,operator,n2,'=',n1/n2)
elif operator=='//':
print(n1,operator,n2,'=',n1//n2)
elif operator=='%':
print(n1,operator,n2,'=',n1%n2)
elif operator=='**':
print(n1,operator,n2,'=',n1**n2)
else:
print('invalid operation') |
00964e6a4d1c65ed83947626cc5622cfd007a316 | Rogersunfly/pythoncamp0 | /scr/guess the number.py | 1,190 | 3.671875 | 4 | import simplegui
import math
import random
secert_the_number = 100
guess_the_number = 0
def new_game():
if guess < secert_the_number:
print "lower!"
elif guess > secert_the_number:
print "higer!"
elif guess == secert_the_number:
print " correct,you are a gooooooood booy!"
else:
print " you are out of control, MYM!"
def range100():
global secert_the_number
secert_the_number = random.randint(0, 100)
number_of_choice = 100
input_guess()
def range1000():
global secert_the_number
secert_the_number = random.randint(0, 1000)
number_of_choice = 1000
input_guess()
def input_guess():
global guess
global guess_the_number
number = math.ceil(math.log(2, number_of_choice)
guess_the_number = guess_the_number + 1
if guess_the_number <= number:
print " Guess is " guess
new_game()
else:
print "you are lose!"
f = simplegui.create_frame("guess the number", 200, 200)
frame.add_button("range=[0, 100)", range100, 200)
frame.add_button("range=[0, 1000)", range1000, 200)
frame.add_input("guess the number", input_guess, 200)
new_game()
|
a841611dea467b93e1cd8715b67c3dccd6ffaa2f | yanggelinux/algorithm-data-structure | /algorithm/dijkstra_search.py | 914 | 3.625 | 4 | # -*- coding: utf8 -*-
nodes = {
"a":{"b":0.2,"c":0.3},
"b":{"d":0.2,"f":0.3},
"c":{"d":0.4,"e":0.1},
"d":{"e":0.3},
"e":{"f":0.2},
"f":{}
}
finish = {}
mw = {}
def get_min_val(dicts={}):
if dicts:
val_list = []
re_dicts = {}
for k,v in dicts.items():
val_list.append(v)
re_dicts[v] = k
min_val = min(val_list)
min_key = re_dicts[min_val]
return min_key
def dijkstra_search():
mw["a"] = 0
finish["a"] = 0
queue = []
queue.append(nodes["a"])
while queue:
node = queue.pop(0)
min_key = get_min_val(node)
if min_key is not None:
finish[min_key] = node[min_key]
print(finish)
for nd,val in node.items():
if finish.get(nd) is not None:
queue.append(nodes[nd])
if __name__ == '__main__':
dijkstra_search() |
83e56c8b59af06cd71596b6d962a5b62f2e83639 | Kolyan78/P101 | /Занятие3/Лабораторные_задания/task1_1/main.py | 597 | 3.828125 | 4 | # def main():
# a = 0
# while True:
# sum_ = pow(a + 1, 2) * 2
# #print(f"Сумма квадратов {a} равна {sum_}")
# if sum_ > 500:
# break
# else:
# a += 1
# return a
def main():
a = 0
list_ = []
while True:
if sum(list_) > 500:
return(len(list_[:-1]))
else:
list_.append(a ** 2)
print(f"Список: {list_}")
print(f"Сумма его квадратов: {sum(list_)}")
a += 1
if __name__ == "__main__":
print(main()) |
515e08198f12cba35372ac23af17aef2875fbaed | mws19901118/Leetcode | /Code/Transpose Matrix.py | 200 | 3.546875 | 4 | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))] #Transpose matrix.
|
b72085fa05aef68e768629b4378886940c2a0fab | rajasree-r/Bactracking-1 | /addOperators.py | 1,395 | 3.640625 | 4 | # Time complexity: O(4^N)
# Space complexity: O(4^N)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
class Solution:
def addOperators(self, num: str, target: int) :
result = []
self.backTrack(num, 0, 0, '', target, result)
return result
def backTrack(self, nxt, diff, sums, expression, target, result):
if not nxt:
if sums == target:
result.append(expression)
return
for i in range(1, len(nxt) + 1):
current = nxt[:i]
if len(current) > 1 and current[0] == '0':
return
nums = nxt[i:]
if not expression:
self.backTrack(nums, int(current), int(current), current, target, result)
else:
# addition
self.backTrack(nums, int(current), sums + int(current), expression + "+" + current, target, result)
# subtraction
self.backTrack(nums, -int(current), sums - int(current), expression + '-' + current, target, result)
# multiplication
self.backTrack(nums, diff * int(current), (sums - diff) + (diff * int(current)),
expression + "*" + current, target, result)
r = Solution()
num = "123"
target = 6
print("Output:", r.addOperators(num, target))
|
6049df909df7d54a7e58d825f17611a4f396a347 | PriscillaRoy/Parking-Lot-Vacancy-Detector | /testscr.py | 624 | 3.609375 | 4 | import os
class runFolder:
def runfolder(self,folderpath):
filenames = os.listdir(folderpath) # get all files' and folders' names in the current directory
xml = []
jpg = []
for filename in filenames: # loop through all the files and folders
#Listing the separate xml and jpg files
if(filename.find(".xml") != -1):
xml.append(filename)
elif(filename.find(".jpg") != -1):
jpg.append(filename)
# Sorting the files
xml.sort()
jpg.sort()
result = list(zip(xml,jpg))
return(result) |
2114d138ca658aa217c2f44b666797b1ffd338e4 | IDemiurge/LeetCodePython | /algs/removeDuplicates.py | 391 | 3.53125 | 4 | # https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution:
def removeDuplicates(self, nums) -> int:
for n, val in enumerate(nums):
for i, val2 in enumerate(nums[n + 1:]):
if val2 == val:
nums.pop(i + 1)
return nums
print(removeDuplicates(None, [1, 1, 2, 2, 3, 1, 1, 2, 2, 3, 5]))
|
2c1ea5cbcb911796b18dfa853fec0eac517c588e | antalcides/migit | /py/ej3_rkutta4o.py | 1,013 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Fecha de creación: Thu Oct 22 01:58:05 2015
Creado por: antalcides
"""
"""
A spacecraft is launched at the altitude H = 772 km above the sea level with the speed v 0 = 6700 m/s in the direction shown. The differential equations describing the motion of the spacecraft are
r" = r(0')^2 - (GM)/r^2, 0" = -(2r'0')/r
where r and θ are the polar coordinates of the spacecraft. The constants involved in the motion are
G = 6.672 × 10 −11 m^ 3 kg^−1s^−2 = universal gravitational constant
M = 5.9742 × 10 24 kg = mass of the earth
R = 6378.14 km = radius of the earth at sea level
"""
from numpy import*
from run_kut4 import *
from printSoln import *
def F(x,y):
F = zeros(4)
F[0] = y[1]
F[1] = y[0]*(y[3]**2) - 3.9860e14/(y[0]**2)
F[2] = y[3]
F[3] = -2.0*y[1]*y[3]/y[0]
return F
x = 0.0
xStop = 1200.0
y = array([7.15014e6, 0.0, 0.0, 0.937045e-3])
h = 50.0
freq = 2
X,Y = integrate(F,x,y,xStop,h)
printSoln(X,Y,freq)
plot(X,Y,'--or')
|
d7e320069ddc1871954fc98d2a603770f3cd3158 | jjcrab/code-every-day | /day72_subarraySumEqualsK.py | 870 | 3.8125 | 4 | # https://leetcode.com/problems/subarray-sum-equals-k/
'''
Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Example 2:
Input: nums = [1,2,3], k = 3
Output: 2
'''
# can't pass
# class Solution:
# def subarraySum(self, nums: List[int], k: int) -> int:
# count = 0
# for i in range(len(nums)):
# total = 0
# for j in range(i, len(nums)):
# total += nums[j]
# if total == k:
# count += 1
# return count
# better way to do it -> hashmap
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
dic = {0: 1}
cur, res = 0, 0
for v in nums:
cur += v
res += dic.get(cur - k, 0)
dic[cur] = dic.get(cur, 0) + 1
return res
|
b06170edc81d96b5b172cb6b345b20371c70aea8 | Ma-rk/python-cookbook-3rd | /04_IteratorsAndGenerators/08_SkippingTheFirstPartOfAnIterable.py | 508 | 3.640625 | 4 | from itertools import dropwhile
with open('sample.txt') as f:
for line in f:
print(line, end='')
print()
print()
print()
print('========using drop while========')
with open('sample.txt') as f:
for line in dropwhile(lambda line: line.startswith('pip'), f):
print(line, end='')
print()
print()
print()
print('========a good try========')
with open('sample.txt') as f:
lines = (line for line in f if not line.startswith('pip'))
for line in lines:
print(line, end='')
|
71a2fe42585b7a6a2fece70674628c1b529f3371 | pltuan/Python_examples | /list.py | 545 | 4.125 | 4 | db = [1,3,3.4,5.678,34,78.0009]
print("The List in Python")
print(db[0])
db[0] = db[0] + db[1]
print(db[0])
print("Add in the list")
db.append(111)
print(db)
print("Remove in the list")
db.remove(3)
print(db)
print("Sort in the list")
db.sort()
print(db)
db.reverse()
print(db)
print("Len in the list")
print(len(db))
print("For loop in the list")
for n_db in db:
print(n_db)
print(min(db))
print(max(db))
print(sum(db))
my_food = ['rice', 'fish', 'meat']
friend_food = my_food
friend_food.append('ice cream')
print(my_food)
print(friend_food)
|
f9cecdd5440c7a202d3ef2ad4ae8f2640c71fb44 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/83_6.py | 2,490 | 4.40625 | 4 | Python | Frequency of numbers in String
Sometimes, while working with Strings, we can have a problem in which we need
to check how many of numerics are present in strings. This is a common problem
and have application across many domains like day-day programming and data
science. Lets discuss certain ways in which this task can be performed.
**Method #1 : Usingre.findall() + len()**
The combination of above functions can be used to perform this task. In this,
we check for all numbers and put in list using findall() and the count is
extracted using len().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + len()
import re
# initializing string
test_str = "geeks4feeks is No. 1 4 geeks"
# printing original string
print("The original string is : " + test_str)
# Frequency of numbers in String
# Using re.findall() + len()
res = len(re.findall(r'\d+', test_str))
# printing result
print("Count of numerics in string : " + str(res))
---
__
__
**Output :**
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3
**Method #2 : Usingsum() + findall()**
The combination of above functions can also be used to solve this problem. In
this, we cumulate the sum using sum(). The task of findall() is to find all
the numerics.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Frequency of numbers in String
# Using re.findall() + sum()
import re
# initializing string
test_str = "geeks4feeks is No. 1 4 geeks"
# printing original string
print("The original string is : " + test_str)
# Frequency of numbers in String
# Using re.findall() + sum()
res = sum(1 for _ in re.finditer(r'\d+', test_str))
# printing result
print("Count of numerics in string : " + str(res))
---
__
__
**Output :**
The original string is : geeks4feeks is No. 1 4 geeks
Count of numerics in string : 3
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
85276698a74c996bbf7b6bfb3752e7d7d86bfb22 | yyf-fan/keyunxing | /勾玉.py | 492 | 3.546875 | 4 | import turtle
mp = turtle.Pen()
mp.speed(0)
#放置图案居中
mp.penup()
mp.goto(140,86)
mp.pendown()
#for循环绘制勾玉
for j in range(3):
#双曲线绘制勾
mp.fillcolor("black")
mp.begin_fill()
mp.dot(100,"black")
mp.backward(50)
mp.right(90)
mp.circle(100,-90)
mp.circle(50,150)
mp.end_fill()
#计算转向时考虑画笔方向
mp.right(90)
mp.penup()
mp.forward(300)
mp.pendown()
turtle.done() |
8d7dc46026cd1e151e740c039a24e4db6d22a05e | mentat-us/PythonExercises | /Chapter_4_Selections/Exercises/Exercise_4_16.py | 97 | 3.546875 | 4 | import random
number = random.randint(65, 90)
print("Random upper case letter is", chr(number)) |
95a68978d7e36e1fb8328f699187105b162ca7ba | WongueShin/codeit_ex | /student.py | 4,309 | 3.703125 | 4 | class Student:
# 코드를 쓰세요
def __init__(self, name, idnum, major):
self.info_manage = InfoManage(name, major, idnum)
self.student_info = Info(self.info_manage.gpa, self.info_manage.name, self.info_manage.major,
self.info_manage.idnum)
self.average_gpa = AverageGpa(self.student_info.out_val())
self.printer = Printer(self.student_info.out_val(), self.average_gpa.average(self.student_info.out_val()))
class Printer:
def __init__(self, vallist, average_val):
self.name = vallist[0]
self.gpa = average_val
self.major = vallist[2]
self.idnum = vallist[3]
def renewval (self, vallist, average_val):
self.name = vallist[0]
self.gpa = average_val
self.major = vallist[2]
self.idnum = vallist[3]
def print_report_card(self, vallist, average_val):
self.renewval(vallist, average_val)
print(f'코드잇 대학 성적표\n\n학생 이름:{self.name}\n학생 번호:{self.idnum}\n소속 학과:{self.major}\n평균 학점:{average_val}')
class AverageGpa:
def __init__(self, vallist):
self.average_val = 'test'
self.placeholder = 0
self.length = 1
self.i = 0
self.gpa_val = vallist[1]
def renewval(self, vallist):
self.gpa_val = vallist[1]
def average(self, vallist):
self.renewval(vallist)
#print('AverageGpa.gpa_val'+str(self.gpa_val))
self.placeholder = 0
for self.i in self.gpa_val:
self.placeholder += self.i
#print('AverageGpa.placeholder= '+str(self.placeholder))
self.length = len(self.gpa_val)
#print('AverageGpa.length= ' + str(self.length))
if len(self.gpa_val) <= 0:
self.length = 1
#print('test if')
self.average_val = self.placeholder / self.length
#print('AverageGpa.average_val= '+str(self.average_val))
return self.average_val
class Info:
def __init__(self, gpa, name, major, idnum):
self.gpa = gpa
self.name = name
self.major = major
self.idnum = idnum
self.vallist = [self.name, self.gpa, self.major, self.idnum]
def input_renew_val (self, vallist):
self.name = vallist[0]
self.gpa = vallist[1]
self.major = vallist[2]
self.idnum = vallist[3]
self.vallist = [self.name, self.gpa, self.major, self.idnum]
def out_val(self):
return self.vallist
class InfoManage:
def __init__(self, name, major, idnum):
self._gpa = []
self._name = name
self._major = major
self._idnum = idnum
@property
def gpa(self):
return self._gpa
@gpa.setter
def gpa(self, new_val):
self._gpa = new_val
@property
def name(self):
return self._name
@name.setter
def name(self, new_val):
self._name = new_val
@property
def major(self):
return self._major
@major.setter
def major(self, new_val):
self._major = new_val
@property
def idnum(self):
return self._idnum
@idnum.setter
def idnum(self, new_val):
self._idnum = new_val
def change_student_info(self, name, idnum, major):
self.name = name
self.idnum = idnum
self.major = major
def add_grade(self, val):
self.gpa.append(val)
def renew_row_val(self):
vallist = [self.name, self.gpa, self.major, self.idnum]
return vallist
# 작성한 클래스에 맞춰서 실행 코드도 바꿔보세요
# 학생 인스턴스 정의
younghoon = Student("강영훈", 20120034, "통계학과")
younghoon.info_manage.change_student_info("강영훈", 20130024, "컴퓨터 공학과")
# 학생 성적 추가
younghoon.info_manage.add_grade(3.0)
younghoon.info_manage.add_grade(3.33)
younghoon.info_manage.add_grade(3.67)
younghoon.info_manage.add_grade(4.3)
younghoon.student_info.input_renew_val(younghoon.info_manage.renew_row_val())
#print('test'+str(younghoon.student_info.gpa))
#print('average'+str(younghoon.average_gpa.gpa_val))
# 학생 성적표
younghoon.printer.print_report_card(younghoon.student_info.out_val(), younghoon.average_gpa.average(younghoon.student_info.out_val()))
|
7a9fa0c750f757eeb8463ef117f11f5b0d344004 | attapun-an/A2_advanced_data_types | /linked_list_ordered.py | 4,478 | 3.96875 | 4 | from LL_node import *
class OrderedList():
def __init__(self):
self.head = None
# isEmpty
def isEmpty(self):
return self.head is None
"""Mr. M: Ca."we know if it's empty, head == None, and if we reach the
end, we get None .Loop through it until we hit None, then add it" """
# add
def add(self, item):
# set up variables
current = self.head
# keeps track of previous item
prev = current
temp = Node(item)
if self.isEmpty() is True:
temp.set_next(None)
self.head = temp
else:
current = current.get_next()
# loop through while the next item is not None AND the position has not been found
while current is not None:
if current.get_data() > item:
temp.set_next(current)
prev.set_next(temp)
return
# Advice from Buta
# when you find a problem, look at every line separately and try to figure it out
# only have one print statement at a time, print separately
# you have to code more, get used to recurssion in code
# use return, stop using print all the time
prev = current
# print("prev: {0}".format(prev.get_data()))
current = current.get_next()
# print("curr: {0}".format(current.get_data()))
temp.set_next(current)
prev.set_next(temp)
# search
def search(self, item):
current = self.head
# if the list is not empty
if self.isEmpty() is not True:
while current is not None:
cur_item = current.get_data()
if cur_item == item:
return {"status": "Found", "item": item}
# Mr. M -- return True -> can be used as a check for remove(item)
else:
current = current.get_next()
return{"status": "Not Found", "item": item}
else:
return{"status": "List is empty", "item": item}
def remove_first(self):
if self.isEmpty() is False:
current = self.head
self.head = current.get_next()
def remove_last(self):
if self.isEmpty() is False:
current = self.head
previous = None
# cheat method
while current.get_next() is not None:
previous = current
current = current.get_next()
previous.set_next(None)
def remove(self, item):
print("attemping to remove {0}".format(item))
# Mr. M -- This should also have a check
current = self.head
previous = None
# found to print result for user (not part of looping mechanism
found = False
while current != None:
if current.get_data() == item:
previous.set_next(current.get_next())
found = True
break
else:
previous = current
current = current.get_next()
return found
def disp_rem_status(self, boolean):
if boolean == True:
print("Item removed")
else:
print("Item not found")
def display2(self):
current = self.head
line = ""
while current is not None:
line = line + (str(current.get_data())) + " "
current = current.get_next()
print (line)
def main():
thisList = OrderedList()
thisList.add(1)
thisList.display2()
thisList.add(2)
thisList.display2()
thisList.add(3)
thisList.display2()
thisList.add(40)
thisList.display2()
thisList.add(5)
thisList.display2()
print(thisList.search(2))
print(thisList.search(40))
print(thisList.search(29))
thisList.display2()
print("""
remove first""")
thisList.remove_first()
thisList.display2()
print("""
remove last""")
thisList.remove_last()
thisList.display2()
remstatus = thisList.remove(3)
thisList.disp_rem_status(remstatus)
remstatus = thisList.remove(5)
thisList.disp_rem_status(remstatus)
thisList.add(40)
thisList.display2()
remstatus = thisList.remove(10)
thisList.disp_rem_status(remstatus)
if __name__ == '__main__':
main()
# remove
|
a0ac834985afe3379e319f2db37b73dacec20c5b | jangjichang/Today-I-Learn | /Algorithm/Programmers/베스트앨범/test_bestalbum.py | 1,174 | 3.8125 | 4 | """
"""
genres = ["classic", "pop", "classic", "classic", "pop"] # , "hiphop", "hiphop"
plays = [500, 600, 150, 800, 2500] # , 1000, 500
returns = [4, 1, 3, 0]
def test_simple():
assert solution(genres, plays) == returns
def solution(genres, plays):
# zipped = zip(genres, plays, range(0, len(genres)))
answer = dict()
for i in zip(genres, plays, range(0, len(genres))):
if answer.get(i[0]) is None:
answer[str(i[0])] = int(i[1])
else:
answer[str(i[0])] += int(i[1])
answer = sorted(answer.items(), key=lambda x: x[1], reverse=True)
returns = list()
for genre in answer:
temp = list()
for genre_plays in zip(genres, plays, range(0, len(genres))):
if genre_plays[0] == genre[0]:
temp.append(genre_plays)
temp = sorted(temp, key=lambda x: x[1], reverse=True)
# print(temp)
if len(temp) >= 2:
returns.append(temp[0][2])
returns.append(temp[1][2])
elif len(temp) == 1:
returns.append(temp[0][2])
# print(answer)
return returns
if __name__ == '__main__':
solution(genres, plays)
|
41d8c61f0779271a6ab1965cf261dc86c2ef3c54 | iamasik/Python-For-All | /C6/Tuple_to_List_to_string.py | 354 | 3.84375 | 4 | Tuple=tuple(range(1,8))
print(Tuple)
#Tuple to list to tuple
List=list(Tuple)
print(List)
List.append(6)
Tuple=tuple(List)
print(Tuple)
Tuple2=tuple(range(1,8))
Str=str(Tuple2)
print(Str)
print(type(Str))
#Join Tuple
T1=(1,2,3,4)
T2=(5,6,7,8)
T3=T1+T2
print(T3)
#Delete tuple
del T1
print(T1) #Error Becouse Tuplw Doesn't Exist |
17a5f20e63d19f233aae4c2fe2f13c8daa8f517c | bharadwajnunna/average-of-students-using-class | /avg students.py | 596 | 3.765625 | 4 | #Use Classes: #Find the avg marks of each student.
class AvgMarks:
print("Avg Marks of each student : ")
def average(self,i,students):
[print("{}\t\t{}\t-->{}".format(j['name'],sum(i)/len(i),sum(i)//len(i))) for j in students if i==j['marks']]
students=[{'name': "John",'rollno': 1234,'marks': [45, 67, 78]},
{'name': "Michael",'rollno': 12345,'marks': [67, 67, 78]},
{'name': "Alexis",'rollno': 1234456,'marks': [67, 55, 88]}
]
st=AvgMarks()
[st.average(i,students) for i in [i['marks'] for i in students]] #using list comprehensive |
6f4adfe7bc218464b2f7e11e98b90cb0b9421154 | kingsley-ijomah/python-basics | /dot-dsl/dot_dsl.py | 1,409 | 3.59375 | 4 | NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self.dst = dst
self.attrs = attrs
def __eq__(self, other):
return (self.src == other.src and
self.dst == other.dst and
self.attrs == other.attrs)
class Graph:
def __init__(self, data=None):
self.nodes = []
self.edges = []
self.attrs = {}
self.data = data or []
if type(self.data) != list: raise TypeError('Type Error')
for tuple in self.data:
if len(tuple) < 2: raise TypeError('Type Error')
for (key, *args) in self.data:
if key == NODE:
if len(args) != 2: raise ValueError('Invalid Value')
self.nodes.append(Node(*args))
elif key == EDGE:
if len(args) != 3: raise ValueError('Invalid Value')
self.edges.append(Edge(*args))
elif key == ATTR:
if len(args) != 2: raise ValueError('Invalid Value')
name, value = args
self.attrs[name] = value
else:
raise ValueError('Invalid Value')
|
45cee2698a98e24244ab00c1383514bd5f9b9d42 | travisrobinson/coursera-specializations | /data-structures-and-algorithms/algorithmic-toolbox/week-2/lcm.py | 214 | 3.625 | 4 | # Uses python3
import sys
def gcd(a, b):
while b!= 0:
(a,b) = (b,a%b)
return a
def main():
a,b = map(int,sys.stdin.readline().split())
c = gcd(a, b)
d = (a*b)//c
print(d)
main()
|
721ff6d2373e9b291533d550215ff196412aee4c | gpf1991/pbase | /day15/exercise/generator.py | 827 | 3.9375 | 4 | # 练习:
# 1. 已知有列表:
# L = [2, 3, 5, 7]
# 1) 写一个生成器函数,让此函数能够动态的提供数据,数据
# 为原列表中数字的平方加1 即 : x**2+1
# 2) 写一个生成器表达式,让此表达式能够动态提供数据,数据
# 同样为原列表中的数字的平方加1
# 3) 生成一个列表,此列表内的数据为原列表L中的数字的平方加1
# 最终生成的数为: 5 10 26 50
L = [2, 3, 5, 7]
def mygen(lst):
for x in lst:
yield x ** 2 + 1
for x in mygen(L):
print(x) # 5 10 26 50
print("--------------------")
gen = (x ** 2 + 1 for x in L)
for x in gen:
print(x)
L2 = [x ** 2 + 1 for x in L]
print("L2=", L2)
# 3) 生成一个列表,此列表内的数据为原列表L中的数字的平方加1
|
1401f8bc06b7cbdf79142af599304d3fe5902d0e | hoxuanhoangduong/hoxuanhoangduong-labs-c4e22 | /Lab3/Homework/ex5.py | 277 | 3.828125 | 4 | from turtle import *
def draw_star(x,y,length):#,color):
# colormode()
# pencolor(color)
penup()
setx(x)
sety(y)
pendown()
for i in range(5):
forward(length)
right(144)
draw_star(20,250,100)
# draw_star(20,250,100,"blue")
mainloop() |
e9c10f66655e4384996bc4d67053cf415ddc7018 | Phong-Hua/Udacity_Show-me-the-Data-Structures | /Problem5.py | 4,611 | 4.71875 | 5 | """
Blockchain
A Blockchain is a sequential chain of records, similar to a linked list. Each block contains some information and
how it is connected related to the other blocks in the chain.
Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data.
For our blockchain we will be using a SHA-256 hash, the Greenwich Mean Time when the block was created, and text strings as the data.
Use your knowledge of linked lists and hashing to create a blockchain implementation.
We can break the blockchain down into three main parts.
First is the information hash:
"""
from datetime import datetime
import hashlib
def calc_hash(self):
sha = hashlib.sha256()
hash_str = "We are going to encode this string of data!".encode('utf-8')
sha.update(hash_str)
return sha.hexdigest()
"""
We do this for the information we want to store in the block chain such as transaction time, data, and information like the previous chain.
The next main component is the block on the blockchain:
"""
class Block:
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calc_hash()
def calc_hash(self):
sha = hashlib.sha256()
hash_str = str(self).encode('utf-8')
sha.update(hash_str)
return sha.hexdigest()
def get_hash(self):
return self.hash
"""
Above is an example of attributes you could find in a Block class.
Finally you need to link all of this together in a block chain, which you will be doing by implementing it in a linked list.
All of this will help you build up to a simple but full blockchain implementation!
"""
class Blockchain:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def append(self, block):
if self.is_empty():
self.head = block
self.tail = block
else:
self.tail = block
self.size += 1
def is_empty(self):
return self.size == 0
def get_size(self):
return self.size
def test_case_1():
"""
"""
print("***********Test_case_1**************")
blockchain = Blockchain()
first_block = Block(datetime.now(), 'First block', 0)
print(blockchain.get_size())
# 0
blockchain.append(first_block)
print(blockchain.get_size())
# 1
second_block = Block(datetime.now(), 'Second block', first_block.get_hash())
blockchain.append(second_block)
print(blockchain.get_size())
# 2
def test_case_2():
"""
Edge test case, with first block is empty string
"""
print("***********Test_case_2**************")
blockchain = Blockchain()
timestamp = datetime.now()
first_block = Block(timestamp, '', 0)
print(blockchain.get_size())
# 0
blockchain.append(first_block)
print(blockchain.get_size())
# 1
def test_case_3():
"""
Edge test case, with second block has same timestamp with first block
"""
print("***********Test_case_3**************")
blockchain = Blockchain()
timestamp = datetime.now()
first_block = Block(timestamp, '', 0)
print(blockchain.get_size())
# 0
blockchain.append(first_block)
print(blockchain.get_size())
# 1
second_block = Block(timestamp, 'Second block', first_block.get_hash())
blockchain.append(second_block)
print(blockchain.get_size())
# 2
def test_case_4():
"""
Edge test case, two blocks have a same data => both hashes should be different
"""
print("***********Test_case_4**************")
blockchain = Blockchain()
first_block = Block(datetime.now(), 'Data', 0)
print(blockchain.get_size())
# 0
blockchain.append(first_block)
print(blockchain.get_size())
# 1
second_block = Block(datetime.now(), 'Data', first_block.get_hash())
blockchain.append(second_block)
print(blockchain.get_size())
# 2
print(first_block.get_hash() != second_block.get_hash())
# True
def test_case_5():
"""
Edge test case, two blocks have a same data, same timestamp => both hashes should be different
"""
print("***********Test_case_5**************")
blockchain = Blockchain()
timestamp = datetime.now()
first_block = Block(timestamp, 'Data', 0)
print(blockchain.get_size())
# 0
blockchain.append(first_block)
print(blockchain.get_size())
# 1
second_block = Block(timestamp, 'Data', first_block.get_hash())
blockchain.append(second_block)
print(blockchain.get_size())
# 2
print(first_block.get_hash() != second_block.get_hash())
# True
test_case_1()
test_case_2()
test_case_3()
test_case_4()
test_case_5() |
e7c4fa27fe60bdde5f5015e8d0627cb05d720ab5 | kimi9527/chess-yi | /chess/chess_view.py | 1,939 | 3.5 | 4 | # coding=utf-8
import pygame
from sys import exit
from chess.images import BACKROUND, SELECTED
MAX_X = 8 # 0-8
MAX_Y = 9 # 0-9
class ChessView(object):
"""
棋盘显示
"""
@staticmethod
def Pixel2XY(pixel_x, pixel_y):
'''
界面像素到棋局坐标变化
'''
x = (pixel_x - 5) // 40
y = (pixel_y - 5) // 40
if x < 0:
x = 0
if x > MAX_X:
x = MAX_X
if y < 0:
y = 0
if y > MAX_Y:
y = MAX_Y
return x, MAX_Y - y
@staticmethod
def XY2ixel(x, y):
"""
棋局坐标到像素变化
"""
x = x * 40 + 5
y = (MAX_Y - y) * 40 + 5
return x, y
def __init__(self):
# init pygame
pygame.init()
# 设置屏幕分辨率 set display
self._screen = pygame.display.set_mode((377, 417))
# 设置标题 set caption
self.set_title("chess yi")
# pygame.display.set_caption("chess yi")
def set_title(self, title: str):
"""
设置标题
"""
if(title == '' or title is None):
return
pygame.display.set_caption(title)
def redraw(self):
"""
刷新界面
"""
# 设置背景图片 set background image
self._screen.blit(BACKROUND, [0, 0])
def show_images(self, images: dict):
if images is None:
return
for x, y in images:
self._screen.blit(images[(x, y)], self.XY2ixel(x, y))
def show_hints(self, positions: []):
if positions is None:
return
for x, y in positions:
self._screen.blit(SELECTED, self.XY2ixel(x, y))
def update(self):
"""
更新显示
"""
pygame.display.update()
def exit(parameter_list):
"""
quit game view
"""
exit()
|
3fb07e8762f1876e6d6cc2680500145be6d333c1 | aa-fahim/leetcode-problems | /Pacific Atlantic Water Flow/main.py | 1,552 | 4.09375 | 4 | '''
DFS Approach
Time Complexity: O((n * m)^ 2) where n is the number of rows and m is the number of columns in the matrix.
Iterate through each position of the grid and perform DFS until we have visited a node that touches the atlantic ocean and a node that touches the pacific ocean.
'''
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
rows, cols = len(heights), len(heights[0])
res = []
def dfs(r, c):
pacific = False
atlantic = False
stack = [(r,c)]
moves = [(0,1), (0,-1), (1,0), (-1,0)]
visited = set()
while(len(stack) > 0):
r, c = stack.pop(-1)
visited.add((r,c))
if r == 0 or c == 0:
pacific = True
if r == rows - 1 or c == cols - 1:
atlantic = True
if atlantic and pacific:
break
for nr, nc in moves:
if (r + nr, c + nc) not in visited and (r + nr) in range(rows) and (c + nc) in range(cols) and heights[r][c] >= heights[r + nr][c + nc]:
stack.append((r + nr, c + nc))
return pacific and atlantic
for r in range(rows):
for c in range(cols):
tmp = dfs(r, c)
if tmp == True:
res.append([r, c])
return res
|
ce1d72b36cfd56f5ae1e75bce167417dced8055d | taihuibantian/workspace | /binary_search.py | 721 | 3.8125 | 4 | import sys
#二分探索法
# arr : 数値リスト
# n : 要素数
# left : 左端要素のindex
# right : 右端要素のindex
# center : 中央要素のindex
# target : 探索値
arr = [11,13,24,26,35,37,46,49,54,68]
print(arr)
target=input("探索値を入力する:")
target=int(target)
n = len(arr)
left = 0
right = n -1
while left <= right:
center = (left + right) // 2 #要素の真ん中をチェック
if arr[center] == target:
print(f"探索値:{target}は0から数えて{center}番目にあります")
sys.exit()
elif arr[center] < target:
left = center + 1
else:
right = center - 1
print(f'探索値:{target}は見つかりませんでした') |
a53c4569ce35be5d1a7556b07f491ac2477f1966 | danaimone/Grokking-The-Coding-Interview-Solutions | /Tree Breadth First Search/zigzag_traversal.py | 1,260 | 4.09375 | 4 | from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def traverse(root):
result = []
if root is None:
return result
queue = deque()
queue.append(root)
left_to_right = True
while queue:
level_size = len(queue)
current_level = deque()
for i in range(level_size):
current_node = queue.popleft()
if left_to_right:
current_level.append(current_node.val)
else:
current_level.appendleft(current_node.val)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
result.append(list(current_level))
left_to_right = not left_to_right
return result
def main():
root = TreeNode(12)
root.left = TreeNode(7)
root.right = TreeNode(1)
root.left.left = TreeNode(9)
root.right.left = TreeNode(10)
root.right.right = TreeNode(5)
root.right.left.left = TreeNode(20)
root.right.left.right = TreeNode(17)
print("Zigzag traversal: " + str(traverse(root)))
if __name__ == "__main__":
main()
|
372f952d9817c4e4e954584deb96a912673e8c5d | Kapilpatidar5001/MPT1 | /mid1_1.py | 309 | 3.59375 | 4 | l1=(input("enter list 1 seperated by comma")).split(',')
w=input("enter world to remove")
o=int(input("enter the occurence to remove"))
c=0
r=[]
print(type(w))
print(l1)
for i in l1:
if (i==w):
c=c+1
if (c!=o):
r.append(i)
else:
r.append(i)
print(r)
|
84b4313b59cb60649f27d1a01a9237f7bb3cf253 | arundhathips/programs_arundhathi | /CO1 pg 11.py | 304 | 4.28125 | 4 | #Find biggest of 3 numbers entered.
x = int(input("Enter 1st number: "))
y = int(input("Enter 2nd number: "))
z = int(input("Enter 3rd number: "))
if (x > y) and (x > z):
largest = x
elif (y > x) and (y > z):
largest = y
else:
largest = z
print("The largest number is",largest) |
3945694a0bb9cf543a828b7af9d267a11471cf26 | sgfm/BrightsideDataChallenge | /main.py | 3,179 | 3.71875 | 4 | import pandas as pd
import numpy as np
import pickle
import math
def check_interest(loan, desired_interest):
'''
Checks if the loan has the desired interest rate to invest. Returns boolean.
'''
return float(loan.int_rate[:-1]) >= desired_interest
def format_loan(loan):
'''
This takes in a loan and formats it to be evaluated by the machine learning models. This is a replication of the cleaning process seen in the notebook.ipynb
'''
#Loading in the columns
col = pickle.load( open( "columns.pkl", "rb" ) )
zero_data = np.zeros(shape=(1,len(col)))
#Creating the zeroed dataframe
s = pd.DataFrame(zero_data, columns=col)
#Populating the dataframe with the correct dummies from the loan
dummy_lis = ['sub_grade', 'home_ownership', 'verification_status', 'issue_d', 'purpose', 'addr_state']
for dummy in dummy_lis:
dum = loan[f'{dummy}']
s.dum = 1
#Transforming the features in the loan
arr = loan[['annual_inc', 'delinq_amnt', 'tot_coll_amt', 'total_rec_late_fee']] + 1
for i, x in enumerate(arr):
arr[i] = math.log(x)
loan.loc[['annual_inc', 'delinq_amnt', 'tot_coll_amt', 'total_rec_late_fee']] = arr
loan.tax_liens = math.sqrt(loan.tax_liens)
#Converting the interest string to a float
loan.int_rate = float(loan.int_rate[:-1])
#Turning the binary catagories into booleans
if loan.term == ' 36 months':
loan.term = True
else:
loan.term = False
if loan.initial_list_status == 'w':
loan.initial_list_status = True
else:
loan.initial_list_status = False
if loan.application_type == 'Individual':
loan.application_type = True
else:
loan.application_type = False
if loan.disbursement_method == 'Cash':
loan.disbursement_method = True
else:
loan.disbursement_method = False
for index, value in loan.items():
if index in s.columns:
s[f'{index}'] = value
return s
def evaluate_loan(loan, desired_interest):
'''
This functions pulls everything together. Returns True if the desired interest rate is met and the models find that the loan wont go into default, hardship, or settlement.
'''
if check_interest(loan, desired_interest):
hardship_model = pickle.load( open( "models/final_hardship_model.pkl", "rb" ) )
settle_model = pickle.load( open( "models/final_settle_model.pkl", "rb" ) )
default_model = pickle.load( open( "models/final_default_model.pkl", "rb" ) )
clean_loan = format_loan(loan)
res_lis = [hardship_model.predict(clean_loan)[0], settle_model.predict(clean_loan)[0], default_model.predict(clean_loan)[0]]
return not any (res_lis)
else:
return False
if __name__ == "__main__":
#This is where you can add a stream of data or another data set. Using the first row of the first csv for demonstration.
df = pd.read_csv('data/2016Q1.csv.gz')
loan = df.iloc[0]
desired_interest = 5 #Least interest rate acceptable
if evaluate_loan(loan, desired_interest):
print('Approved')
else:
print('Disapproved')
|
e42f291e8f902a91b6e44eacb16ee490c52ccb85 | messerzen/Pythont_CEV | /aula06_desafio01.py | 128 | 3.8125 | 4 | n1=int(input('Digite um nro:'))
n2=int(input('Digite outro nro:'))
s=n1+n2
print('A soma entre {} e {} é {}'.format(n1, n2, s)) |
a10a0606ba1732d757f5814c5e5955aadab4e0cc | kingfi/cs181-s21-homeworks | /hw1/T1_P4.py | 4,669 | 3.5625 | 4 | #####################
# CS 181, Spring 2021
# Homework 1, Problem 4
# Start Code
##################
import csv
import numpy as np
import matplotlib.pyplot as plt
import math
csv_filename = 'data/year-sunspots-republicans.csv'
years = []
republican_counts = []
sunspot_counts = []
with open(csv_filename, 'r') as csv_fh:
# Parse as a CSV file.
reader = csv.reader(csv_fh)
# Skip the header line.
next(reader, None)
# Loop over the file.
for row in reader:
# Store the data.
years.append(float(row[0]))
sunspot_counts.append(float(row[1]))
republican_counts.append(float(row[2]))
# Turn the data into numpy arrays.
years = np.array(years)
republican_counts = np.array(republican_counts)
sunspot_counts = np.array(sunspot_counts)
last_year = 1985
# Plot the data.
plt.figure(1)
plt.plot(years, republican_counts, 'o')
plt.xlabel("Year")
plt.ylabel("Number of Republicans in Congress")
plt.figure(2)
plt.plot(years, sunspot_counts, 'o')
plt.xlabel("Year")
plt.ylabel("Number of Sunspots")
plt.figure(3)
plt.plot(sunspot_counts[years<last_year], republican_counts[years<last_year], 'o')
plt.xlabel("Number of Sunspots")
plt.ylabel("Number of Republicans in Congress")
plt.show()
# Create the simplest basis, with just the time and an offset.
X = np.vstack((np.ones(years.shape), years)).T
# TODO: basis functions
# Based on the letter input for part ('a','b','c','d'), output numpy arrays for the bases.
# The shape of arrays you return should be: (a) 24x6, (b) 24x12, (c) 24x6, (c) 24x26
# xx is the input of years (or any variable you want to turn into the appropriate basis).
# is_years is a Boolean variable which indicates whether or not the input variable is
# years; if so, is_years should be True, and if the input varible is sunspots, is_years
# should be false
def make_basis(xx,part='a',is_years=True):
#DO NOT CHANGE LINES 65-69
if part == 'a' and is_years:
xx = (xx - np.array([1960]*len(xx)))/40
if part == "a" and not is_years:
xx = xx/20
if part == "a":
arr = []
arr = [[ x**j for j in range(6)] for x in xx]
return np.array(arr)
if part == 'b':
arr = []
arr = [ ([1] + [math.exp(( -(x - j)**2) / 25) for j in range(1960, 2011, 5)]) for x in xx]
return np.array(arr)
if part == 'c':
arr = []
arr = [ ([1] + [ math.cos(x / j) for j in range(1, 6)]) for x in xx]
return np.array(arr)
if part == 'd':
arr = []
arr = [ ([1] + [ math.cos(x / j) for j in range(1, 26)]) for x in xx]
return np.array(arr)
return
#print("basis ", make_basis(years, part="b", is_years=True))
# Nothing fancy for outputs.
Y = republican_counts
# Find the regression weights using the Moore-Penrose pseudoinverse.
def find_weights(X,Y):
w = np.dot(np.linalg.pinv(np.dot(X.T, X)), np.dot(X.T, Y))
return w
# Compute the regression line on a grid of inputs.
# DO NOT CHANGE grid_years!!!!!
grid_years = np.linspace(1960, 2005, 200)
grid_sunspots = np.linspace(0, 160, 200)
#grid_X = np.vstack((np.ones(grid_years.shape), grid_years))
print("Years Loss: ")
for part in ['a', 'b', 'c', 'd']:
w = find_weights(make_basis(years, part= part, is_years=True), Y)
basis = make_basis(grid_years, part=part)
grid_Yhat = np.dot(basis, w)
# TODO: plot and report sum of squared error for each basis
loss = 0
for i in range(len(Y)):
yhat = np.dot(make_basis(years, part = part), w)
y = Y[i]
loss = loss + (y - yhat[i])**2
print('L2: ', loss)
# Plot the data and the regression line
plt.plot(years, republican_counts, 'o', grid_years, grid_Yhat, '-')
plt.xlabel("Year")
plt.ylabel("Number of Republicans in Congress")
plt.savefig('Year_' + part + '.png')
plt.show()
print("Sunspot Loss: ")
for part in ['a', 'c', 'd']:
w = find_weights(make_basis(sunspot_counts[years < last_year], part= part, is_years=False), Y[years < last_year])
basis = make_basis(grid_sunspots, part = part, is_years=False)
grid_Yhat = np.dot(basis, w)
loss = 0
for i in range(len(Y[years < last_year])):
yhat = np.dot(make_basis(sunspot_counts[years < last_year], part = part, is_years=False), w)
y = Y[i]
loss = loss + (y - yhat[i])**2
print('L2: ', loss)
# Plot the data and the regression line
plt.plot(sunspot_counts[years < last_year], republican_counts[years < last_year], 'o', grid_sunspots, grid_Yhat, '-')
plt.xlabel("Sunspot Count")
plt.ylabel("Number of Republicans in Congress")
plt.savefig('Sunspot' + part + '.png')
plt.show()
|
7cf57531750623eed76a78f9f8284407a11887a3 | Farooqut21/my-work | /assignment from 3 .1 to 3.13/3.10/no vowel.py | 136 | 3.75 | 4 | s=input("enter a string")
def noVowel(s):
for char in s:
if char in 'aeiou':
return False
return True
|
b53aa413ac28e2375c5554fee45739ad55daba43 | joaqFarias/poo-python | /tienda_y_productos/product_lib.py | 684 | 3.859375 | 4 | class product:
def __init__(self, name: str, price: int, category:str) -> None:
self.name = name
self.price = price
self.category = category
def update_price(self, percent_change: float, is_increased: bool) -> object:
if is_increased == True:
self.price = self.price + (percent_change * self.price)
else:
self.price = self.price - (percent_change * self.price)
print(f"el nuevo precio del producto {self.name} es {self.price}")
return self
def print_info(self) -> object:
print(f"Nombre producto: {self.name} | Categoria: {self.category} | Precio: {self.price}")
return self |
de148db132644417340bd5675fbcc4e9a4225f6a | schwertJake/Barren_Land_Analysis | /barren_land_graph/barren_land.py | 1,571 | 3.5625 | 4 | """
barren_land.py
This module is the vertex objects for the graph
that will be created from the barren land plots.
The vertex contains coordinates and total area.
"""
class BarrenLand:
_coord_map = {
"x0": 0,
"y0": 1,
"x1": 2,
"y1": 3
}
_plotly_viz_attr = {
"type": "rect",
"line": {
"color": "rgba(255, 69, 0, 1)",
"width": 2,
},
"fillcolor": "rgba(255, 69, 0, 0.7)"
}
def __init__(self, coord_arr: list, index: int):
self.coord_dict = self._assign_coordinates(coord_arr)
self.index = index # index in list of barren land object
self.area = (self.coord_dict['x1'] - self.coord_dict['x0']) * \
(self.coord_dict['y1'] - self.coord_dict['y0'])
def _assign_coordinates(self, coord_arr: list) -> dict:
"""
Takes the raw input list of ints of form [X0 Y0 X1 Y1]
for the rectangle, and assigns to self.coord_dict via
self.coord_map
:param coord_str: list of coordinates
:return: none
"""
ret_dict = {}
for key, val in self._coord_map.items():
ret_dict[key] = coord_arr[val]
ret_dict['x1'] += 1
ret_dict['y1'] += 1
return ret_dict
def display(self):
"""
Returns a dictionary with coordinates and visualization
properties to be displayed via Plotly
:return: dict or plotly display attributes
"""
return dict(**self.coord_dict, **self._plotly_viz_attr)
|
f4545a9e1017d08c40c7e0467ca95a92752b84ad | GriTRini/study | /python/1일차/알바비계산.py | 737 | 3.921875 | 4 | #응용문제1 : Part-time calculation Program
name = str(input('alba name : '))
hour = int(input('hour: '))
pay = int(input('pay : '))
total = hour * pay
print(total)
#출력방법
#1. 콤마연산자사용
print(name ,'님의 총 금액은',total, '원 입니다. 수고많으셨습니다.^^')
#2. 형식문자(서식문자) 사용 : 정수(%d), 실수(%f), 문자열(%s)
print('알바생의 이름은 %s 입니다' % name)
print('총금액은 %d 입니다' % total)
#3. 문자열 .format()함수
print('알바생의 이름은{}입니다'.format(name))
print('%s님의 총금액은 %d원입니다.' % (name, total))
#4. f-string 사용
print(f'알바생의 이름은 {name}입니다.')
print(f'총금액은 {total}입니다.')
|
90b6c518ba17e1b79f97899aacc68e2c7c193417 | SinCatGit/leetcode | /00204/count_primes.py | 727 | 3.65625 | 4 | class Solution:
def countPrimes(self, n: int) -> int:
"""
[204. Count Primes](https://leetcode.com/problems/count-primes/)
Count the number of prime numbers less than a non-negative number, *n*.
**Example:**
```
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
```
"""
if n <= 2:
return 0
res = [1]*n
res[0], res[1] = 0, 0
for i in range(2, int(n**0.5)+1):
if res[i] == 1:
res[i*i:n:i] = [0]*(len(res[i*i:n:i]))
return sum(res)
if __name__ == '__main__':
sol = Solution()
print(sol.countPrimes(499979))
|
99b610579e5eafe4c7a218b45cc1412ff2814a83 | arnabs542/DataStructures_Algorithms | /bitwise/Min_XOR_value.py | 638 | 3.8125 | 4 | '''
Min XOR value
Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value.
Report the minimum XOR value.
Problem Constraints:
2 <= length of the array <= 100000
0 <= A[i] <= 109
Input 1:
A = [0, 2, 5, 7]
Input 2:
A = [0, 4, 7, 9]
Output 1:
2
Output 2:
3
'''
class Solution:
# min xor can only be obtained between adjacent elements, a[0] ^ a[3] will never be lesser than a[0]^a[1] in a sorted arr
def findMinXor(self, a):
a.sort()
min_x = float('inf')
for i in range(0,len(a)-1):
min_x = min(min_x, a[i]^a[i+1])
return min_x |
785da3de78d0e5059a632a62eb95d191e190e185 | pdturney/modeling-major-transitions | /view_contest.py | 4,776 | 3.515625 | 4 | #
# View Contest
#
# Peter Turney, July 16, 2019
#
# Select two seeds from pickles and watch them battle.
#
import golly as g
import model_classes as mclass
import model_functions as mfunc
import model_parameters as mparam
import random as rand
import time
import pickle
import os
#
# Open a dialog window and ask the user to select two pickles.
#
g.note("View Contest\n\n" + \
"You will be presented with two dialog menus:\n" + \
" (1) Select a file of pickled seeds.\n" + \
" (2) Select another file of pickled seeds.\n" + \
"Two seeds, chosen randomly from each pickle, will then compete.")
#
path1 = g.opendialog("Select the first pickled seed file (*.bin)", \
"(*.bin)|*.bin", g.getdir("app"))
path2 = g.opendialog("Select the second pickled seed file (*.bin)", \
"(*.bin)|*.bin", g.getdir("app"))
#
# Some info to display to the user, in the header of the main window.
#
[head1, tail1] = os.path.split(path1)
[head2, tail2] = os.path.split(path2)
#
g.show("Red: " + path1 + " Blue: " + path2)
#
# Load pickles and select the first seed from each pickle.
# The seeds are in order of decreasing fitness.
#
handle1 = open(path1, "rb") # rb = read binary
pickle1 = pickle.load(handle1)
handle1.close()
seed1 = rand.choice(pickle1) # random seed from pickle1
#
handle2 = open(path2, "rb") # rb = read binary
pickle2 = pickle.load(handle2)
handle2.close()
seed2 = rand.choice(pickle2) # random seed from pickle2
#
# Let the seeds play the Immigration Game.
#
width_factor = mparam.width_factor
height_factor = mparam.height_factor
time_factor = mparam.time_factor
#
# At the bottom of this loop, the user will be prompted to quit
# the loop, if desired.
#
while True:
# random rotation of seeds
s1 = seed1.random_rotate()
s2 = seed2.random_rotate()
# switch red to blue in the second seed
s2.red2blue()
# set up Golly
[g_width, g_height, g_time] = mfunc.dimensions(s1, s2, \
width_factor, height_factor, time_factor)
g.setalgo("QuickLife") # use the QuickLife algorithm
g.new("Immigration") # initialize cells to state 0
g.setrule("Immigration:T" + str(g_width) + "," + str(g_height)) # make a toroid
[g_xmin, g_xmax, g_ymin, g_ymax] = mfunc.get_minmax(g) # find range of coordinates
s1.insert(g, g_xmin, -1, g_ymin, g_ymax) # insert the first seed into Golly
s2.insert(g, +1, g_xmax, g_ymin, g_ymax) # insert the second seed into Golly
g.setmag(mfunc.set_mag(g)) # set magnification
g.setcolors([0,255,255,255]) # set state 0 (the background) to white
#
g.update() # show the intial state
#
g.note("These are the intial seeds.\n" + \
"Red is on the left and blue is on the right.\n" + \
"The file names are in the header of the main window.\n" + \
"Drag this note to a new location if it is blocking your view.\n\n" + \
"Red seed directory: " + head1 + "\n" + \
"Red seed file: " + tail1 + "\n" + \
"Red seed size: {} x {}\n".format(seed1.xspan, seed1.yspan) + \
"Red seed density: {:.4f} ({} ones)\n\n".format(seed1.density(), \
seed1.count_ones()) + \
"Blue seed directory: " + head2 + "\n" + \
"Blue seed file: " + tail2 + "\n" + \
"Blue seed size: {} x {}\n".format(seed2.xspan, seed2.yspan) + \
"Blue seed density: {:.4f} ({} ones)\n\n".format(seed2.density(), \
seed2.count_ones()) + \
"Select OK to begin the competition.\n")
#
while (int(g.getgen()) < g_time):
g.run(1) # run for 1 step without displaying
g.update() # now display
#
[count1, count2] = mfunc.count_pops(g) # see who won
if (count1 > count2):
result = "Red won! Red: {}. Blue: {}.\n\n".format(count1, count2)
elif (count2 > count1):
result = "Blue won! Red: {}. Blue: {}.\n\n".format(count1, count2)
else:
result = "Tie! Red: {}. Blue: {}.\n\n".format(count1, count2)
#
# Note that s2 is blue, which means it contains twos, not ones.
# Thus we use seed2, which is red, for density() and count_ones().
#
message = result + \
"Red seed directory: " + head1 + "\n" + \
"Red seed file: " + tail1 + "\n" + \
"Red seed size: {} x {}\n".format(seed1.xspan, seed1.yspan) + \
"Red seed density: {:.4f} ({} ones)\n\n".format(seed1.density(), \
seed1.count_ones()) + \
"Blue seed directory: " + head2 + "\n" + \
"Blue seed file: " + tail2 + "\n" + \
"Blue seed size: {} x {}\n".format(seed2.xspan, seed2.yspan) + \
"Blue seed density: {:.4f} ({} ones)\n\n".format(seed2.density(), \
seed2.count_ones()) + \
"Select Cancel to end.\n" + \
"Select OK to run again with new rotations and locations."
#
g.note(message) # here is where the user can quit
#
#
# |
89bfe9554fc45480038510661013667fbf9bc782 | soumya9988/Python_Machine_Learning_Basics | /Python_Basic/4_Lists/list_basics.py | 992 | 4 | 4 | my_shopping_list = ['butter', 'egg', 'milk', 'fish', 'potato']
dessert_list = ('ice cream', 'cookie', 'pineapple')
print('I have %d items to buy and they are: ' % (len(my_shopping_list)))
for item in my_shopping_list:
print(item, end=' ')
my_shopping_list.sort()
print('After sorting, the list is: ', my_shopping_list)
my_shopping_list.append('Water melon')
print('Modified shopping list is: ', my_shopping_list)
del my_shopping_list[2]
print('After deletion the list is ', my_shopping_list)
my_shopping_list.insert(2, 'Ice cream')
print('Adding new value: ', my_shopping_list)
ind = my_shopping_list.index('egg')
print('Index of egg is: ', ind)
# Tuples.....
print('The dessert menu is', dessert_list)
food_menu = ('Pasta', 'meatballs', dessert_list)
print('Food menu is :')
for item in food_menu:
print(item, end=' ')
print('Number of dessert items are: ', len(food_menu[2]))
print('Hope you like all the %d items!' % (len(food_menu) - 1 + len(food_menu[2])))
|
feb64b4ddca2623f736c0ed638e0d8b4e87ca877 | Grug16/CS112-Spring2012 | /Objects2.py | 963 | 4.25 | 4 | #!/usr/bin/env python
class Student(object):
def __init__(self, name):
self.name = name
def say(self, message):
print self.name +": "+message
def say_to(self,other,message):
self.say(message+", "+other.name)
def printf(self):
print self.name
bob = Student("Bob")
fred = Student("Fred")
fred.say("No way")
juliet = Student("Juliet")
bob.say_to(fred, "I love you")
bob.say("Hi Fred.")
fred.say("Go away, Bob.")
class Course(object):
def __init__(self, name):
self.name = name
self.enrolled=[]
def enroll(self, student):
self.enrolled.append(student)
def printf(self):
for student in self.enrolled:
student.printf()
bob = Student("Bob")
fred = Student("Fred")
cs112 = Course("CS112")
cs112.enrolled.append(bob) #this is bad. Better to use as a function than direct access
cs112.enroll(fred)
cs112.printf()
bob2 = bob
print bob2 is bob |
37628c443287fe3222077c047359a2437f57e91a | damiansp/AI_Learning | /AI_modern_approach/03_SolvingBySearching/missionariesAndCannibals/missionaries_and_cannibals.py | 2,187 | 3.5 | 4 | def get_boat_side(state):
return 0 if state[0][2] == 1 else 1
# Test
#print(get_boat_side([[0, 0, 0], [3, 3, 1]]))
#print(get_boat_side([[3, 3, 1], [0, 0, 0]]))
def cross_river(state, n_cannibals, n_missionaries, boat_side):
new_state = [state[0][:], state[1][:]]
change = [n_cannibals, n_missionaries, 1]
for i, n in enumerate(change):
new_state[boat_side][i] -= n
new_state[1 - boat_side][i] += n
return new_state
# Test
#state = [[3, 3, 1], [0, 0, 0]]
#print(cross_river(state, 1, 1, 0))
#print(cross_river(state, 2, 0, 0))
#state = [[1, 1, 0], [2, 2, 1]]
#print(cross_river(state, 2, 0, 1))
def is_legal(state):
for bank in state:
n_cannibals, n_missionaries = bank[0:2]
if n_cannibals and n_missionaries and n_cannibals > n_missionaries:
return False
return True
# Test
#print(is_legal([[3, 3, 1], [0, 0, 0]]))
#print(is_legal([[3, 1, 0], [0, 2, 1]]))
def expand(state):
boat_side = get_boat_side(state)
cannibal_range = range(state[boat_side][0] + 1)
missionary_range = range(state[boat_side][1] + 1)
moves = [[c, m] for c in cannibal_range for m in missionary_range
if 0 < c + m < 3]
resulting_states = []
for move in moves:
c, m = move
resulting_state = (cross_river(state, c, m, boat_side))
if is_legal(resulting_state):
resulting_states.append(resulting_state)
return resulting_states
# Test
#print(expand([[3, 3, 1], [0, 0, 0]]))
#print(expand([[2, 2, 0], [1, 1, 1]]))
def main():
goal_state = [[0, 0, 0], [3, 3, 1]]
unexplored_states = [[[3, 3, 1], [0, 0, 0]]]
explored_states =[]
while goal_state not in explored_states:
print('\nExplored States:')
for es in explored_states:
print(' ', es)
next_state_to_explore = unexplored_states.pop()
reachable_states = expand(next_state_to_explore)
explored_states.append(next_state_to_explore)
for state in reachable_states:
if state not in explored_states:
unexplored_states.append(state)
print('Goal state found!')
if __name__ == '__main__':
main()
|
a2e030d61c355b54573bb9b8f9c59c88a8a50426 | Twice22/PythonMachineLearning | /ch10/PolynomialRegression/lr_to_polreg.py | 1,919 | 3.6875 | 4 | # in the previous sections, we assumed a linear relationship between
# explanatory and response variables but we can have sth like :
# y = w0 + w1x + w2x²x² + ... + wdx^d
# we will use PolynomialFeatures transformer class from scikit
# to add a quadratic term (d = 2) to a simple reg problem with
# one explanatory variable and compare the pol to the linear fit
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# np.newaxis transform it to a col vect
X = np.array([258.0, 270.0, 294.0, 320.0, 342.0, 368.0,
396.0, 446.0, 480.0, 586.0])[:, np.newaxis]
y = np.array([236.4, 234.4, 252.8, 298.6, 314.2, 342.2,
360.8, 368.0, 391.2, 390.8])
lr = LinearRegression()
pr = LinearRegression()
# add a second degreee polynomial term
quadratic = PolynomialFeatures(degree=2)
X_quad = quadratic.fit_transform(X)
# fit a simple linear reg model for comparison:
lr.fit(X, y)
# [[250] [260] [270] ... [590]]
X_fit = np.arange(250,600,10)[:, np.newaxis]
y_lin_fit = lr.predict(X_fit)
# fit a multiple reg model on the transformed features for
# polynomial regression:
pr.fit(X_quad, y)
# need to transform to pol before predicting using pr classifier
y_quad_fit = pr.predict(quadratic.fit_transform(X_fit))
plt.scatter(X, y, label='training points') # nuage de point
plt.plot(X_fit, y_lin_fit, label='linear fit', linestyle='--')
plt.plot(X_fit, y_quad_fit, label='quadratic fit')
plt.legend(loc='upper left')
plt.show()
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
y_lin_pred = lr.predict(X)
y_quad_pred = pr.predict(X_quad)
print('Training MSE linear: %.3f, quadractic: %.3f' % (
mean_squared_error(y, y_lin_pred),
mean_squared_error(y, y_quad_pred)))
print('Training R^2 linear: %.3f, quadratic: %.3f' % (
r2_score(y, y_lin_pred),
r2_score(y, y_quad_pred))) |
b0ee47291040fa7a225796bd2d7510a0bafa7583 | paulwratt/cloudmesh-pi-burn | /cloudmesh/burn/wifi/ubuntu.py | 2,079 | 3.59375 | 4 | """
Implementation of a function the set the WIFI configuration.
This function is primarily developed for a Raspberry PI
"""
import textwrap
from cloudmesh.common.console import Console
from cloudmesh.common.sudo import Sudo
from cloudmesh.common.util import writefile
class Wifi:
"""
The class is used to group a number of useful variables and functions so
it is easier to program and manage Wifi configurations.
The default location for the configuration file is
/etc/wpa_supplicant/wpa_supplicant.conf
"""
location = "/etc/wpa_supplicant/wpa_supplicant.conf"
template = textwrap.dedent("""
wifis:
wlan0:
dhcp4: true
optional: true
access-points:
{ssid}:
password: "{password}"
""").strip()
@staticmethod
def set(ssid=None,
password=None,
country="US",
psk=True,
location=location,
sudo=False):
"""
Sets the wifi. Only works for psk based wifi
:param ssid: The ssid
:type ssid: str
:param password: The password
:type password: str
:param country: Two digit country code
:type country: str
:param psk: If true uses psk authentication
:type psk: bool
:param location: The file where the configuration file should be written to
:type location: str
:param sudo: If tru the write will be done with sudo
:type sudo: bool
:return: True if success
:rtype: bool
"""
if ssid is None or password is None:
Console.error("SSID or password not set")
return False
config = Wifi.template.format(**locals())
try:
if sudo:
Sudo.writefile(location, config)
else:
writefile(location, config)
except FileNotFoundError as e: # noqa: F841
Console.error(f"The file does not exist: {location}")
return False
return True
|
2a2d0440139eee30be0e720ff3b02b31edaaf0c8 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/kindergarten-garden/4243f13b01c94421ac2f8cd5e668440f.py | 722 | 3.671875 | 4 | from collections import defaultdict
class Garden:
def __init__(self, plants, students=('Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry')):
self._garden = defaultdict(list)
students = tuple(sorted(students))
flowers = dict( (f[0], f) for f in ('Grass', 'Clover', 'Radishes', 'Violets'))
for row in plants.split('\n'):
for i, f in enumerate(row):
self._garden[students[i/2]].append(flowers[f])
def plants(self, who):
return self._garden[who]
if __name__ == '__main__':
print Garden('VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV')._garden
|
c2bde8e8a379ffd502cce4f76079a76aac8b4345 | ksvikram/hRankworkouts | /python/RegEx/Applications/SplitthePhoneNumbers.py | 274 | 3.765625 | 4 | import re
R = re.compile(r'(\d{1,3})[\-\ ](\d{1,3})[\-\ ](\d{4,10})')
for _ in range(input()):
line = raw_input()
match = R.search(line)
if match:
print 'CountryCode={},LocalAreaCode={},Number={}'.format(match.group(1), match.group(2), match.group(3))
|
cc4572c43d3aa694e03255f9f94d1bd43628d532 | kwura/python-projects | /Foundations of Programming/Spiral.py | 2,808 | 4.5625 | 5 | # Description: Creates a spiral with a specific dimension and outputs the neighboring numbers of a target number in three lines.
def make_spiral(dims):
# create 2-D list with zeros
a = []
for i in range (dims):
b = []
for j in range(dims):
b.append(0)
a.append(b)
reference = dims ** 2
for limit in range (dims//2):
# Start at top right corner and go left
index = len(a[0]) - 1 - limit
while( index >= limit):
a[limit][index] = reference
index -= 1
reference -= 1
# Go down first column
index = limit + 1
while(index < len(a) - limit):
a[index][limit] = reference
index += 1
reference -= 1
# Go through bottom row left to right
index = limit + 1
while(index < (len(a[0]) - limit)):
a[len(a) - 1 - limit][index] = reference
index += 1
reference -= 1
# Go up last column
index = len(a) -2 - limit
while(index > limit):
a[index][len(a[0])-1 - limit] = reference
index -= 1
reference -= 1
# Fill in the center of the spiral
a[dims//2][dims//2] = 1
# Return the spiral
return a
def is_onEdge(number, list):
# Check if number is on vertical sides of perimeter
for i in range (len(list)):
if(list[i][0]== number or list[i][len(list) -1]==number):
return True
# Check if number is on horizontal sides of perimeter
if( number in list[0] or number in list[len(list)-1]):
return True
return False
def find_target(number, list):
# Find location of target number and return the index of the row and column
for i in range(1, len(list) -1):
if( number in list[i]):
row = i
column = list[i].index(number)
return row, column
def main():
# Prompt the user for number of dimensions
dims = input("Enter dimension: ")
while( dims.isdigit() == False ):
dims = input("Enter dimension: ")
dims = int(dims)
if( dims % 2 == 0 ):
dims += 1
# Prompt the user for number in spiral
target = input("Enter number in spiral: ")
while( target.isdigit() == False ):
target = input("Enter number in spiral: ")
target = int(target)
if( target < 1 or target > dims**2 ):
print()
print("Number not in Range")
return
# Create the spiral
spiral = make_spiral(dims)
# Check if second number is on perimeter
if(is_onEdge(target,spiral)):
print()
print("Number on Outer Edge")
return
# Find the target
row, column = find_target(target, spiral)
# Print the output
print()
print(spiral[row-1][column-1], spiral[row-1][column], spiral[row-1][column+1])
print(spiral[row][column-1], spiral[row][column], spiral[row][column+1])
print(spiral[row+1][column-1], spiral[row+1][column], spiral[row+1][column+1])
main() |
ec2cf5c57b123686804436dc8ef7d6fb0d33069b | slchangtw/Advanced_Programming_in_Python_Jacobs | /assignment_6/vballsim.py | 2,952 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# JTSK-350112
# a6_3.py
# Shun-Lung Chang
# sh.chang@jacobs-university.de
from random import random
def get_inputs():
# RETURNS prob_a, prob_b, number of games to simulate
a = float(input("What is the prob. player A wins a serve (between 0 and 1)? "))
b = float(input("What is the prob. player B wins a serve (between 0 and 1)? "))
n = int(input("How many games to simulate (larger than 0)? "))
if not (0 <= a <= 1) or not (0 <= b <= 1) or n <= 0:
raise ValueError('Some inputs are invalid.')
return a, b, n
def game_over(a, b, sanctioned=False):
# a and b are scores for teams in a volleyball game
# RETURNS true if game is over, false otherwise
if not sanctioned:
return (a >= 15 or b >= 15) and (abs(a-b) >= 2)
else:
return a == 25 or b == 25
def sim_one_game(prob_a, prob_b, sanctioned=False):
# Simulates a single game between teams A and B
# RETURNS A's final score, B's final score
serving = "A"
score_a = 0
score_b = 0
while not game_over(score_a, score_b, sanctioned):
if serving == "A":
if random() < prob_a:
score_a = score_a + 1
else:
if sanctioned:
score_b = score_b + 1
serving = "B"
else:
if random() < prob_b:
score_b = score_b + 1
else:
if sanctioned:
score_a = score_a + 1
serving = "A"
return score_a, score_b
def sim_n_games(n, prob_a, prob_b, sanctioned=False):
# Simulates n games between teams A and B
# RETURNS number of wins for A, number of wins for B
wins_a = 0
wins_b = 0
for i in range(n):
score_a, score_b = sim_one_game(prob_a, prob_b, sanctioned)
if score_a > score_b:
wins_a = wins_a + 1
else:
wins_b = wins_b + 1
return wins_a, wins_b
def print_summary(wins_a, wins_b):
# Prints a summary of wins for each player.
n = wins_a + wins_b
print("\nGames simulated: {0}".format(n))
print("Wins for A: {0} ({1:0.1%})".format(wins_a, wins_a/n))
print("Wins for B: {0} ({1:0.1%})".format(wins_b, wins_b/n))
def main():
# main function
prob_a, prob_b, n = get_inputs()
wins_a, wins_b = sim_n_games(n, prob_a, prob_b, sanctioned=False)
print_summary(wins_a, wins_b)
wins_a, wins_b = sim_n_games(n, prob_a, prob_b, sanctioned=True)
print_summary(wins_a, wins_b)
if __name__ == '__main__':
try:
main()
except ValueError as e:
print(e)
"""If player A has a higher probability winning a serve, he/she will
win more games in first kind of volleyball game. On the contrary,
if player B has a higher probability, he/she will win more games in
second kind of volleyball game.""" |
fa413d8d3221fc761c60f4fead461ae9f41c415c | Nextc3/aulas-de-mainart | /Listas/Lista 3/q2.py | 1,156 | 4.15625 | 4 | #Crie três listas, uma lista de cada coisa a seguir:
##• frutas
#• docinhos de festa (não se esqueça de brigadeiros!!)
#• ingredientes de feijoada
#Lembre-se de salvá-las em alguma variável!
#a. Agora crie uma lista que contém essas três listas.
#Nessa lista de listas (vou chamar de listona):
#b. você consegue acessar o elemento brigadeiro?
#c. Adicione mais brigadeiros à segunda lista de listona. O que aconteceu com a lista de docinhos
#de festa?
#d. Adicione bebidas ao final da listona, mas sem criar uma lista!
frutas = ["maçã", "uva", "jaca"]
docinhos_de_festa = ["brigadeiro", "beijinho", "cajuzinho"]
ingredientes = ["fejão", "calabresa", "coentro"]
listona = [frutas, docinhos_de_festa, ingredientes]
print("Listona: ")
print(listona)
print("Imprimindo o elemento brigadeiro listona[2][0]")
print(listona[2][0])
listona[1].append("brigadeiro1")
listona[1].append("brigadeiro2")
print("Imprimindo depois de adicionar brigadeiros")
print(listona)
print(docinhos_de_festa)
listona.append("cerveja")
listona.append("refrigerante")
listona.append("água")
print("Imprimindo depois de adicionar bebidas:")
print(listona)
|
2c1a05d74485982b8b3ec9e72e788feeb9816b66 | KDiggory/pythondfe | /PYTHON/Files/Files.py | 1,213 | 3.828125 | 4 | #help(open) ##opens the help info for the inbuilt method open
openedfile = open("README.md")
print(openedfile) ## prints metadata - (open file IO type of data). Not the contents of the file!
#help(openedfile) ## will then open help for the new variable you've made - can see there is a read function in there.
## help very useful to see what you can do with the file
filecontents = openedfile.read() ## makes a variable of the contents of the file
filecontents = filecontents + "\nI'm adding some useful contents as a test" # can then add to the file, the \n adds it on a new line
filecontents = filecontents + "\nand another new line here"
print(filecontents)
## README.md is a read only file so can't save into it! Would need to copy the contents to a new file in order to save it.
#writefile = open("README.md.new","w") # this makes a new variable of the README.md file that is a new copy that is writable
writefile = open("README.md.new", "a+")
writefile.write(filecontents)
print(writefile) # prints the metadata for the file - need to read it
contentswritefile = writefile.read()
print(contentswritefile)
openedfile.close() # to close the files
writefile.close()
print("Finished") |
8c5dca2178ab6ec77ff9c863eed8eeccc099e65b | kibazohb/Leetcode-Grind | /Medium/braceExpansion/solution_02.py | 1,386 | 3.75 | 4 | from collections import defaultdict
class Solution:
def expand(self, S: str) -> List[str]:
"""
"{a,b}c{d,e}f"
Questions to ask: Will sequence of characters be in order?
can we have more than one interfering character?
can we have interfering characters at the beginning of the string?
DFS approach (i personally prefer this approach.)
When we deal with recursiom, the return function pretty much helps to
pop the current item off the stack, then it deals with the rest.
"""
graph = defaultdict(list)
access = False
inside = []
path = ''
idx = 0
self.out=[]
for x in S:
if x == "{":
access = True
elif x == ",":
continue
elif x == "}":
access = False
idx += 1
elif access:
graph[idx].append(x)
else:
graph[idx].append(x)
idx+=1
print(graph)
self.dfs(path,graph,0)
return sorted(self.out)
def dfs(self, path, graph, idx) -> None:
if len(path) == len(graph):
self.out.append(path)
return None
for char in graph[idx]:
self.dfs(path + char, graph, idx + 1)
|
2ff11413f9c77b387250dce359d712fbc426f1a3 | stephensb/devcon19python | /ListComprehension.py | 150 | 3.828125 | 4 | numbsq = []
for num in range(8):
numbsq.append(num**2)
print(numbsq)
#list comprehension
numbsq = [num**2 for num in range(8)]
print(numbsq) |
c841c9b1ad3401e995f9b8cd0662299deee35ebb | JetimLee/DI_Bootcamp | /pythonlearning/week1/listMethods2.py | 532 | 4 | 4 | basket = [1, 2, 3, 4, 5]
new_basket = ['a', 'b', 'c', 'd']
print(basket.index(2))
print(new_basket.index('a'))
# this will tell you the index of the item passed inside
print(new_basket.index('c', 0, 3))
# here you say which thing you want the index of and the indices you're searching through
print('z' in new_basket)
#like .includes in JavaScript
# will give you true/false depending on if the thing is inside of the list
print(new_basket.count('a'))
# will tell you how many occurances there are of something inside of a list
|
81f5cc170d86fd440a8c49d3cea319e5d254117a | enra64/iot-ledmatrix | /host/helpers/TextScroller.py | 3,025 | 4.03125 | 4 | from Canvas import Canvas
from CustomScript import CustomScript
from helpers.Color import Color
class TextScroller:
"""
This class is designed to help with scrolling text over the canvas. Following functions are expected to be forwarded:
* :meth:`update` to update the text position
* :meth:`draw` to draw the text. background can be cleared.
The following functions may be called to change the text:
* :meth:`set_text` change displayed text
* :meth:`set_font` change font the text is rendered in
* :meth:`set_size` change font size
* :meth:`set_color` change text color
"""
def __init__(self, canvas, text: str = None, font_path="Inconsolata.otf", font_size: int = 10):
self.current_x = 0
self.current_y = 0
self.current_color = Color(255, 255, 255)
self.canvas = canvas
self.font_path = font_path
self.font_size = font_size
self.current_text_width = None
self.rendered_text = None
self.text = text
self.re_render = text is not None
def set_text(self, text: str):
"""
Change the displayed text. Position will be reset.
:param text: the new text
"""
self.text = text
self.current_x = self.canvas.width
self.re_render = True
def set_font(self, font_path: str):
"""
Change the font used for the display.
:param font_path: path to the font file
"""
self.re_render = True
self.font_path = font_path
def set_size(self, font_size: int):
"""
Change font size
:param font_size: font size. 13 is large
"""
self.font_size = font_size
self.re_render = True
def set_color(self, color: Color):
"""
Change text color
:param color: text color
"""
self.current_color = color
def update(self):
"""
Update the font display
"""
self.current_x -= 1
if self.re_render and self.text is not None and self.font_path is not None and self.font_size is not None:
self.re_render = False
self.rendered_text = self.canvas.render_text(self.text, self.font_path, self.font_size)
# wrap around matrix borders
if self.rendered_text is not None and self.current_text_width is not None:
if self.current_x + self.current_text_width < 0:
self.current_x = self.canvas.width
def draw(self, canvas: Canvas, clear: bool = False):
"""
Draw the font pixels to the screen.
:param canvas: the canvas to be drawn to
:param clear: if True, the canvas will be cleared before drawing the font
"""
if clear:
canvas.clear()
if self.rendered_text is not None:
self.current_text_width = canvas.draw_text(self.rendered_text, int(self.current_x), int(self.current_y), self.current_color)
|
54cee7e266bf311bed11f13a4b2c0d708b8c80e6 | kenekc18/MiniProjects_ | /GuessingGame.py | 473 | 4.09375 | 4 | import random
targetNumber = random.randrange(1,10)
print(targetNumber)
while True:
guessedNumber = int(input("Enter a number between 1 and 10:"))
if guessedNumber == targetNumber:
print("Congratulations you guessed the right number")
elif guessedNumber < targetNumber:
print("The number is too low")
print("Try again")
elif guessedNumber > targetNumber:
print("The number is too high")
print("Try again")
|
744808ae5dbb38d9c6b11ab6fac9cba4c3cad781 | shalom-pwc/challenges | /Pytho Challenges/02.calculate-remainder.py | 121 | 3.890625 | 4 | # Calculate Remainder
# ----------------------------------
def remainder(num):
return num % 2
print(remainder(5))
# 1 |
90a2d82ac44bcedd78470cf744dfefb7ec4c25e0 | Aadi2001/HackerRank30DaysChallenge | /Day 2-Operators/Operators.py | 2,029 | 4.28125 | 4 | """
Task
Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal's total cost. Round the result to the nearest integer.
Example
mealcost = 100
tippercent = 20
taxpercent = 8
A tip of 15% * 100 = 15, and the taxes are 8% * 100 = 8. Print the value 123 and return from the function.
Function Description
Complete the solve function in the editor below.
solve has the following parameters:
int meal_cost: the cost of food before tip and tax
int tip_percent: the tip percentage
int tax_percent: the tax percentage
Returns The function returns nothing. Print the calculated value, rounded to the nearest integer.
Note: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result.
Input Format
There are 3 lines of numeric input:
The first line has a double, mealcost (the cost of the meal before tax and tip).
The second line has an integer, tippercent (the percentage of mealCost being added as tip).
The third line has an integer, taxpercent (the percentage of mealCost being added as tax).
Explanation
Given:
meal _cost = 12, tip_percent = 20, tax_percent = 8
Calculations:
tip = 12 and 12/100x20 = 2.4
tax = 8 and 8/100x20 = 0.96
total_cost = meal_cost +tip +tax = 12 +2.4 +0.96 = 15.36
round(total_cost) = 15
We round total_cost to the nearest integer and print the result, 15.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'solve' function below.
#
# The function accepts following parameters:
# 1. DOUBLE meal_cost
# 2. INTEGER tip_percent
# 3. INTEGER tax_percent
#
def solve(meal_cost, tip_percent, tax_percent):
# Write your code here
if __name__ == '__main__':
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
solve(meal_cost, tip_percent, tax_percent)
|
cafc9dda499d07b8103ff3922c623270038f9715 | nate-d-olson/CBBG_Rosalind_Bioinf | /ba1i_KC.py | 1,141 | 3.609375 | 4 | #!/usr/bin/python
# File created on Nov 05, 2015
__author__ = "Kenneth Cheng"
__credits__ = ["Kenneth Cheng"]
__version__ = "0.0.1-dev"
__maintainer__ = "Kenneth Cheng"
__email__ = ""
"""
Definition:
Problem Description:
Find the most frequent words with mismatches in a string.
Given: Strings Text along with integers k and d.
Return: All most frequent k-mers with up to d mismatches in Text.
"""
import sys
from rosalind_utils import readdat
from ba1g_KC import hamming_dist
from ba1k_KC import permutdna
from collections import defaultdict
# Approach 1 (dummy's approach):
def maxfreq_mm(seq, k, d):
k = int(k)
d = int(d)
seql = len(seq)
freq_dict = defaultdict(int)
for kmer in permutdna(k):
for i in xrange(seql - k + 1):
if hamming_dist(kmer, seq[i:i + k]) <= d:
freq_dict[kmer] += 1
maxfreq = max(freq_dict.values())
for kmer in freq_dict:
if freq_dict[kmer] == maxfreq:
print kmer,
def main(filename):
dat = readdat(filename)
maxfreq_mm(*dat)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename) |
c33de1d20031e544564d61ab744e00737135eaaf | ovwane/leetcode-1 | /src/HammingDistance.py | 684 | 3.859375 | 4 | '''
LeetCode: Hamming Distance
description:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Input: x = 1, y = 4
Output: 2
Example:
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
author: Ehco1996
time: 2017-11-16
'''
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
Solution().hammingDistance(100, 412)
|
6a3416ef730e94c2df91c349b10efca2fb3495e9 | nisarggurjar/PythonRevisionSession | /String.py | 534 | 3.984375 | 4 | X = 'hello to ALL'
Y = str("Welcome to Python's Class")
Z = 'Good Afternoon'
print(X[1])
print(X[-3])
a = X[-3]
print(a)
print(Y +' ' + X + ' ' + Z)
print(X*5)
# Slicing
print(Y[0:7])
print(Y[8:10])
print(Y[11:])
print(Y[:7])
print(X[::2])
print(X[::-1])
print(list(X))
print(X.split())
print(X.split('o'))
print(X.capitalize())
print(X.casefold())
print(X.index('t'))
a = "Hello, My name is {1}. i am pursuing {0}"
name = input("Enter your name")
course = input("Enter your course")
print(a.format(course,name))
|
b90577fd5cb2966a94e50950b1281ad639875a61 | mjindal585/snapbuzz | /codes/edgeenhance.py | 1,286 | 3.515625 | 4 | # import image module
from PIL import Image
from PIL import ImageFilter
from PIL import ImageDraw, ImageFont
import math
import time
import tkinter
from tkinter import filedialog
import os
root=tkinter.Tk()
root.withdraw()
def edgeenhance():
print(":: Welcome To Edge Enhancement ::")
time.sleep(0.5)
print("Select File Path")
time.sleep(1)
path = filedialog.askopenfilename(initialdir = os.getcwd(),title = "Select file",filetypes = (("png files","*.png"),("jpg files","*.jpg"),("all files","*.*"))) # Your image path
print(path)
# Open an already existing image
imageObject = Image.open(path)
# Apply edge enhancement filter
edgeEnahnced = imageObject.filter(ImageFilter.EDGE_ENHANCE)
# Apply increased edge enhancement filter
moreEdgeEnahnced = imageObject.filter(ImageFilter.EDGE_ENHANCE_MORE)
# Show original image - before applying edge enhancement filters
imageObject.show()
# Show image - after applying edge enhancement filter
edgeEnahnced.show()
# Show image - after applying increased edge enhancement filter
moreEdgeEnahnced.show()
print("Type exit to terminate")
if __name__ == '__main__' :
# Calling main function
edgeenhance()
|
1b769f895322ba26a21c8e3ec260ccacf8118d1d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2405/60641/303877.py | 3,064 | 3.625 | 4 | class BinaryTree:
def __init__(self, value):
self.father = None
self.left_node = None
self.right_node = None
self.value = value
def set_father(self, x):
self.father = x
def set_son(self, x):
if self.left_node is None:
self.left_node = x
else:
self.right_node = x
def get_depth(self, node):
result = -1
if self.value == node.value:
result = 0
else:
if self.left_node is not None:
temp = self.left_node.get_depth(node)
if temp != -1:
result = 1 + temp
if self.right_node is not None:
temp = self.right_node.get_depth(node)
if temp != -1:
result = 1 + temp
return result
def max_depth(self):
result = 1
left_depth = 0
right_depth = 0
if self.left_node is not None:
left_depth = self.left_node.max_depth()
if self.right_node is not None:
right_depth = self.right_node.max_depth()
result += max(left_depth, right_depth)
return result
def max_width(self):
result = 1
one_line_nodes = [self]
while len(one_line_nodes) != 0:
length = len(one_line_nodes)
result = max(result, length)
for i in range(0, length):
if one_line_nodes[i].left_node is not None:
one_line_nodes.append(one_line_nodes[i].left_node)
if one_line_nodes[i].right_node is not None:
one_line_nodes.append(one_line_nodes[i].right_node)
one_line_nodes = one_line_nodes[length:]
return result
if __name__ == '__main__':
n = int(input().strip())
nodes = [BinaryTree(i) for i in range(0, n + 1)]
for i in range(0, n - 1):
x, y = map(int, input().strip().split(" "))
nodes[y].set_father(nodes[x])
nodes[x].set_son(nodes[y])
tree = nodes[1]
print(tree.max_depth())
print(tree.max_width())
node_1, node_2 = map(int, input().strip().split(" "))
common_node = 0
parent_1 = node_1
parent_2 = node_2
while tree.get_depth(nodes[parent_1]) != tree.get_depth(nodes[parent_2]) or common_node == 0:
if tree.get_depth(nodes[parent_1]) > tree.get_depth(nodes[parent_2]):
parent_1 = nodes[parent_1].father.value
continue
elif tree.get_depth(nodes[parent_1]) < tree.get_depth(nodes[parent_2]):
parent_2 = nodes[parent_2].father.value
continue
if parent_1 == parent_2:
common_node = parent_1
break
else:
parent_1 = nodes[parent_1].father.value
parent_2 = nodes[parent_2].father.value
distance = (tree.get_depth(nodes[node_1]) - tree.get_depth(nodes[common_node])) * 2 + tree.get_depth(
nodes[node_2]) - tree.get_depth(nodes[
common_node])
print(distance)
|
a350a064edbc2e5fe912d76b49bf62c89e387624 | ResmyBaby/pythonPlayground | /oop/Enumarate.py | 332 | 3.75 | 4 | __author__ = 'asee2278'
list = [2,2.2,0," " ]
count = 0
for item in list :
print "index "+ str(count) +" has element ",
print item
count+=1
for index,item in enumerate(list):
if index >2 : break;
print( index , item)
lst = [2==2,2==3,4%2==0]
print all(list)
print complex(1,2)
er = complex('2+2j')
print er
|
375e539c5b4eb744be0044ae7ebc4de9f78c4663 | tonycao/CodeSnippets | /python/homework/Archive/A2/A2Answer_sean.py | 5,029 | 3.765625 | 4 | ## Assignment 2 - Analyzing water
## Author: Sean Curtis
## Collaborators: None
## Time spent (hours): N/A
## In this assignment, we're going to visualize and analyze data to answer
## meaningful questions. Some of the framework you need is in place, you
## have to fill in the gaps.
import numpy as np
import pylab as plt
# read the data
# depth: a 276 by 2 array with depth of Jordan and Falls lakes
# for each month from Jan 1985 to Dec 2007, which is 23 years.
# Data that is not available is NaN.
depth = np.loadtxt('depth.txt')
# rain: a 276x2 array with total rainfall in inches for each month
rain = np.loadtxt('rain.txt')
# hawgage: a 365x4 array of daily average river or lake height (ft) at
# Haw River, Bynum, and above & below the Jordan Lake Dam by Moncure.
# (These sites are listed upstream to downstream, but the gauges are
# not in that order.)
hawgage = np.loadtxt('hawgage.txt')
# hawrain: a 365x2 array of daily rainfall (in) measured at two
# rain gauges from 29 Aug 07 - 28 Aug 08.
hawrain = np.loadtxt('hawrain.txt')
## QUESTION 1
# 1. Plot a line graph of depths for both lakes.
plt.plot( depth )
# these show how to label the figure
plt.title('Depth of Jordan and Falls lakes') # the title of the figure
plt.ylabel('Depth (feet)') # label for the y-axis
plt.xlabel('Months starting with Jan 1985') # label for the x-axis
plt.savefig('Fig1.png') # the saved output figure
plt.close() # close this plot so it doesn't interfere later
## QUESTION 2
# 2. The targets for Jordan and Falls lakes are 216ft and 251.5ft, respectively.
# For how many months was each lake over its target?
jordanTgt = 216
fallsTgt = 251.5
targets = np.array([ jordanTgt, fallsTgt ] )
overTgt = depth > targets
overTgtCount = np.sum( overTgt, axis=0 )
print 'Months Jordan lake exceeded its target depth:', overTgtCount[0]
print 'Months Falls Lake exceeded its target depth:', overTgtCount[1]
## QUESTION 3
# 3. Plot the rain in August as a line graph over years for both lakes.
augRain = rain[ 7::12, : ]
plt.plot( augRain )
plt.title('Rain in August for Jordan and Falls lakes')
plt.savefig('Fig2.png')
plt.close()
## QUESTION 4
# 4. Compute the average height that Falls Lake is above its target
# for each month over the 23 years from 1985-2007, and display as bar
# chart with a bar for each month. Plot the line for 2007 in red on
# top of this bar chart.
monthVsYear = np.reshape( depth[ :, 1 ], (-1, 12 ) )
FallsByMonth = np.mean( monthVsYear, axis=0 )
FallsByMonth -= fallsTgt
plt.bar( np.arange(1, 13), FallsByMonth, align='center')
year2007 = depth[-12:, 1] - fallsTgt
plt.plot( np.arange(1, 13), year2007, 'r')
plt.title('Average Falls lake depth 85-07, and line for 2007')
plt.ylabel('Height above target(ft)')
plt.xlabel('Month')
plt.savefig('Fig3.png')
plt.close()
## QUESTION 5
# 5. Determine how many days had more than 1 in of precipitation at
# the two sites in hawrain, and how many days had less than 1/4 in.
grtrOne = hawrain > 1
print 'Number of days either lake had more than one inch', np.sum( np.sum( grtrOne, axis=1 ) > 0 )
qrtr = hawrain < 0.25
print 'Number of days either lake had less than 1/4 inch:', np.sum( np.sum( qrtr, axis=1 ) > 0 )
## QUESTION 6
# 6. Plot line graphs showing the cumulative amount of rain over the
# past year at both sites. Which of the two locations (1 or 2)
# received the most rain?
cumRain = np.cumsum( hawrain, 0 )
plt.plot( cumRain )
maxIndex = np.argmax(cumRain[ -1, : ])
plt.title('Cumulative Rainfall')
plt.xlabel('Days since 28Aug07')
plt.ylabel('Cumulative rainfall (in)')
plt.savefig('Fig4.png')
plt.close()
# !!! Determine which site had the most total rain -- the np.argmax function will help !!!
# !!! This print statement should print 1 or 2 (be careful there....) !!!
print 'The site with more total rain:', maxIndex + 1
## QUESTION 7
# 7. Determine the lowest height for each gauge, and create an array
# of adjusted heights by subtracting the corresponding lowest heights.
# Plot these adjust heights as a line graph.
minHeight = hawgage.min( 0 )
adjHeight = hawgage - minHeight
plt.plot( adjHeight )
plt.title('Adjusted gauge heights')
plt.xlabel('Days since 28Aug07')
plt.ylabel('Height above min (ft)')
plt.savefig('Fig5.png')
plt.close()
## QUESTION 8
# 8. Determine the maximum increase and maximum decrease in height
# from one day to the next for each of the four gauges in hawgage.
delta = np.diff( hawgage, axis=0 )
minDelta = delta.min( 0 )
maxDelta = delta.max( 0 )
print 'Maximum one-day change in height:', maxDelta
print 'Minimum one-day change in height:', minDelta
## YOUR THOUGHTS
## Type in some of your thoughts about this assignment below. Make sure that it all begins with
## pound signs (#) or your python script won't run at all. |
1ce03a3f7aab8af12c5188038d8b4d79595d7d8f | GraysonO/O-Connell_Grayson_CISC233 | /Linked List.py | 1,211 | 3.75 | 4 | class LinkedStack:
class Node:
slots = '_element', '_next'
def init (self, element, next):
self.element = element
self.next = next
def init (self):
self.head = None
self.size = 0
def len (self):
return self.size
def is_empty(self):
return self.size == 0
def push(self, e):
self.head = self.Node(e,self.head)
def top(self):
if self.isempty():
raise Empty('Stack is empty')
return self.head.element
def pop(self):
if self.isempty():
raise Empty('Stack is empty')
answer = self.head.element
self.head = self.head.next
self.size -= 1
return answer
def Sort(self,x,y):
sorted = LinkedStack
if x.head >= y.head:
sorted.head = x.head
else:
sorted.head = y.head
while x.next != None and y.next != None:
if x.next < y.next:
sorted.next = y.next
else:
sorted.next = x.next
a = LinkedStack()
a.push(3)
a.push(5)
a.push(7)
b = LinkedStack()
b.push(2)
b.push(3)
b.push(4)
c = LinkedStack
c.Sort(a,b)
print c
|
925ae08a59d1c71d5e0b630d103fbdf3a57a174a | tmu-nlp/NLPtutorial2020 | /seiichi/tutorial00/tutorial00.py | 1,045 | 4.1875 | 4 | # tutorial00
# ファイルの中の単語の頻度を数えるプログラムを作成
import sys, os
from itertools import chain
from collections import Counter
def count(path: str):
"""
Args: path, str
Return: word_cnt, dict
"""
if type(path) != str:
raise TypeError
cnt = 0
word_cnt = {}
with open(path, "r") as f:
file = f.readlines()
for line in file:
for word in line.strip().split():
if word not in word_cnt.keys():
word_cnt[word] = 0
word_cnt[word] += 1
return word_cnt
# def count(path: str):
# if type(path) != str:
# raise TypeError
# with open(path, "r") as f:
# return Counter(chain.from_iterable(map(str.split, f)))
if __name__ == "__main__":
# path = sys.argv[1]
path = "../../test/00-input.txt"
# path = "../../data/wiki-en-train.word"
word_cnt = count(path)
# 昇順に出力
for k, v in sorted(word_cnt.items()):
print("{}\t{}".format(k, v))
print(word_cnt)
|
e4b96d9ba800d8220855d881ac398615d12f1c75 | Jorgeteixeira00/CURSO-EM-V-DEO---EXERCICIOS | /Ex47.py | 165 | 3.828125 | 4 | #Exercício Python 047: Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50
for x in range(0,51,2):
print(x,end=' ') |
c22f8c4ee468d8810349e71eca8bd884c5685a99 | Ethan-O/Computational-Physics | /Assignment 5/Animation test.py | 2,040 | 3.6875 | 4 | # Planetary motion with the Euler-Cromer method
# based on Giordano and Nakanishi, "Computational Physics"
# Yongli Gao, 2/11/2006
#
# Add a plot for the Earth as the Vpython zooming has failed.
# Yongli Gao, 2/15/2017
from vpython import *
# possible values x=1, y=0, v_x=0, v_y=2pi, dt=0.002, beta=2
print ("two planet motion")
xe = 1.
ye = 0.
ve_x = 0.
ve_y = 6.28
xj = 0.
yj = 5.2
vj_x = - 2. * pi / sqrt(yj)
vj_y = 0.
dt = 0.002
# me/ms = 3.e-6, mj/ms = 9.5e-4
# me = float(raw_input("earth mass (in solar mass) -> "))
# mj = float(raw_input("jupiter mass (in solar mass) -> "))
# to visualize procession, try ve_y = 5., mj = 9.5e-2
me = 3.0e-6
mj = 9.5e-4
# plot
window_w = 400
scene1 = display(width=window_w, height=window_w)
earth = sphere(radius=0.1, color=color.green)
earth.trail = curve(color=color.cyan)
jupiter = sphere(radius=0.1, color=color.yellow)
jupiter.trail = curve(color=color.cyan)
sun = sphere(pos=vec(0.,0.,0.), radius = 0.2, color=vec(1,1,1))
# plot earth only
scene2 = display(x=window_w,width=window_w, height=window_w)
earth2 = sphere(radius=0.02, color=color.green)
earth2.trail = curve(color=color.cyan)
sun2 = sphere(pos=vec(0.,0.,0.), radius = 0.1, color=vec(1,1,1))
# x,y = position of planet
# v_x,v_y = velocity of planet
# dt = time step
while 1: # use Euler-Cromer method
rate(100)
re = sqrt(xe**2 + ye**2)
rj = sqrt(xj**2 + yj**2)
rej = sqrt((xe - xj)**2 + (ye - yj)**2)
ve_x = ve_x - 4 * pi**2 * dt * (xe / re**3 + mj * (xe - xj) / rej**3)
ve_y = ve_y - 4 * pi**2 * dt * (ye / re**3 + mj * (ye - yj) / rej**3)
vj_x = vj_x - 4 * pi**2 * dt * (xj / rj**3 + me * (xj - xe) / rej**3)
vj_y = vj_y - 4 * pi**2 * dt * (yj / rj**3 + me * (yj - ye) / rej**3)
xe = xe + ve_x * dt
ye = ye + ve_y * dt
xj = xj + vj_x * dt
yj = yj + vj_y * dt
earth.pos = vec(xe,ye,0.)
earth.trail.append(pos=earth.pos)
earth2.pos = vec(xe,ye,0.)
earth2.trail.append(pos=earth.pos)
jupiter.pos = vec(xj,yj,0.)
jupiter.trail.append(pos=jupiter.pos)
|
722925a74c58f3e2697ee41d58211f3f3a16f5d7 | sky-dream/LeetCodeProblemsStudy | /[0505][Medium][The_Maze_II]/The_Maze_II_2.py | 2,020 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# leetcode time cost : time exceeded
# leetcode memory cost : time exceeded
# Solution 2, DFS
class Solution:
def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
m,n = len(maze),len(maze[0])
Distances = [[float('inf')]*n for _ in range(m)]
Directions = [(-1,0,'u'),(0,1,'r'),(0,-1,'l'),(1,0,'d')]
# set init value
Distances[start[0]][start[1]] = 0
def isValid(x,y,maze):
if 0<=x<m and 0<=y<n and maze[x][y] == 0:
return True
else:
return False
def destinationReached(x,y,destination):
if x == destination[0] and y == destination[1]:
return True
else:
return False
def DFS(maze,start,Distances):
pop_x,pop_y = start[0],start[1]
for dx,dy,direction in Directions:
x,y,step = pop_x+dx, pop_y+dy,Distances[pop_x][pop_y] # 1st step from start is 0
# not increase step here, then no need decrease step when backtrack from below while
# if destination is a hole like 499, then while need also check [x,y] != destination
while isValid(x,y,maze) and step < Distances[x][y]:
x,y = x+dx, y+dy
step += 1
# backtrack to the point before the blocked point, try another direction
x,y = x-dx, y-dy
# update the distance of (x,y) if this path is shorter
if step < Distances[x][y]:
#print("update point",x,y,",distance to ",step,",on the direction:",direction)
Distances[x][y] = step
DFS(maze,[x,y],Distances)
DFS(maze,start,Distances)
return Distances[destination[0]][destination[1]] if Distances[destination[0]][destination[1]] != float('inf') else -1 |
b553996a64ceb9b88886a71df6329384baa1badb | fontfish/Wolf-and-Poems | /Tools/fibonacci.py | 341 | 3.796875 | 4 | # From my Fibonacci bash script, converted into Python.
smlFib = input('First number:')
bigFib = input('Second number:')
fibRep = input('Number of repeats:')
times = 1
repeat = int(fibRep) + 1
while times <= repeat:
newFib = int(smlFib) + int(bigFib)
smlFib = bigFib
bigFib = newFib
times = times + 1
print(smlFib, bigFib) |
fde27fc6f4f64d6d5170931b0d79dee13cb3eca9 | AkiraMisawa/sicp_in_python | /chap2/c2_03_width_height.py | 507 | 3.625 | 4 | import utility
def make_rectangle(width, height):
return utility.cons(width, height)
def width_rectangle(r):
return utility.car(r)
def length_rectangle(r):
return utility.cdr(r)
def perimeter_rectangle(r):
return 2 * (width_rectangle(r) + length_rectangle(r))
def area_rectangle(r):
return width_rectangle(r) * length_rectangle(r)
def main():
r = make_rectangle(4, 8)
print(perimeter_rectangle(r))
print(area_rectangle(r))
if __name__ == '__main__':
main()
|
8a78226d7d581fbe760e5a038af498e67133a38a | Czy2GitHub/Python | /python_exec/tuple/tuple.py | 605 | 3.90625 | 4 | # -*- coding:utf-8 -*-
# 元组的基本知识
# 元组中的元素不可变
# 元组的三种创建
tuple1 = ("c语言", "Java", "python", "c++")
tuple2 = ("高级语言", ("Python", "Java"), "中级语言", "汇编语言",)
tuple3 = "计算机组成原理", "计算机网络", "数据结构"
# 如果元组只有一个元素,则元组定义时需要添加一个","
tuple4 = ("Python_exec",)
# 定义了一个字符串
tuple5 = ("Python_exec")
# 可以使用type()来测试变量类型
print("tuple4的类型为:", type(tuple4))
print("tuple5的类型为:", type(tuple5))
|
7c1dc5ab4625adfd8fc344d5ffd6065208f65ffc | peterkisfaludi/Leetcode | /142_linked-list-cycle-ii.py | 667 | 3.578125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
s=head
f=head
if head is None: return None
while True:
f=f.next
if f is None: return None
if f==s: break
s=s.next
f=f.next
if f is None: return None
if f==s: break
v=set()
p=head
while p is not None:
if p in v: return p
v.add(p)
p=p.next
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.