blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
b39d713b56ad6bb9852160a2c428c383bcbf987f | Gerard1-11/PythonPractice | /FirstExercises/A4/ventaSoftware.py | 1,330 | 4.03125 | 4 | #encoding: UTF-8
#Gerardo Arturo Valderrama Quiroz
#A01374994
#Programa que recibe un número de paquetes comprados e imprimie el descuento y el total de la compra
#Funcion que calcula la cifra del descuento de los paquetes comprados
def calculardescuento(nuPaquetes):
if nuPaquetes >=0 and nuPaquetes <= 9:
descuento = 0
return descuento
elif nuPaquetes >= 10 and nuPaquetes <= 19:
descuento = (1500*.20)*nuPaquetes
return descuento
elif nuPaquetes >= 20 and nuPaquetes <= 49:
descuento = (1500*.20)*nuPaquetes
return descuento
elif nuPaquetes >= 50 and nuPaquetes <= 99:
descuento = (1500*.20)*nuPaquetes
return descuento
else:
descuento = (1500*.20)*nuPaquetes
return descuento
#Funcion que calcula el total a pagar
def calculartotal(nuPaquetes, descuento):
total = (nuPaquetes * 1500) - descuento
return total
#Funcion principal main que lee, procesa e imprime datos
def main():
nuPaquetes = int(input("Teclea el número de paquetes comprados: "))
if nuPaquetes >=0:
print("El descuento es de $%.2f" % calculardescuento(nuPaquetes))
print("El total de la compra es de $%.2f" % calculartotal(nuPaquetes,calculardescuento(nuPaquetes)))
else:
print("ERROR: El número que introdujo no es válido")
main()
|
0725195ed90726b18ff41658f27e5e8e46e14316 | franklingu/leetcode-solutions | /questions/maximum-gap/Solution.py | 1,438 | 3.859375 | 4 | """
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 109
"""
class Solution:
def maximumGap(self, nums: List[int]) -> int:
if len(nums) < 2:
return 0
elif len(nums) == 2:
return abs(nums[0] - nums[1])
mmin, mmax = min(nums), max(nums)
if mmax == mmin:
return 0
buckets = [[] for _ in range(len(nums))]
step = math.ceil((mmax - mmin) / (len(nums) - 1))
for n in nums:
bidx = (n - mmin) // step
b = buckets[bidx]
if len(b) == 0:
b.append(n)
b.append(n)
else:
b[0] = min(b[0], n)
b[1] = max(b[1], n)
prev = mmin
ret = 0
for b in buckets:
if len(b) == 0:
continue
ret = max(ret, b[0] - prev)
prev = b[1]
return ret |
820b0d77982871ba340fa7353992cc473c140716 | nervaishere/DashTeam | /python/7th_session/1list.py | 170 | 3.90625 | 4 | number = 3
things = ["string", 0, [1, 2, number], 4.56]
print(things[1])
print(things[2])
print(things[2][2])
nums = [1, 2, 3]
print(nums + [4, 5, 6])
print(nums * 3)
|
602ce1b023a134cf7c98d116ae7389e4d3fd9c71 | moheeeldin19-meet/YL1-Session4 | /animals.py | 469 | 3.65625 | 4 | class animal(object):
def __init__(self,sound,name,age,favorite_color):
self.sound=sound
self.name=name
self.age=age
self.favorite_color=favorite_color
def eat (self,food):
print("yummy!! "+ self.name + " is eating " + food)
def description(self):
print(self.name + " is " + self.age + "years and loves the color " + self.favorite_color)
def make_sound(self,x):
print(self.sound *x)
|
6b648a52b3fa530c66ee17893c75933ab23cc460 | catalinc/advent-of-code-2017 | /day_2.py | 2,099 | 3.625 | 4 | # Solution to http://adventofcode.com/2017/day/2
import unittest
import sys
def matrix_checksum(matrix, row_fn):
total = 0
for row in matrix:
total += row_fn(row)
return total
def min_max_diff(row):
if not row:
return 0
min_val = row[0]
max_val = row[0]
for n in row:
if n < min_val:
min_val = n
elif n > max_val:
max_val = n
return max_val - min_val
def even_divisible(row):
for i in range(len(row) - 1):
for j in range(i + 1, len(row)):
a = row[i]
b = row[j]
if a < b:
a, b = b, a
q, r = divmod(a, b)
if r == 0:
return q
return 0
def parse_matrix_from_file(filename):
matrix = []
with open(filename, 'r') as input_file:
for line in input_file:
row = [int(t) for t in line.split()]
matrix.append(row)
return matrix
class Test(unittest.TestCase):
def test_min_max_diff(self):
test_data = [([5, 1, 9, 5], 8), ([7, 5, 3], 4)]
for row, expected in test_data:
self.assertEqual(expected, min_max_diff(row))
def test_even_divisible(self):
test_data = [([5, 9, 2, 8], 4), ([9, 4, 7, 3], 3), ([3, 8, 6, 5], 2)]
for row, expected in test_data:
self.assertEqual(expected, even_divisible(row))
def test_matrix_checksum(self):
test_data = [[5, 1, 9, 5], [7, 5, 3], [2, 4, 6, 8]]
self.assertEqual(18, matrix_checksum(test_data, row_fn=min_max_diff))
test_data = [[5, 9, 2, 8], [9, 4, 7, 3], [3, 8, 6, 5]]
self.assertEqual(9, matrix_checksum(test_data, row_fn=even_divisible))
def main():
if len(sys.argv) >= 2:
for name in sys.argv[1:]:
matrix = parse_matrix_from_file(name)
for fn in [min_max_diff, even_divisible]:
print('Checksum.%s for %s is %d' %
(fn.__name__, name, matrix_checksum(matrix, row_fn=fn)))
else:
unittest.main()
if __name__ == '__main__':
main()
|
c19b2a7f39422c2ceaa66474c5f3ce4d583ae6f0 | rebecadiaconu/fmi | /ml/lab/algoritmi/normalizare.py | 855 | 3.53125 | 4 | import numpy as np
from numpy.linalg import norm
import sklearn.preprocessing as preprocessing
a = np.array([10, 20, 30])
print(a)
l = norm(a, 1) # 1 pt L1, 2 pt L2
print(l)
result = np.divide(a, l)
print(result)
print("\n------------\n")
def normalize(train_data, type=None):
if type is None:
return train_data
elif type == 'standard':
scaler = preprocessing.StandardScaler()
scaler.fit(train_data)
return scaler.transform(train_data)
elif type == 'min-max':
scaler = preprocessing.MinMaxScaler()
scaler.fit(train_data)
return scaler.transform(train_data)
elif type == 'l1' or type == 'l2':
scaler = preprocessing.Normalizer(type)
scaler.fit(train_data)
return scaler.transform(train_data)
data = [[4,2,3,-1]]
print(normalize(data, 'standard')) |
021cf8f6ae2a04bc6cffbe8109ae9f14a250c65c | SarcoImp682/Simple-Tic-Tac-Toe | /Topics/Split and join/What day is it/main.py | 67 | 3.71875 | 4 | date = input().split('-')
for x in range(0, 3):
print(date[x])
|
62248f89b65103b8783414a65300d7ef718dab97 | Catalina-AR/python-2020 | /python_stack/python/fundamentals/Funciones_intermedias2.py | 3,773 | 3.890625 | 4 | #Actualiza los valores en diccionarios y listas
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
#1. Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora debería ser [[5,2,3], [15,8,9]].
x = [ [5,2,3], [10,8,9] ]
x[1][0] = 15
print(x)
#2.Cambia el apellido del primer alumno de 'Jordan' a 'Bryant'
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
students[0]['first_name'] = 'Bryant'
print(students)
#3.En el directorio sports_directory, cambia 'Messi' a 'Andres'
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
sports_directory['soccer'][0] = 'Andres'
print(sports_directory)
#4.Camba el valor 20 en z a 30
z = [ {'x': 10, 'y': 20} ]
z[0]['y']=30
print(z)
#2.Itera a través de una lista de diccionarios
#Crea una función iterateDictionary(some_list) que, dada una lista de diccionarios,
# la función recorra cada diccionario de la lista e imprime cada clave y el valor asociado.
# Por ejemplo, dada la siguiente lista:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
#iterateDictionary(students)
# La salida debería ser: (Está bien si cada clave y valor quedan en dos líneas separadas)
# Bonus: Hacer que aparezcan exactamente así!
#first_name - Michael, last_name - Jordan
#first_name - John, last_name - Rosales
#first_name - Mark, last_name - Guillen
#first_name - KB, last_name - Tonel
#resp
def iterateDictionary(students):
for i in students:
print(i)
iterateDictionary(students)
def iterateDictionary_somelist(students):
for i in students:
print("first_name -", i["first_name"]+", " "last_name -", i["last_name"],)
iterateDictionary_somelist(students)
#3.Obtén valores de una lista de diccionarios
#Crea una función iterateDictionary2(key_name, some_list)
# que, dada una lista de diccionarios y un nombre de clave, la función imprima el valor almacenado en esa clave para cada diccionario.
# Por ejemplo, iterateDictionary2 ('first_name', students) debería generar:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def iterateDictionary_2(key, dict):
for i in dict:
print(i[key])
iterateDictionary_2('first_name', students)
def iterateDictionary_2(key, dict):
for i in dict:
print(i[key])
iterateDictionary_2('last_name', students)
#4.Itera a través de un diccionario con valores de listas
#Crea una función printInfo(some_dict)que, dado un diccionario cuyos valores son todas listas,
# imprima el nombre de cada clave junto con el tamaño de su lista,
# y luego imprima los valores asociados dentro de la lista de cada clave. Por ejemplo:
dojo = {
'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'],
'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon']
}
def print_info(some_dict):
for each_key in some_dict:
print(len(some_dict[each_key]), each_key.upper())
for each_list_value in some_dict[each_key]:
print(each_list_value)
print("")
print_info(dojo) |
e756cc71577b3064538656ba465e45b27a445dbd | Amir324/itc_bootcamp_winter2020 | /Python/200228154626_List 2.py | 3,655 | 4.125 | 4 | """ This program has been adapted for use by GVAHIM
- the main revisions regard pep8 compliance and use of variable names
Copyright 2010 Google Inc.
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
Google's Python Class
http://code.google.com/edu/languages/google-python-class/
Additional basic list exercises """
def remove_adjacent(nums):
'''
D. Given a list of numbers, return a list where
all adjacent == elements have been reduced to a single element,
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
modify the passed in list.
:param nums:
:return: list without duplicates
'''
i = 1
while i < len(nums):
if nums[i] == nums[i-1]:
nums.pop(i)
i -= 1
i += 1
return nums
def linear_merge(sorted1, sorted2):
'''
E. Given two lists sorted in increasing order, create and return a merged
list of all the elements in sorted order. You may modify the passed in lists.
Ideally, the solution should work in "linear" time, making a single
pass of both lists.
:param sorted1:
:param sorted2:
:return: merge sortet list
'''
sorted_list = []
sorted1_index = sorted2_index = 0
# We use the list lengths often, so its handy to make variables
sorted1_length, sorted2_length = len(sorted1), len(sorted2)
for _ in range(sorted1_length + sorted2_length):
if sorted1_index < sorted1_length and sorted2_index < sorted2_length:
# We check which value from the start of each list is smaller
# If the item at the beginning of the left list is smaller, add it
# to the sorted list
if sorted1[sorted1_index] <= sorted2[sorted2_index]:
sorted_list.append(sorted1[sorted1_index])
sorted1_index += 1
# If the item at the beginning of the right list is smaller, add it
# to the sorted list
else:
sorted_list.append(sorted2[sorted2_index])
sorted2_index += 1
# If we've reached the end of the of the left list, add the elements
# from the right list
elif sorted1_index == sorted1_length:
sorted_list.append(sorted2[sorted2_index])
sorted2_index += 1
# If we've reached the end of the of the right list, add the elements
# from the left list
elif sorted2_index == sorted2_length:
sorted_list.append(sorted1[sorted1_index])
sorted1_index += 1
return sorted_list
def test(got, expected):
""" simple test() function used in main() to print
what each function returns vs. what it's supposed to return. """
if got == expected:
prefix = " OK "
else:
prefix = " X "
print("%s got: %s expected: %s" % (prefix, repr(got), repr(expected)))
def main():
""" main() calls the above functions with interesting inputs,
using test() to check if each result is correct or not. """
print("\nremove_adjacent")
test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])
print("\nlinear_merge")
test(linear_merge(["aa", "xx", "zz"], ["bb", "cc"]), ["aa", "bb", "cc", "xx", "zz"])
test(linear_merge(["aa", "xx"], ["bb", "cc", "zz"]), ["aa", "bb", "cc", "xx", "zz"])
test(linear_merge(["aa", "aa"], ["aa", "bb", "bb"]), ["aa", "aa", "aa", "bb", "bb"])
if __name__ == "__main__":
main()
|
0c14009118cfedeeb9c1206c941f3dc3131ff112 | AnelaK/PrimePartitions | /PrimePartitions.py | 1,409 | 3.828125 | 4 | import sys, math
def sieveOfEratosthenes(a, b):
#returns list of all primes between a and b inclusive using the method Sieve of Eratosthenes
primes =[True for i in range(b+1)]
primes[0] = False
primes[1] = False
length = int(math.sqrt(b))
for i in range(length + 1):
if (primes[i] == True):
for j in range(i ** 2, b + 1, i):
primes[j] = False
result_primes = []
for p in range(a, b + 1, 1):
if (primes[p] == True):
result_primes.append(p);
return result_primes
def prime_partitions (n, k, solution=[]):
#returns prime partitions of n with all the primes being greater than k
if (n == 0):
#if we reach 0 after recursive calls that means we have found primes that when summed up give the n
solution = list(map(str, solution))
print(' + '.join(solution))
elif (n > k):
#recursive calls
for prime in sieveOfEratosthenes(k + 1, n):
prime_partitions(n-prime, prime, solution + [prime])
print("Prime Partitions - Python Version \n")
while True:
try:
n = int(input("Enter a number for which you want prime partitions. To exit at any moment please enter any non-number character! "))
prime_partitions(n, 1)
except:
print("You entered non-number. Goodbye!")
sys.exit() |
28728197681c0b0e63c854a9862a711d0086ed5b | 316513979/thc | /Clases/Programas/recursividad.py | 718 | 3.8125 | 4 | # -*- coding: utf-8 -*-
def fib(n):
""" Calcula el nesimo término
de la sucesión de fibonacci con n natural
"""
if n>2:
return fib(n-1)+fib(n-2)
else:
return 1
print fib(1)
print fib(2)
print fib(5)
print fib(10)
def gauss(n):
if 1<n:
return gauss(n-1)+n
else:
return 1
# Mi versión:
def printr (L):
A=L
if 1<len(A):
print A[0],
A.pop(0)
printr (A)
else:
print A[0],
# Las versiones del profesor:
def printr1(L):
if L:
print L[0],
printr(L[1:])
else:
None
def printr2(L):
if len(L)>1:
print L[0],
printr(L[1:])
else:
None
|
959cba0cb76a2ee5871015ec5acbf280183170a6 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4446/codes/1596_1016.py | 345 | 3.515625 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
ladoa=float(input("comprimento do lado a:"))
ladob=float(input("comprimento do lado b:"))
ladoc=float(input("comprimento do lado c:"))
semip=(ladoa + ladob + lado) |
ccb2a7c0e19b3cee1a6508c55da7aa14629e579e | SushmaBR/FirstPython | /MinutesToYearsConversion.py | 185 | 4.0625 | 4 | min=float(input("Enter the minutes"))
hrs=min/60
days=hrs/24
years=days/365.25
yrs=min/60/24/365.25
print("hrs:",hrs)
print("days:",days)
print("years:",years)
print("yrs:",yrs) |
1b873ff1371b2d1f9378a401389a4a0f4b0b67be | pseudonative/ultrapython3 | /PythonScripts/find_greater_number.py | 225 | 4.03125 | 4 | a=eval(input("Enter your first number: "))
b=eval(input("Enter your second number: "))
if a>b:
print(f'{a} is greater than {b}')
elif a<b:
print(f'{b} is greater than {a}')
else:
print(f'{a} and {b} are equal')
|
bdddbda29cbcf377bbb1fed70ae006f0f629ef92 | Aigggerim/web_development | /function/a5.py | 251 | 3.609375 | 4 | def min(a, b, c, d):
if a > b:
A = b
else:
A = a
if c > d:
B = d
else:
B = c
if A > B:
return B
return A
a = input().split(" ")
print(min(int(a[0]), int(a[1]), int(a[2]), int(a[3]))) |
a8129ec8eada7c3cb0ea6091c7e33f35d87927d2 | mhoogveld/AoC_2016 | /aoc-03.py | 2,253 | 3.796875 | 4 | #!/usr/bin/python
import re
__author__ = "[email protected]"
class AoC_03:
def __init__(self):
pass
def run(self):
triangle_input_file = "input-03"
h_triangle_count = self.horizontal_triangle_count(triangle_input_file)
v_triangle_count = self.vertical_triangle_count(triangle_input_file)
print("Number of possible horizontal triangles: {}".format(h_triangle_count))
print("Number of possible vertical triangles: {}".format(v_triangle_count))
def horizontal_triangle_count(self, triangle_input_file):
triangle_count = 0
with open(triangle_input_file, 'r', encoding='utf-8') as infile:
for line in infile:
sides_match = re.match("[^\d]*(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]*", line)
if sides_match:
triangle_def = [sides_match.group(1), sides_match.group(2), sides_match.group(3)]
if self.is_triangle(triangle_def):
triangle_count += 1
return triangle_count
def vertical_triangle_count(self, triangle_input_file):
triangle_count = 0
triangle_defs = [[], [], []]
with open(triangle_input_file, 'r', encoding='utf-8') as infile:
for line in infile:
sides_match = re.match("[^\d]*(\d+)[^\d]+(\d+)[^\d]+(\d+)[^\d]*", line)
if sides_match:
triangle_defs[0].append(sides_match.group(1))
triangle_defs[1].append(sides_match.group(2))
triangle_defs[2].append(sides_match.group(3))
if len(triangle_defs[0]) == 3:
for triangle_def in triangle_defs:
if self.is_triangle(triangle_def):
triangle_count += 1
triangle_defs = [[], [], []]
return triangle_count
def is_triangle(self, sides):
if not len(sides) == 3:
return False
try:
sides = list(map(int, sides))
sides.sort()
return sides[0] + sides[1] > sides[2]
except ValueError:
return False
if __name__ == "__main__":
solver = AoC_03()
solver.run()
exit(0)
|
fc080076086e75990adddb88957763106e19d4ff | GenericMappingTools/pygmt | /examples/tutorials/basics/regions.py | 7,095 | 3.828125 | 4 | """
Setting the region
==================
Many of the plotting methods take the ``region`` parameter, which sets the
area that will be shown in the figure. This tutorial covers the different types
of inputs that it can accept.
"""
import pygmt
###############################################################################
# Coordinates
# -----------
#
# A string of coordinates can be passed to ``region``, in the form of
# *xmin*/*xmax*/*ymin*/*ymax*.
fig = pygmt.Figure()
fig.coast(
# Set the x-range from 10E to 20E and the y-range to 35N to 45N
region="10/20/35/45",
# Set projection to Mercator, and the figure size to 15 centimeters
projection="M15c",
# Set the color of the land to light gray
land="lightgray",
# Set the color of the water to white
water="white",
# Display the national borders and set the pen thickness to 0.5p
borders="1/0.5p",
# Display the shorelines and set the pen thickness to 0.5p
shorelines="1/0.5p",
# Set the frame to display annotations and gridlines
frame="ag",
)
fig.show()
###############################################################################
#
# The coordinates can be passed to ``region`` as a list, in the form of
# [*xmin*, *xmax*, *ymin*, *ymax*].
fig = pygmt.Figure()
fig.coast(
# Set the x-range from 10E to 20E and the y-range to 35N to 45N
region=[10, 20, 35, 45],
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# Instead of passing axes minima and maxima, the coordinates can be passed for
# the bottom-left and top-right corners. The string format takes the
# coordinates for the bottom-left and top-right coordinates. To specify corner
# coordinates, append **+r** at the end of the ``region`` string.
fig = pygmt.Figure()
fig.coast(
# Set the bottom-left corner as 10E, 35N and the top-right corner as
# 20E, 45N
region="10/35/20/45+r",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
# Global regions
# --------------
#
# In addition to passing coordinates, the argument **d** can be passed to set
# the region to the entire globe. The range is 180W to 180E (-180, 180) and 90S
# to 90N (-90 to 90). With no parameters set for the projection, the figure
# defaults to be centered at the mid-point of both x- and y-axes. Using
# **d**\ , the figure is centered at (0, 0), or the intersection of the equator
# and prime meridian.
fig = pygmt.Figure()
fig.coast(
region="d",
projection="Cyl_stere/12c",
land="darkgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# The argument **g** can be passed, which encompasses the entire globe. The
# range is 0E to 360E (0, 360) and 90S to 90N (-90 to 90). With no parameters
# set for the projection, the figure is centered at (180, 0), or the
# intersection of the equator and International Date Line.
fig = pygmt.Figure()
fig.coast(
region="g",
projection="Cyl_stere/12c",
land="darkgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
# ISO code
# --------
#
# The ``region`` can be set to include a specific area specified by the
# two-character ISO 3166-1 alpha-2 convention
# (for further information: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).
fig = pygmt.Figure()
fig.coast(
# Set the figure region to encompass Japan with the ISO code "JP"
region="JP",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# The area encompassed by the ISO code can be expanded by appending
# **+r**\ *increment* to the ISO code. The *increment* unit is in degrees, and
# if only one value is added it expands the range of the region in all
# directions. Using **+r** expands the final region boundaries to be multiples
# of *increment* .
fig = pygmt.Figure()
fig.coast(
# Expand the region boundaries to be multiples of 3 degrees in all
# directions
region="JP+r3",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# Instead of expanding the range of the plot uniformly in all directions, two
# values can be passed to expand differently on each axis. The format is
# *xinc*/*yinc*.
fig = pygmt.Figure()
fig.coast(
# Expand the region boundaries to be multiples of 3 degrees on the x-axis
# and 5 degrees on the y-axis.
region="JP+r3/5",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# Instead of expanding the range of the plot uniformly in all directions, four
# values can be passed to expand differently in each direction.
# The format is *winc*/*einc*/*sinc*/*ninc*, which expands on the west,
# east, south, and north axes.
fig = pygmt.Figure()
fig.coast(
# Expand the region boundaries to be multiples of 3 degrees to the west, 5
# degrees to the east, 7 degrees to the south, and 9 degrees to the north.
region="JP+r3/5/7/9",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# The ``region`` increment can be appended with **+R**, which adds the
# increment without rounding.
fig = pygmt.Figure()
fig.coast(
# Expand the region setting outside the range of Japan by 3 degrees in all
# directions, without rounding to the nearest increment.
region="JP+R3",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
###############################################################################
#
# The ``region`` increment can be appended with **+e**, which is like **+r**
# and expands the final region boundaries to be multiples of *increment*.
# However, it ensures that the bounding box extends by at least 0.25 times the
# increment.
fig = pygmt.Figure()
fig.coast(
# Expand the region boundaries to be multiples of 3 degrees in all
# directions
region="JP+e3",
projection="M12c",
land="lightgray",
water="white",
borders="1/0.5p",
shorelines="1/0.5p",
frame="ag",
)
fig.show()
|
31abf94f557d3d7ac348e859e26b8fc845c76b5c | joudkh/Programming-Languages | /Lecture 10/Lecture 10 (Classes).py | 2,654 | 4.03125 | 4 |
# construtor
################################################
# you cannot define multiple constructors
class MyClass:
def __init__(self):
self.value=123
# def __init__(self,thing):
# self.value=thing
def set(self,value):
self.value=value
def display(self):
print(self.value)
y=MyClass()
y.display()
y.set(4)
y.display()
# one constructor
################################################
class MyClass:
def __init__(self,thing=0):
self.value=thing
def set(self,value):
self.value=value
def display(self):
print(self.value)
y=MyClass()
y.display()
y.set(4)
y.display()
y.value
################################################
################################################
# static variable
################################################
class C:
counter = 0
def __init__(self):
self.counter += 1
def show(self):
print(self.counter)
x = C()
x.show()
y = C()
y.show()
################################################
class C:
counter = 0
def __init__(self):
C.counter += 1
def show(self):
print(C.counter)
x = C()
x.show()
y = C()
y.show()
################################################
################################################
################################################
class C:
counter = 0
def __init__(self):
C.counter += 1
def __del__(self):
C.counter -= 1
x = C(); print("Number of instances: : " + str(C.counter))
y = C(); print("Number of instances: : " + str(C.counter))
del x; print("Number of instances: : " + str(C.counter))
del y; print("Number of instances: : " + str(C.counter))
################################################
################################################
# inheritance
################################################
class A:
def __init__(self, data=0):
self.data = data
def display(self):
print (self.data)
class B(A):
def square(self):
self.data = self.data * self.data
o = B(5)
o.square()
o.display()
################################################
################################################
# Multiple Inheritance
################################################
class A:
def A(self):
print("I am A")
class B:
def A(self):
print("I am a")
def B(self):
print("I am B")
class C(B,A):
def C(self):
print("I am C")
c=C()
c.A()
c.B()
c.C()
################################################
################################################
|
b635fa6009e093121e45a5d5d2ec1fe998f088ee | qiaosiyi/oj | /test/python/common/strStr.py | 1,363 | 3.65625 | 4 | class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
n = len(needle)
m = len(haystack)
if n == 0: return 0
if n > m: return -1
i = 0
j = 0
flag = 0
flag2= 0
for k in range(m):
if haystack[i] == needle[j]:
if j == n - 1:
return i - n + 1
i = i + 1
j = j + 1
flag = 1
if flag: flag2 = 1
else :
if flag2:
flag2 = 0
i = i - 1
elif flag:
flag = 0
i = i + 1
else:
i = i + 1
j = 0
return -1
|
a167346c514c6865854904e59a3fa61ae258c672 | abloskas/Flask_projects | /python_class/funWithfunctions.py | 1,045 | 4.21875 | 4 | def odd_even():
for i in range(1,2001):
if i%2 == 0:
print 'number is {}. this is an even number.'.format(i)
else:
print 'number is {}. this is an odd number.'.format(i)
odd_even()
# Number is 1. This is an odd number.
# Number is 2. This is an even number.
# Number is 3. This is an odd number.
# ...
# Number is 2000. This is an even number.
def multiply(list,num):
for i in range(len(list)):
list[i] = list[i]*num
print list
multiply([2,4,10,16],5)
def layered_multiples(list, num):
newList = []
for i in range(len(list)):
list[i] = list[i]*num
newList2 = []
for x in range(0, list[i]):
newList2.append(1)
newList.append(newList2)
print newList
layered_multiples([2,4,5],3)
# def layered_multiples(arr):
# # your code here
# return new_array
# x = layered_multiples(multiply([2,4,5],3))
# print x
# # output
# >>>[[1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
|
93cf7fa83d5278ab5ebb9b4fd41286c8144c6712 | clui951/python-miscellaneous | /329_longest_increasing_path_matrix/329_longest_increasing_path_matrix.py | 2,496 | 3.6875 | 4 | class Solution:
# DFS from each coordinate looking for increasing path, while utilizing DP
# O(N * M), DFS will visit each coordinate once, bc DP saves revisiting node and no way to go backwards on path
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
# given a coordinate, return whether or not it is a valid place in the matrix
def in_matrix(i,j):
if i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix[0]):
return True
# given a coordinate, return all cardinal adjacent coordinates where the value is greater than the given coordinate's
CARDINAL_DIRS = [[0,-1], [1,0], [0,1], [-1,0]]
def get_next_increasing_spaces(i,j):
increasing_spaces = []
for c_dirs in CARDINAL_DIRS:
poss_i, poss_j = i + c_dirs[0], j + c_dirs[1]
if in_matrix(poss_i, poss_j):
if matrix[poss_i][poss_j] > matrix[i][j]:
increasing_spaces.append([poss_i, poss_j])
return increasing_spaces
# given a coordinate, does recursive DFS through increasing spaces to return the max path ending on the coordinate
# also utilizes DP to prevent recomputation of coordinates
dp_longest_path_from = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]
def do_dp(i,j):
# already visited
if dp_longest_path_from[i][j] != 0:
return dp_longest_path_from[i][j]
# check all increasing directions
max_len = 1
for space in get_next_increasing_spaces(i,j):
poss_len = 1 + do_dp(space[0], space[1])
max_len = max(max_len, poss_len)
dp_longest_path_from[i][j] = max_len
return max_len
# run DP DFS from each coordinate and track max
longestLength = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
longestLength = max(longestLength, do_dp(i,j))
return longestLength
if __name__ == "__main__":
print("=== longestIncreasingPath ===")
s = Solution()
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
assert s.longestIncreasingPath(nums) == 4
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
assert s.longestIncreasingPath(nums) == 4
print("=== done! ===") |
8e3ae694cbd6a9d9ebc59f0b3d631f210ed61d4e | Checkmate50/dynkin_diagrams | /src/diagram_manager.py | 9,379 | 3.90625 | 4 | def ddiagram(letter, number=-1):
"""
Given a dynkin diagram letter and positive number
Or the letter and number as a single string
Generates the string associated with that diagram
Returns "invalid graph" if the input did not describe a possible graph
STYLE:
o denotes a vertex
- denotes a single edge
= denotes a double edge
~ denotes a triple edge
< and > denote directions of double and triple edges
| replaces o to denote a branch
:param letter:
:param number:
:return:
"""
letter = str(letter).lower()
number = int(number)
if number == -1:
number = int(letter[1:])
letter = letter[0]
if letter not in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
raise ValueError("invalid graph")
if number <= 0:
raise ValueError("invalid graph")
if letter == "e" and (number > 8 or number < 3):
raise ValueError("invalid graph")
if letter == "f" and number != 4:
raise ValueError("invalid graph")
if letter == "g" and number != 2:
raise ValueError("invalid graph")
if number == 1:
return "o"
if letter == "a":
return ("o-"*number)[:-1]
if letter == "b":
return ("o-"*(number-1))[:-1]+"=>o"
if letter == "c":
return ("o-"*(number-1))[:-1]+"<=o"
if letter == "d":
if number == 2:
return "o\no"
if number == 3:
return "|-o"
return ("o-"*(number-3))[:-1]+"-|-o"
if letter == "e":
if number == 3:
return "o-o\no"
if number == 4:
return "o-o-o-o"
if number == 5:
return "o-o-|-o"
return ("o-"*(number-4))[:-1] + "-|-o-o"
if letter == "f":
return "o-o=>o-o"
return "o<~o"
def cross(diagrams):
"""
Given a list of tuples (letter, number) or strings
Returns the string representation of crossing these diagrams
Note that newlines deliminate new diagrams
:param diagrams:
:return:
"""
s = ""
for diagram in diagrams:
if isinstance(diagram, tuple):
s += ddiagram(*diagram) + "\n"
else:
s += ddiagram(diagram) + "\n"
return s.strip()
def cartan_matrix(diagrams):
"""
Given a string representation of a dynkin diagram
Or a list of string representations of dynkin diagrams
Returns the associated cartan matrix as a 2-dimensional array
Raises a value exception if the given string includes invalid characters
:param diagrams:
:return:
"""
if isinstance(diagrams, list):
diagrams = "\n".join(list(map(str, diagrams)))
else:
diagrams = str(diagrams)
size = diagrams.count("o") + 2 * diagrams.count("|")
if size == 0:
raise ValueError("Invalid String " + diagrams)
cartan = [[2 if i == j else 0 for i in range(size)] for j in range(size)]
count = 0
for diagram in diagrams.split("\n"):
allowed = {"o", "-", "=", "~", ">", "<", "|"}
left = False
skip = False
for c in diagram:
if c not in allowed:
raise ValueError("Invalid String:\n" + diagram)
if c == "-":
count += 1
if skip:
cartan[count - 2][count] = cartan[count][count - 2] = -1
else:
cartan[count - 1][count] = cartan[count][count - 1] = -1
skip = False
elif c == "=" or c == "~":
value = -2 if c == "=" else -3
count += 1
cartan[count - 1][count] = cartan[count][count - 1] = -1
if left:
cartan[count][count - 1] = value
else:
cartan[count - 1][count] = value
left = False
elif c == "<":
left = True
elif c == "|":
count += 1
skip = True
cartan[count - 1][count] = cartan[count][count - 1] = -1
count += 1
return cartan
def cartan_diagram(cartan):
"""
Given a cartan matrix as a 2-dimensional array
Returns the string representation of the associated dynkin diagram(s)
If there are multiple diagrams, they are delimited with newlines
Raises a ValueError of the given matrix is not a valid cartan matrix
:param cartan:
:return:
"""
allowed_values = [-1, -2, -3]
# lines is an array of arrays of tuples indicating what each point is connected to
# That is, lines[i] = [(point, count)...], count is the number of lines from a to b (sign indicates direction)
points = [[] for _ in range(len(cartan))]
# Assemble the lines array by recording each i,j value
# Note that we check the requirements of dynkin diagrams in this construction
for i in range(len(cartan)):
if len(cartan[i]) != len(cartan):
raise ValueError("Matrix must be square")
for j in range(len(cartan[i])):
if i == j:
if cartan[i][j] != 2:
raise ValueError("Given matrix does not have a 2 (required) at (" + str(i) + ", " + str(j) + ")")
continue
if cartan[i][j] == 0:
continue
if cartan[i][j] not in allowed_values:
raise ValueError("Given matrix does not have a value of -1, -2, or -3\
at (" + str(i) + ", " + str(j) + ")")
if cartan[j][i] == 0:
raise ValueError("The line from " + str(i) + " to " + str(j) + " is not reciprocated")
points[i].append((j, cartan[i][j]))
if sum(map(lambda x : x[1], points[i])) <= -4:
ValueError("Point " + str(i) + " has more than 3 lines extending from it")
to_return = ""
# Construct the diagrams based on the line relationships found above
while True:
# Keep running through our list of points until we run out of points (have constructed all the diagrams)
no_points = True
for point in points:
if point != 0:
no_points = False
break
if no_points:
return to_return.strip()
diagram_points = []
# Find an endpoint
for i in range(len(points)):
if points[i] == 0:
continue
if len(points[i]) == 1 or len(points[i]) == 0:
diagram_points.append(i)
break
if len(diagram_points) == 0:
raise ValueError("No endpoint found (most likely there is a cycle) in the given matrix")
diagram = "o"
# Else we have a trivial case
if len(points[diagram_points[0]]) != 0:
# Build the diagram, starting with the found endpoint
current_index = points[diagram_points[0]][0][0]
current_point = points[current_index]
size1 = points[diagram_points[0]][0][1]
size2 = __get_size__(current_point, diagram_points[0])
diagram_points.append(current_index)
current_point = current_point.copy()
diagram += __gen_connector__(size1, size2)
current_point.remove((diagram_points[0], size2))
while len(current_point) != 0:
# Branch case
next_index = current_point[0][0]
next_point = points[next_index]
size1 = current_point[0][1]
if len(current_point) == 1:
diagram += "o"
else:
# Branch case
diagram += "|"
if len(next_point) == 1:
diagram_points.append(next_index)
next_index = current_point[1][0]
next_point = points[next_index]
size1 = current_point[1][1]
elif len(points[current_point[1][0]]) > 1:
raise ValueError("This matrix gives an extending branch")
size2 = __get_size__(next_point, current_index)
diagram_points.append(next_index)
diagram += __gen_connector__(size1, size2)
current_point = next_point.copy()
current_point.remove((current_index, size2))
current_index = next_index
to_return += diagram + ("\n" if diagram == "o" else "o\n")
# Remove points we've already used
for index in diagram_points:
points[index] = 0
def __get_size__(point, index):
"""
Helper function for cartan_diagram
Given a point 'point' and an index
Returns the inner product from 'point' to that index
:param arr:
:param index:
:return:
"""
for line in point:
if line[0] == index:
return line[1]
def __gen_connector__(size1, size2):
"""
Helper function for cartan_diagram
Given the inner product size between the points 'point1' and 'point2'
Returns the diagram string representing this connection in a dynkin diagram
:param point1:
:param point2:
:return:
"""
lines = size1 * size2
if lines == 1:
return "-"
connector = "=" if lines == 2 else "~"
if size1 < size2:
return connector + ">"
return "<" + connector
|
ab37817dcf5890c695389c0333faed5d225a6776 | tangteresa/SnakeGame | /Board.py | 947 | 3.703125 | 4 | import pygame
class Board(pygame.sprite.Sprite):
def __init__(self, screenWidth, screenHeight, squareSize):
super(Board, self).__init__()
self.surf = pygame.Surface((screenWidth, screenHeight))
# size[number of rows, number of columns]
size = [screenWidth//squareSize, screenHeight//squareSize]
self.color(size, squareSize)
"""Colors the tiles of the board in checkerboard style"""
def color(self, size, squareSize):
for row in range(size[0]):
for col in range(size[1]):
# green fill
if (row + col) % 2 == 0:
pygame.draw.rect(self.surf, (63, 252, 113), (row*squareSize, col*squareSize, squareSize, squareSize))
# blue fill
else:
pygame.draw.rect(self.surf, (63, 135, 252), (row * squareSize, col * squareSize, squareSize, squareSize))
|
d9ea8870d906fb16fe86c17840b78c1b497f55f7 | Levber/python-base | /base/001if循环.py | 1,237 | 4.0625 | 4 | '''
猜拳游戏案例
1.出拳
电脑:固定 1,剪刀;随机2
2.判断输赢
1.玩家获胜
2.平局
3.电脑获胜
'''
# 电脑随机出拳
import random
player = int(input("请输入数字代表出拳:0-石头,1-剪刀,2-布"))
computer = random.randint(0, 2)
print(computer)
if ((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or (
(player == 2) and (computer == 0)): # 分析玩家获胜的情况有哪些
print("玩家获胜!!")
elif player == computer:
print("平局!!")
else:
print("电脑获胜!!!")
age = int(input('请输入你的年龄:'))
if age >= 18:
print('your age is', age)
print('you are adult!!')
else:
print('your age is', age)
print('teenager')
'''
身体质量指数bmi=体重/身高的平方
1.体重过轻:bmi<18.5
2.正常值范围:18.5≤bmi<24
3.偏重:bmi≥24
'''
h = float(input("请输入你的身高:"))
w = float(input("请输入你的体重:"))
bmi = w / (h ** 2)
if bmi < 18.5:
print('你的体重有点轻!!', bmi)
elif bmi >= 24.0:
print('你的体重有点重了!!!', bmi)
elif bmi < 24.0 and bmi >= 18.5:
print('你的体重身体指标非常正常', bmi)
|
3045bde899d21f70decca35a0951107df53ad5be | Aurora-yuan/Leetcode_Python3 | /1071 字符串的最大公因子/1071 字符串的最大公因子.py | 925 | 3.59375 | 4 | #label: string difficulty: easy
"""
思路:
题目需要求同时满足两个条件的字符串,那就把分别满足一个条件的字符串找出来,
然后取交集,返回长度最长的那个即可。
"""
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
l1,l2 = len(str1), len(str2)
set1, set2 = set(), set()
for i in range(l1+1):
if self.find(str1, str1[:i]): #字符串切片截取不包括i
set1.add(str1[:i])
for i in range(l2+1):
if self.find(str2, str2[:i]):
set2.add(str2[:i])
res = list(set1 & set2)
res = sorted(res, key = lambda x:-len(x))
return res[0] if res else ""
def find(self, string, tmp): #tmp是否能除尽string
string = string.replace(tmp, "")
return len(string) == 0
|
f2ff85065c4b7cc08679c1cf1d211a182e9d30a1 | kaiocesar/Listasexerciciosppz | /lista_2/exercicio_4.py | 591 | 3.9375 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Author: Kaio Cesar
Exercicio 4 - Lista de exercicios 2 (Curso Python para Zumbis)
Faça um Programa que leia três números e mostre o maior deles.
"""
def maior_numer():
a=float(raw_input('Digite um valor para A? '))
b=float(raw_input('Digite um valor para B? '))
c=float(raw_input('Digite um valor para C? '))
media=(a+b+c)/3
if (a > media):
print "\"A\" é o maior valor"
elif (b > media):
print "\"B\" é o maior valor"
else:
print "\"C\" é o maior valor"
maior_numer() |
a1c602a6e16c9a69d94a8f9c1bc1e85c91f8790f | zavr1k/python-project-lvl1 | /brain_games/games/calc.py | 447 | 3.796875 | 4 | from random import randrange, choice
from operator import sub, add, mul
DESCRIPTION = "What is the result of the expression?"
OPERATIONS = {
'+': add,
'-': sub,
'*': mul,
}
def prepare_round():
number1 = randrange(99)
number2 = randrange(99)
operator = choice(list(OPERATIONS.keys()))
question = f"{number1} {operator} {number2}"
answer = OPERATIONS[operator](number1, number2)
return question, str(answer)
|
994f58bf00635d60e8dfb614f6c599d1e8f32d31 | LariDG/Cahn_Hilliad | /Poisson_Mag.py | 3,094 | 4.15625 | 4 | """
Modelling and Visualisation in Physics
Checkpoint 3: PDEs
Class to initialise 3D potential and magnetic fields
of a lattice with a wire through the centre.
Done so based on Poisson statistics.
Author: L. Dorman-Gajic
"""
import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import sys
import math
from scipy import signal
class Poisson_Mag(object):
def __init__(self, size, A_0, thres):
"""
initialising
:param size: size of 3d lattice as a tuple
:param A_0: initial condition
:param thres: the threshold for convergence
"""
self.size = size
self.omega = 1.0
self.A_0 = A_0
self.thres = thres
self.build()
def build(self):
"""
building lattices for A (the vector potential) and J (the current field)
"""
A_size = (self.size[0]-2, self.size[1]-2, self.size[2]-2)
self.A = (np.random.choice(a=[0.01,-0.01], size = A_size)*np.random.random(A_size) + self.A_0)
self.A = np.insert(self.A,A_size[0]-2,0,axis=0)
self.A = np.insert(self.A,A_size[1]-2,0,axis=1)
self.A = np.insert(self.A,A_size[2]-2,0,axis=2)
self.A = np.insert(self.A,0,0,axis=0)
self.A = np.insert(self.A,0,0,axis=1)
self.A = np.insert(self.A,0,0,axis=2)
self.J = np.zeros(self.size)
def wire(self):
"""
putting a wire through the centre of the current field
"""
self.J[self.size[0]//2, self.size[1]//2, :] = 1.0 / self.size[2]
def jacobi(self, lattice):
"""
Convolution method of updating via the jacobi algorithm given a lattice
"""
kernel = np.array([[[0.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,0.0]],
[[0.0,1.0,0.0],[1.0,0.0,1.0],[0.0,1.0,0.0]],
[[0.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,0.0]]])
return ((signal.fftconvolve(lattice, kernel, mode='same') + self.J)/ 6.0)
def gauss_seidel(self):
"""
Gauss-Seidel algorithm using for loops for a 3D lattice.
"""
for i in range(1,self.size[0]-1):
for j in range(1,self.size[1]-1):
for k in range(1,self.size[2]-1):
self.A[(i,j,k)] = ((1/6)*(self.A[(i+1,j,k)] + self.A[(i-1,j,k)] + self.A[(i,j+1,k)] + self.A[(i,j-1,k)] + self.A[(i,j,k+1)] + self.A[(i,j,k-1)] + self.J[(i,j,k)]) - self.A[(i,j,k)])*self.omega + self.A_0[(i,j,k)]
def m_field(self):
"""
Calculating the magnetic field from the gradient of the potential field
"""
grad = np.gradient(self.A)
B_x = grad[1] - grad[2]
B_y = - grad[2] - grad[0]
B_z = - grad[0] - grad[1]
return (B_x, B_y, B_z)
def terminate_condition(self, p_a, p_b):
"""
if statment to determine if the lattice has converged.
"""
if np.sum(abs(p_a - p_b), axis = None) <= self.thres:
return True
else:
return False
|
515d5b9ca5e3fd9947ac4c4de05a326c4b5e9d8a | joseangel-sc/CodeFights | /Arcade/LabOfTransformations/HigherVersion.py | 1,222 | 3.703125 | 4 | '''Given two version strings composed of several non-negative decimal fields separated by periods ("."), both strings contain equal number of numeric fields. Return true if the first version is higher than the second version and false otherwise.
The syntax follows the regular semver ordering rules:
1.0.5 < 1.1.0 < 1.1.5 < 1.1.10 < 1.2.0 < 1.2.2
< 1.2.10 < 1.10.2 < 2.0.0 < 10.0.0
There are no leading zeros in any of the numeric fields, i.e. you do not have to handle inputs like 100.020.003 (it would instead be given as 100.20.3).
Example
For ver1 = "1.2.2" and ver2 = "1.2.0", the output should be
higherVersion(ver1, ver2) = true;
For ver1 = "1.0.5" and ver2 = "1.1.0", the output should be
higherVersion(ver1, ver2) = false.
Input/Output
[time limit] 4000ms (py)
[input] string ver1
Constraints:
1 ≤ ver1.length ≤ 14.
[input] string ver2
Constraints:
1 ≤ ver2.length ≤ 14.
[output] boolean'''
def higherVersion(ver1, ver2):
version1 = ver1.split(".")
version2 = ver2.split(".")
for i in range(0,len(version1)):
if int(version1[i])>int(version2[i]):
return True
elif int(version1[i])<int(version2[i]):
return False
return False
|
78c3560a52578df150526ab61123bf01b44fd776 | ArianaMikel/CSE | /notes/Ariana Mikel- Validator.py | 1,888 | 4.03125 | 4 | import csv
# Drop the last digit from the number. The last digit is what we want to check against
# Reverse the numbers
# Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9
# Add all the numbers together
# The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10
# (Modulo 10)
def sixteen_digits(number16: str):
if (len(number16)) == 16:
if (len(number16)) == 16:
return True
else:
print("Not every number has 16 digits")
return False
def divisible_by_2(number: int):
if number % 2 == 0:
return True
return False
def valid_card_number(num: str):
if not sixteen_digits(num):
return False
valid_card_number_list = list(num)
valid_card_number_list.pop(15)
for number in range(len(valid_card_number_list)):
valid_card_number_list[number] = int(valid_card_number_list[number])
reversed_num = num[::-1]
reversed_num_list = []
for i in range(len(reversed_num)):
reversed_num_list.append(int(reversed_num[i]))
for index in range(len(reversed_num_list)):
if divisible_by_2(index):
if int(reversed_num_list[index]) * 2 > 9:
reversed_num_list[index] = int(reversed_num_list[index]) * 2 - 9
else:
reversed_num_list[index] *= 2
sum_numbers = sum(reversed_num_list)
if(sum_numbers % 10) == 0:
return True
return False
with open("Book1.csv", "r") as old_csv:
with open("Validator.csv", "w", newline='') as new_csv:
reader = csv.reader(old_csv)
writer = csv.writer(new_csv)
print("Processing...")
for row in reader:
num = row[0]
if valid_card_number(num):
writer.writerow(row)
print("Done")
|
08972516d1c3d75980b8fa48bcf236dd5bed23cd | BlakeBeyond/python-onsite | /week_02/07_conditionals_loops/Exercise_06.py | 183 | 4.25 | 4 | '''
Using a "while" loop, find the sum of numbers from 1-100.
Print the sum to the console.
'''
sum_num = 0
num = 1
while num <= 100:
sum_num +=num
num += 1
print (sum_num) |
70e1981f6c1e8f96cb1f8f3dce951d901c3962fb | sgwon96/codingTestPython | /codeUp100/81~100/87.py | 157 | 3.640625 | 4 | n = int(input())
for i in range(1,n+1):
if i%3 == 0 :
continue
print(i,end=" ")
# 6087 : [기초-종합] 3의 배수는 통과(설명)(py)
|
b74559c419417be90e4f5ab07a64ef6739d583ee | cs-cordero/interview-prep | /leetcode/0543_diameter_of_binary_tree.py | 611 | 3.5625 | 4 | from typing import Optional
class TreeNode:
# Provided by Leetcode
...
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
longest = float("-inf")
def helper(node: Optional[TreeNode]) -> int:
if node is None:
return 0
nonlocal longest
left = helper(node.left)
right = helper(node.right)
longest = max(longest, left + right + 1, max(left, right) + 1)
return max(left, right) + 1
helper(root)
return longest - 1
|
c146da67e2db2c5d5633dd3f5a371028bc669b8c | Tearrockster/Prepro---Python | /Sublime pt/000012.5.py | 472 | 4 | 4 | """[Extra] Cryptography EP.3 - Caesar N Cipher"""
def main():
"""Main function"""
num = int(input())
alphabet = ord(input())
if 65 <= alphabet <= 67 and num > 0:
alphabet -= num
print(chr(alphabet))
if 68 <= alphabet <= 90 and num > 0:
alphabet -= num
print(chr(alphabet))
if 97 <= alphabet <= 99 and num > 0:
print(chr(alphabet))
if 100 <= alphabet <= 122 and num > 0:
print(chr(alphabet))
|
08d810b67b998ce5efc1b8213916d8ee49080101 | TheWildMonk/password-manager-project | /password.py | 1,086 | 3.65625 | 4 | # Password class
import random
class Password:
def __init__(self):
self.letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
self.numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
self.symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
self.nr_letters = random.randint(8, 10)
self.nr_symbols = random.randint(2, 4)
self.nr_numbers = random.randint(2, 4)
def create_password(self):
password_list = [random.choice(self.letters) for _ in range(self.nr_letters)]
password_list += [random.choice(self.numbers) for _ in range(self.nr_numbers)]
password_list += [random.choice(self.symbols) for _ in range(self.nr_symbols)]
random.shuffle(password_list)
password = "".join(password_list)
return password
|
312444efad2dcc5d9dbeff620638bfec26162178 | 953250587/leetcode-python | /LowestCommonAncestorOfABinaryTree_MID_236.py | 2,674 | 4.03125 | 4 | """
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
119ms
"""
self.mark=0
self.lists=[]
if root==None:
return None
if p==q:
return p
def find_p_q(root):
if self.mark==0:
self.lists.append(root)
if root == p or root == q:
self.mark += 1
if self.mark == 2:
return True
if root.left != None:
if find_p_q(root.left):
return True
if root.right != None:
if find_p_q(root.right):
return True
if root in self.lists:
self.lists.remove(root)
return False
find_p_q(root)
return self.lists[-1]
def lowestCommonAncestor_1(self, root, p, q):
#135ms
def path(root, goal):
path, stack = [], [root]
while True:
node = stack.pop()
if node:
if node not in path[-1:]:
path += node,
if node == goal:
return path
stack += node, node.right, node.left
else:
path.pop()
return next(a for a, b in zip(path(root, p), path(root, q))[::-1] if a == b)
root=TreeNode(3)
root.left=TreeNode(5)
root.right=TreeNode(1)
root.left.left=TreeNode(6)
root.left.right=TreeNode(2)
root.left.right.left=TreeNode(7)
root.left.right.right=TreeNode(4)
root.right.left=TreeNode(0)
root.right.riht=TreeNode(8)
print(Solution().lowestCommonAncestor(root,root.left.left,root.left.right.right).val) |
b34fe77e92780ebde586e00d3ab9745b5ffb1b59 | sfwarnock/python_programming | /chapter 7/exercise 7.8.py | 940 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 22 2018
@author: Scott Warnock
"""
# exercise 7.8.py
#
# A person eligible to be a US senator if they are at least 30 years old and have been
# a US citizen for at least 9 years. To be a US represntative these numbers are 25
# and 7, respectively. Write a program that accepts a person's age and years of
# citizenship as input and outputs their elgibility for the Senate and House.
def main():
age = eval(input("Enter your age: "))
usCitizen = eval(input("How many years have you been a U.S. Citizen: "))
if age >= 30 and usCitizen >= 9:
print("You are elgiable to be either a US Senator or House Representative!")
elif age >= 25 and usCitizen >=7:
print("You are elgiable to be a House Representative!")
else:
print("You are not elgiable to be either a US Senator or House Representative!")
main() |
a6ddcabe0f905887fde121fc0f7700f84ffa6b79 | GeekGray-Code/python | /PythonWork/work/w6/整数排序.py | 738 | 3.703125 | 4 | # 输入一个字符串列表,将它转换为数字列表
def strListToIntList(strList):
return list(map(int, strList))
# 判断是否为整数
def isInteger(strValue):
try:
num = int(strValue)
if isinstance(num, int):
return True
except ValueError:
return False
sequenceList=[]
countStr=input()
integerFlag=isInteger(countStr)
if integerFlag:
count=int(countStr)
sequenceList=list(input().strip().split())
sequenceIntList=strListToIntList(sequenceList)
sequenceIntList.sort()
for item in sequenceIntList:
print(item, end=" ")
# sequenceList=list(input().strip().split())
# sequenceIntList=strListToIntList(sequenceList)
#
# sequenceIntList.pop(0)
|
a60d1001a18a58c1aa2ce66c79817369d14f9e69 | grecoe/teals | /4_advanced/designs/1_typing.py | 859 | 3.84375 | 4 | """
Typing helps your API/SDK users know what they should be expecting to pass
and recieve from calling a method.
Unlike languages like C#, Java, etc.... Python won't enforce method types.
Including typing is just a HINT.
A HINT because Python uses duck typing.
If it's critical for your code to have something specific you SHOULD validate it.
"""
import typing
def validated_check(selector : int, message : typing.Dict[str,str]) -> None:
if not isinstance(selector, int):
print("This should THROW because of a type mismatch - selector")
return
if not isinstance(message, dict):
print("This should THROW because of a type mismatch - message")
return
print("All looks good here!")
# Uh-oh......
validated_check(3, "Foo bar")
# OK
validated_check(3, {"some" : "value"})
|
7927aace6b8037445bd904f9be3d758fbcf82af1 | rishabhchopra1096/Python_Crash_Course_Code | /Chapter_6_Dictionaries/7-1.RentalCars.py | 198 | 3.828125 | 4 | car = raw_input("What kind of rental car would you like? " +
"\nIf you do not want any car , enter 'quit'. ")
if car != 'quit':
print("Let me see if i can find a " + car.title() + ".")
|
25cbee5e4b0ea15da9799d8406b7519e63bd2c3f | rwang4/Snake | /inheritance_in_list.py | 112 | 3.578125 | 4 |
class A:
def __init__(self, v):
self.v = v
v = 0
a = A(v)
for i in range(0, 5):
a.v += 5
print(a.v)
|
bc22594475e78d77c59d944a199e32281c896edd | JayceCaiUMD/XCumd | /学习/DataCleaningchar7.2_movies.py | 666 | 3.53125 | 4 | import pandas as pd
import numpy as np
# 处理movies数据 分类变量(categorical)
# DataFrame中的某行属于 多重分类
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_csv('datasets/movielens/movies.dat', sep='::',
header=None, names=mnames)
print(movies.head(10))
#取出所有genre的集合
all_genres= []
for x in movies.genres:
all_genres.extend(x.split('|'))
genres=pd.unique(all_genres)
print(genres)
zero_matrix = np.zeros(len(movies),len(genres)) #行数是movies,列数是genres,的ndarray对象
dummies = pd.DataFrame(zero_matrix,columns=genres) #构成了全0的DataFrame
|
97a0c53c8e6c3bb843118982f306cbe0474fb422 | Andr-Malcev/SP | /Lab 5/4.1 Средний уровент.py | 250 | 3.65625 | 4 | import random
R = 3
listA = []
for i in range(10):
listA.append(round(random.random()*10-5, 2))
print('Исходный массив: ', listA)
print('Наиболее удаленный элемент: ', (max(listA, key=lambda x: abs(R-x))))
|
4146378b69e15199c65ed119dedd5c81f7344283 | JisooBrianKim1/CompletePythonMastery | /functional_programming/comprehensions.py | 594 | 3.625 | 4 | #list, set, dictionary
# my_list = [param for param in iterable]
my_list = [char for char in 'hello']
my_list2 = [num for num in range(0, 100)]
my_list3 = [num ** 2 for num in range(0, 100)]
my_list4 = [num for num in range(0, 100) if num % 2 == 0]
# print(my_list)
# print(my_list2)
# print(my_list3)
# print(my_list4)
# sets
my_list = {char for char in 'hello'}
my_list2 = {num for num in range(0, 100)}
# dictionary
# simple_dict = {
# 'a': 1,
# 'b': 2
# }
# my_dict = {key:value**2 for key, value in simple_dict.items()}
my_dict = {num:num*2 for num in [1, 2, 3]}
print(my_dict) |
3c86348581cfedff5b161c452dc9d6dc4a2fc08a | killbug2004/Snippets | /Algorithm/algorithm/2stackqueue/client.py | 648 | 3.796875 | 4 | from queue import Queue;
if __name__ == "__main__":
queue = Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
queue.show();
print "=====================";
print "pop", queue.dequeue();
queue.show();
print "=====================";
print "pop", queue.dequeue();
queue.show();
print "=====================";
print "pop", queue.dequeue();
queue.show();
print "=====================";
queue.enqueue(7);
queue.enqueue(8);
queue.enqueue(9);
queue.show();
print "=====================";
print "pop", queue.dequeue();
queue.show();
print "=====================";
|
6fbc4852aaa0c3478e97ec3ea407d1c7470985d1 | LiXiaofeng-712/- | /Tedu/python/day06/math_game.py | 632 | 3.65625 | 4 | #coding:utf-8
import random
def exam():
nums = [random.randint(1,100) for i in range(2)]
nums.sort(reverse=True)
op = random.choice('+-')
if op in '+':
result = nums[0] + nums[1]
else:
result = nums[0] - nums[1]
prompt = '%s %s %s = ' %(nums[0],op,nums[1])
answer = int(input(prompt))
if answer == result:
print('\nVery good!')
else:
print('\nWrong answer!')
def main():
while True:
exam()
yn = input('Contine(y/n)?').strip()[0]
if yn in 'nN':
print('\nByeBye!')
break
if __name__ == '__main__':
main()
|
958f4f37c15cffb9bdf2dff4615a0272ae4578e5 | cs-richardson/whosaiditpart1-2-hnguyen21 | /whosaidit.py | 2,868 | 4.15625 | 4 | '''
The code takes a text as an input. It takes the file name of
a text file, reads it and creates a dictionary of unique words.
It keeps count of the frequency of each unique word.
Then, it creates a score based on how similar the
frequency of words appear in each dictionary compared with the
user input text. Then it prints an appropriate message determining
which author it thinks the inputted text is from.
References
https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary
By: Ben
'''
import math
#Functions
#Given function that normalizes letters (takes out punctuation and upper cases).
def normalize(word):
return "".join(letter for letter in word if letter.isalpha()).lower()
'''
Part 1 and 2 Function
This function creates a dictionary with the word as
the key and the frequency as the value
'''
def get_counts(filename):
result_dict = {}
#Getting the individual words
file = open(filename, "r")
total = 0
for lines in file:
lines = lines.split()
for word in lines:
word = normalize(word)
if word != "":
#Adds 1 to the value if the word is already in the dictionary
if word in result_dict:
result_dict[word] = result_dict[word] + 1
total = total + 1
#Adds a new word to the dictionary
else:
result_dict[word] = 1
total = total + 1
result_dict["_total"] = total
file.close()
return result_dict
#Given function that calculates the score of a single word when given a dictionary.
def get_score(word, counts):
denominator = float(1 + counts["_total"])
if word in counts:
return math.log((1 + counts[word]) / denominator)
else:
return math.log(1 / denominator)
'''
This function takes a text and two dictionaries and returns a boolean
'''
def predict(text, williamSDict, janeADict):
janeScore = 0
williamScore = 0
#This splits the text into words
text = text.split()
for word in text:
word = normalize(word)
if word != "":
#Calculates the scores of the entire text
williamScore = williamScore + get_score(word, williamSDict)
janeScore = janeScore + get_score(word, janeADict)
#This tells if its by Shakespeare or Jane Austen
if janeScore > williamScore:
return True
#Part 3 or 4 Main Program
hamletDict = get_counts("hamlet.txt")
prideDict = get_counts("pride-and-prejudice.txt")
textInput = input("Enter a text: ")
#If the predict returns True, it is Jane Austen while if it's false then its Shakespeare
if predict(textInput, hamletDict, prideDict):
print("I think that was written by Jane Austen.")
else:
print("I think that was written by William Shakespeare.")
|
675ee7e6b3c1f2778cb39a2756985e1404af82c4 | AndrewMonteith/Programming-Problems | /missing_words.py | 1,688 | 3.9375 | 4 | '''
Problem: Missing Words
Given 2 sequences s and t, t is a subsequence of s if the words of t
occur in s not necessarily in a contiguos sequence but in the same order.
"hi there" is a subsequence of "hi there friend"
"hi there" is a subsequence of "hi over there friend"
"hi there" is a subsequence of "hi a hi b there c there"
"hi there" is not a subsequence of "there mate, i said hi"
Write a function remove_subsequence(s, t) that removes the first occurence
of the subsequence t from s and returns the result as a words vector.
Examples:
remove_subsequence("hi there friend", "hi there") == ["friend"]
remove_subsequence("hi over there friend", "hi there") == ["over friend"]
remove_subsequence("hi a hi b there c there", "hi there") == ["a", "hi", "b", "c", "there"]
Assumptions:
s & t are non empty strings
1 <= |t| <= |s| <= 10^5
t is a subsequence of s
'''
def remove_subsequence(s, t):
words_s, words_t = s.split(" "), t.split(" ")
t_i = 0 # index of word in words_t we're looking to remove
to_remove = set([])
for i in range(0, len(words_s)):
if words_s[i] == words_t[t_i]:
to_remove.add(i)
t_i += 1
if t_i == len(words_t):
break
return [words_s[i] for i in range(0, len(words_s)) if i not in to_remove]
assert(remove_subsequence("hi there friend", "hi there") == ["friend"])
assert(remove_subsequence("hi over there friend", "hi there") == ["over", "friend"])
assert(remove_subsequence("a hi b hi c there d there", "hi there") == ["a", "b", "hi", "c", "d", "there"])
print("Success") |
8846466ad4edb258a0ca0f80dfa791b9fe363c98 | chvjak/hr-practice | /inside_poly.py | 999 | 3.5 | 4 | f = open('inside_poly1.txt')
def input():
return f.readline()
import sys
from math import acos, sqrt
def pt2normvec(pt0, pt1):
x0, y0 = pt0
x1, y1 = pt1
vec1 = [x1 - x0, y1 - y0]
v1_norm = sqrt(vec1[0] * vec1[0] + vec1[1] * vec1[1])
vec1[0] /= v1_norm
vec1[1] /= v1_norm
return vec1
def angle(pt1, pt0, pt2):
vec1 = pt2normvec(pt0, pt1)
vec2 = pt2normvec(pt0, pt2)
cos_phi = vec1[0] * vec2[0] + vec1[1] * vec2[1]
phi = acos(cos_phi)
# evaluate cross product k sign
k = vec1[0] * vec2[1] - vec1[1] * vec2[0]
if k > 0:
return -phi
else:
return phi
n = int(input())
pts = []
for i in range(n):
x, y = [float(x) for x in input().strip().split(' ')]
pts.append((x, y))
pt0 = [float(x) for x in input().strip().split(' ')]
angle_sum = angle(pts[n - 1], pt0, pts[0])
for i in range(1, n):
phi = angle(pts[i - 1], pt0, pts[i])
angle_sum += phi
print('Inside' if angle_sum > 1.0 else 'Outside')
|
2a0fbe25deb2eed8e67c8ef56b886bbdcf535644 | phuwadonop/QueueLab | /Queue.py | 1,323 | 3.859375 | 4 | from collections import deque
class Queue :
def __init__(self,items = None):
if items == None : self.items = deque()
else : self.items = deque(items,len(items))
def enQueue(self,i) :
self.items.append(i)
def deQueue(self) :
return self.items.popleft()
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def to_string(ls):
s = ""
for e in str(ls) :
if str(e) not in "[]" : s += str(e)
return s
if __name__ == '__main__':
ls_input = input("Enter Input : ").split(',')
q = Queue()
q_ = Queue()
for ele in ls_input :
if ele[0] == 'E':
q.enQueue(int(ele[2:]))
print(to_string(list(q.items)))
else :
if not q.isEmpty() :
x = q.deQueue()
q_.enQueue(x)
print("{} <- ".format(x),end="")
print(to_string(list(q.items))) if not q.isEmpty() else print("Empty")
else : print("Empty")
print("Empty",end=' : ') if q_.isEmpty() else print("{} : ".format(to_string(list(q_.items))),end='')
print("Empty",end='') if q.isEmpty() else print("{}".format(to_string(list(q.items))),end='')
|
e6a93233d33af735196d992780e03411924bed03 | kuboszek/instruments | /user.py | 770 | 3.609375 | 4 | class User:
def __init__(self, nick, avatar, password):
self.nick = nick
self.avatar = avatar
self.rank = 0
self.password = password
self.users = []
self.instruments = []
def addFriend(self, user):
self.users.append(user)
def findFriend(self, nick):
#wyszukiwanie w baze danych / pliku
user = User(nick, 'AVATAR', '1234') # MOCK
#Tak naprawde ta funkcja powinna zwrocic liste uzytkownikow o takim nicku
return user
def addInstrument(self, instrument):
if instrument not in self.instruments:
self.instruments.append(instrument)
def printInstruments(self):
for instrument in self.instruments:
instrument.print()
|
caeb47ac3ccfef7816ca2c0d2f97a02c3ad62818 | raiscreative/100-days-of-python-code | /day_005/high_score.py | 278 | 4.03125 | 4 | score_list = input('Please enter the list of all students\' score\n')
scores = score_list.split()
high_score = -100
for score in scores:
score = int(score)
if score > high_score:
high_score = score
print(f'The highest score in the class is {high_score}.') |
2f132ce7b880a1295325d4ce60d8d09240cb945c | barisceliker1/PYTHON | /whiledöngüsü5.py | 364 | 3.640625 | 4 | gunlukuretim=200
defoluurun=int(input("defolu üürün sayısı giriniz"))
kacgunluk=gunlukuretim/defoluurun
i=0
while True:
i=i+1
if defoluurun>gunlukuretim/100*20:
print("defolu ürün miktarınız çok artmıştır")
else:
print("1 günde üretilen",gunlukuretim,"pantolondan",defoluurun,"tanesi defoludur")
break
|
48aa9bf025676597e6630ad44e21b34123832d81 | devesh37/HackerRankProblems | /Datastructure_HackerRank/Linked List/InsertaNodeAtaSpecificPositionInaLinkedList.py | 1,468 | 3.953125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the insertNodeAtPosition function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#Link: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
#
def insertNodeAtPosition(head, data, position):
count=1
newNode=SinglyLinkedListNode(data)
if(head==None):
head=newNode
return(head)
temp=head
while(temp.next!=None and position!=(count)):
temp=temp.next
count+=1
if(temp.next!=None):
temp1=temp.next
temp.next=newNode
newNode.next=temp1
else:
temp.next=newNode
return(head)
if __name__ == '__main__': |
209e192e16194bdcc60e55bc21e7e7a11e18d3d1 | NikhilRaghav/Lets-Upgrade-Youtube-Courses | /Data Structure and Algorithm with Python Batch 2 - FEB LetsUpgrade Toutube Pgm/Assignments/Assignment_1_Solution-Ques_1_and_2.py | 337 | 4.15625 | 4 | a=int(input("Enter a number"))
b=int(input("Enter another Number "))
#Question 1
print("Addition of two Numbers is ",a+b)
print("Subtration of two Numbers is ",a-b)
print("Multiplication of two Numbers is ",a*b)
print("Division of two Numbers is ",a/b)
print("Floor Division of two Numbers is ", a//b)
#Question 2
print("a ^b = ",a**b)
|
da255daa79c4f468d79e6081d79f2739dd50a406 | C-CCM-TC1028-102-2113/tarea-4-A01026608 | /assignments/06PromedioConDecision/src/exercise.py | 294 | 3.921875 | 4 | def main():
#escribe tu código abajo de esta línea
contador= 0
suma= 0
numero=1
while True:
numero= float(input())
if numero<0:
break
suma= suma+numero
contador= contador+1
promedio= suma/contador
print( promedio)
|
ee4b9d815c120fa76678e3fa20b64d0bca78c263 | anth7310/Minimax-Tic-Tac-Toe-Python | /minimax.py | 4,444 | 3.890625 | 4 | def checkWinner(board):
""" Returns true if winner exist
"""
states = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5 ,8],
[0, 4, 8],
[2, 4, 6]
]
# flatten board
flat_board = []
for row in board:
for col in row:
flat_board.append(col)
# No empty states, return tie
if '' not in flat_board:
return 'tie'
# Winner exist
for state in states:
a, b, c = state
if flat_board[a] == flat_board[b] == flat_board[c] and flat_board[a] != '':
return flat_board[a]
# Game still continuing
return ''
def minimax(board, depth, isMax):
"""
Takes a 3x3 list
depth is recursion depth
isMax is maximizing player
"""
bestMove = []
result = checkWinner(board)
if result == 'x': # heristic values
return 10
if result == 'o':
return -10
if result == 'tie':
return 0
if isMax: # maximizing player is 'x'
bestScore = -float("Inf")
if result == '': # is there empty spot to play
for i in range(3):
for j in range(3):
if board[i][j] == '':
board[i][j] = 'x'
# add depth to optimize play, want player to choose fastest win
value = minimax(board, depth+1, False) - depth
board[i][j] = ''
bestScore = max(bestScore, value)
else: # minimizing player is 'o'
bestScore = float("Inf")
if result == '':
for i in range(3):
for j in range(3):
if board[i][j] == '':
board[i][j] = 'o'
value = minimax(board, depth+1, True) + depth
board[i][j] = ''
bestScore = min(bestScore, value)
# return the best score for the given board
return bestScore
def calculateScores(board, isMax):
# calculate values with heuristic score
scores = [
['', '', ''],
['', '', ''],
['', '', '']
]
for i in range(3):
for j in range(3):
if board[i][j] == '':
if isMax:
board[i][j] = 'x'
scores[i][j] = minimax(board, 0, not isMax)
else:
board[i][j] = 'o'
scores[i][j] = minimax(board, 0, not isMax)
board[i][j] = ''
return scores
def pickOptimalMove(board, isMax, returnScore=False):
if isMax:
bestScore = -float("Inf")
for i in range(3):
for j in range(3):
if board[i][j] == '':
board[i][j] = 'x'
score = minimax(board, 0, False)
board[i][j] = ''
if score > bestScore:
bestScore = score
bestMove = (i, j)
else:
bestScore = float("Inf")
for i in range(3):
for j in range(3):
if board[i][j] == '':
board[i][j] = 'o'
score = minimax(board, 0, True)
board[i][j] = ''
if score < bestScore:
bestScore = score
bestMove = (i, j)
if returnScore:
return bestMove, bestScore
return bestMove
# board = [
# ['x', 'x', ''],
# ['', 'o', ''],
# ['', '', 'o']
# ]
board = [
['', 'o', 'x'],
['o', 'x', ''],
['', '', '']
] # (2, 0)
# board = [
# ['x', 'o', ''],
# ['o', 'x', ''],
# ['', '', '']
# ] # (2, 2)
# board = [
# ['x', 'o', ''],
# ['x', 'o', ''],
# ['', '', '']
# ] (2, 0)
# board = [
# ['', '', ''],
# ['', '', ''],
# ['', '', '']
# ]
print(minimax(board, 0, isMax=True))
print(calculateScores(board, True))
print(pickOptimalMove(board, isMax=True, returnScore=False))
### Play game
# while True:
# print(calculateScores(board, isMax=True))
# ai = pickOptimalMove(board, isMax=True, returnScore=False)
# board[ai[0]][ai[1]] = 'x'
# print(board)
# x = int(input())
# y = int(input())
# board[x][y] = 'o'
# print(board)
|
53d554b118c476038ec15f84af5827cc4353bb02 | Fouad-Karam/Python-TurtleCrossing | /main.py | 898 | 3.703125 | 4 | from turtle import Turtle, Screen
from player import Player
from scoreboard import Scoreboard
from cars import Cars
import time
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("white")
screen.title("TurtleCrossing")
screen.tracer(0)
player = Player()
scoreboard = Scoreboard()
new_car = Cars()
screen.listen()
screen.onkeypress(player.move, "Up")
game_is_on = True
while game_is_on:
time.sleep(0.03)
screen.update()
new_car.create_car()
new_car.move_cars()
# Detect collision with cars
for car in new_car.all_cars:
if car.distance(player) < 20:
game_is_on = False
scoreboard.game_over()
# Detect that turtle crossed the road
if player.ycor() > 260:
player.reset_position()
new_car.level_up()
scoreboard.increase_score()
screen.exitonclick()
|
d0bea0e62d332e8d28fe606c47f3b091bedb42a7 | neoxie/geektime_python | /21_multithread/homework.py | 814 | 3.765625 | 4 | import time
import concurrent.futures
import threading
import multiprocessing
def cpu_bound(number):
print(sum(i * i for i in range(number)))
def calculate_sums(numbers):
# for number in numbers: #1 single thread
# cpu_bound(number) #1 single thread
# with concurrent.futures.ProcessPoolExecutor() as executor: #2 multi-process
# executor.map(cpu_bound, numbers) #2 multi-process
with multiprocessing.Pool() as pool: #3 multiprocessing pool
pool.map(cpu_bound, numbers) #3 multiprocessing pool
def main():
start_time = time.perf_counter()
numbers = [10000000 + x for x in range(20)]
calculate_sums(numbers)
end_time = time.perf_counter()
print('Calculation takes {} seconds'.format(end_time - start_time))
if __name__ == '__main__':
main()
|
7d15bba70d093b04781e396e07309f8d9aa9ab54 | katariasid565/band-generator | /main.py | 366 | 3.53125 | 4 | # ------------------------------------------
print("Welcome to the band Generator..!!")
# ------------------------------------------
city = input("what's name of the city you grow up in?\n")
# ------------------------------------------
pet = input("what's your pet name?\n")
# ------------------------------------------
print("your band name is " + city + " "+ pet) |
9472eb6f69d316dd1da1adb972fa9899662c3e35 | Hu-sky/Advance | /Learning Record/3.4 学习记录.py | 1,176 | 3.703125 | 4 | # 1.from datetime import datetime 或import datetime.datetime
# 2.获取当前时间:datetime.now()
# 指定时间:dt=datetime(2020, 5, 12 ,9, 45) >>> 200-05-12 09:45:00
# 3.epch time记为0,1970-01-01 00:00:00 UTC+00:00时区时刻
# 4.转换:datetime(time).timestamp() >>> 秒.毫秒 class<float>
# 5.本地时间:datetime.fromtimestamp(距离epch time秒)
# 格林威治时间:datetime.utcfromtimestamp(距离epch time秒)
# 6.str转换为datetime:转换后的datetime没有时区属性
# datetime.strptime('2020-6-1 19:45:27','%Y-%m-%d %H:%M:%S')
# 7.datetime转换为str:
# datetime.now().strftime('%a,%b %d %H:%M')
# 8.datetime加减,需导入timedelta类:time+timedelta(days=, hours=)
# 9.本地时间转换为UTC时间:
# 导入timezone类,利用tzinfo(默认None)属性
# 创建时区UTC+8:00 tz_utc_8=timezone(timedelta(hours=8))
# 强制设置为UTC+8:00 now.replace(tzinfo=tz_utc_8)
#10.时区转换:
# 先拿datetime时间,utc_time=datetime.utcnow().replace(tzinfo=timezone.utc)
# bj_time=utc_time.astimezone(timezone(timedelta(hours=8)))
#11.%a/%A:星期 %b/%B:月份(英) %m:月 %y/%Y:年份 %I/%H:小时 %M/%S:分秒 |
8ba19ee0a4811e3f73a66d95e82614ac2b553973 | weifengli001/pythondev | /vendingmachine/test.py | 2,787 | 4.28125 | 4 | """
CPSC-442X Python Programming
Assignment 1: Vending Machine
Author: Weifeng Li
UBID: 984558
"""
#Global varable
paid_amount = 0.0#The total amount of insert coins
total = 0 #The total costs
change = 0 # change
drinks = {"Water" : 1, "Soda" : 1.5, "Juice" : 3} # The drinks dictionary stores drinks and their price
snackes = {"Chips" : 1.25, "Peanuts" : 0.75, "Cookie" : 1} #The snackes dictionary stores snackes and their price
"""
entering function
parameter: factor, is the value of the coin
"""
def vending(factor = 0.25):
global paid_amount, total, change
print("Welco to the UB vending machine.")
cnt = input("Enter the number of quarters you wish to insert: ")
paid_amount = int(cnt) * factor
change = paid_amount - total
print("You entered ", paid_amount, " dollars.")
main_menu()
#main menu
def main_menu():
global paid_amount, total, change
while True:
print("------------------------------------")
print("Select category: ")
print("1. Drinks")
print("2. Snacks")
print("3. Exit")
selection = input("Select an option: ")
if(selection == '1'):
drinks_menu()
elif(selection == '2'):
snackes_menu()
elif(selection == '3'):
#change = paid_amount - total
print("Paid amount: ", paid_amount, ", total purchase: ", total, ", change: ", change)
return
else:
print("Invalid selection.")
#drinks menu
def drinks_menu():
global paid_amount, total, change
while True:
print("-------------------------------------")
print(" Juice ($3)")
print(" Water ($1)")
print(" Soda ($1.5)")
drink = input("Enter your drink selection (x to exit): ")
if(drink == 'x'):
break
elif(drinks.get(drink) == None):
print("Invalid selection.")
else:
if(drinks[drink] > change):
print("You don't have enough money to buy", drink)
else:
total += drinks[drink]
change -= drinks[drink]
#snackes menu
def snackes_menu():
global paid_amount, total, change
while True:
print("-----------------------------------------")
print(" Chips: ($1.25)")
print(' Peanuts: ($0.75)')
print(" Cookie: ($1)")
snack = input("Enter your snack selection (x to exit): ")
if(snack == 'x'):
break
elif(snackes.get(snack) == None):
print("Invalid selection.")
else:
if(snackes[snack] > change):
print("You don't hava enough money to buy", snack)
else:
total += snackes[snack]
change -= snackes[snack]
vending()
|
cd97e9b2fbc8ec1fcdb65f8910370af463920652 | herasj/Constructor_Imagenes | /list_ops.py | 6,018 | 3.578125 | 4 | import copy
import numpy as np
def sumar_subl(l,h): #Sumar los valores de cada sublista
newl=[]
temp=0
for x in range(0,4):
for y in range(0,h):
temp=temp+l[x][y]
newl.append(copy.deepcopy(temp))
temp=0
return newl
def restar_l(l1,l2,h): #Restar dos listas de bordes
lista_resta=[] #Lista que contendrá todas las diferencias
r_l=[] #Almacena la diferencia entre el derecho de l1 y el izquierdo de l2
u_d=[] #Almacena la diferencia entre el superior de l1 y el inferior de l2
d_u=[] #Almacena la diferencia entre el inferior de l1 y el superior de l2
l_r=[] #Almacena la diferencia entre el izquierdo de l1 y el derecho de l2
for x in range(0,h):
r_l.append(abs(l1[3][x]-l2[2][x]))
u_d.append(abs(l1[0][x]-l2[1][x]))
d_u.append(abs(l1[1][x]-l2[0][x]))
l_r.append(abs(l1[2][x]-l2[3][x]))
#Añadir los datos a la lista principal
lista_resta.append(copy.deepcopy(r_l));
lista_resta.append(copy.deepcopy(u_d));
lista_resta.append(copy.deepcopy(d_u));
lista_resta.append(copy.deepcopy(l_r));
r_l.clear();u_d.clear();d_u.clear();l_r.clear(); #Eliminar datos innecesarios
return lista_resta
def menor(list):
temp=[99999,-1] #[Menor, posición]
for x in range(0,len(list)):
if(list[x]<temp[0]):
temp[0]=list[x]
temp[1]=x
return temp
def mueve(grid,n1,n2,mov):
#Si el mov es 0, n2 queda a la derecha de n1
#Si el mov es 1, n2 queda arriba de n1
#Si el mov es 2, n2 queda debajo de n1
#Si el mov es 3, n2 queda a la izquierda de n1
esta1=esta(grid,n1)
esta2=esta(grid,n2)
if mov==0: # n1->n2
if((esta1[0]!=-1) and (esta2[0]==-1)): #Si está n1 pero n2 no
grid[esta1[0]].insert(esta1[1]+1,n2) #Se inserta n2 al lado de n1
elif ((esta1[0]==-1) and (esta2[0]!=-1)):#Si està n2 pero no n1
grid[esta2[0]].insert(esta2[1],n1) #Se inserta n1 a la izq de n2
elif ((esta1[0]==-1) and (esta2[0]==-1)):#No esta n1 y n2
#Se intenta añadir n1 y n2 al grid vacio
if(len(grid[0])<=1):
grid[0].append(n1);grid[0].append(n2)
elif(len(grid[1])<=1):
grid[1].append(n1);grid[1].append(n2)
elif(len(grid[2])<=1):
grid[2].append(n1);grid[2].append(n2)
else:
print("ERROR: No hay espacio en el grid para n1= ",n1," y n2= ",n2, "con mov= ",mov)
print(grid)
elif mov==1: #n2 arriba de n1
if((esta1[0]!=-1) and (esta2[0]==-1)): #Si está n1 pero n2 no
grid[esta1[0]-1].insert(esta1[1],n2) #Se inserta n2 arriba de n1
elif ((esta1[0]==-1) and (esta2[0]!=-1)):#Si està n2 pero no n1
grid[esta2[0]+1].insert(esta2[1],n1) #Se inserta n1 debajo de n2
elif ((esta1[0]==-1) and (esta2[0]==-1)):#No esta n1 y n2
#Se intenta añadir n1 y n2 al grid vacio
if((len(grid[0])<=2)and (len(grid[1])<=2)):
grid[0].append(n2);grid[1].append(n1)
elif((len(grid[1])<=2)and (len(grid[2])<=2)):
grid[1].append(n2);grid[2].append(n1)
else:
print("ERROR: No hay espacio en el grid para n1= ",n1," y n2= ",n2, "con mov= ",mov)
print(grid)
elif mov==2:#n2 debajo de n1
if((esta1[0]!=-1) and (esta2[0]==-1)): #Si está n1 pero n2 no
grid[esta1[0]+1].insert(esta1[1],n2) #Se inserta n2 debajo de n1
elif ((esta1[0]==-1) and (esta2[0]!=-1)):#Si està n2 pero no n1
grid[esta2[0]-1].insert(esta2[1],n1) #Se inserta n1 arriba de n2
elif ((esta1[0]==-1) and (esta2[0]==-1)):#No esta n1 y n2
#Se intenta añadir n1 y n2 al grid vacio
if((len(grid[0])<=2)and (len(grid[1])<=2)):
grid[0].append(n1);grid[1].append(n2)
elif((len(grid[1])<=2)and (len(grid[2])<=2)):
grid[1].append(n1);grid[2].append(n2)
else:
print("ERROR: No hay espacio en el grid para n1= ",n1," y n2= ",n2, "con mov= ",mov)
print(grid)
else: #n2 izq de n1
if((esta1[0]!=-1) and (esta2[0]==-1)): #Si está n1 pero n2 no
grid[esta1[0]].insert(esta1[1],n2) #Se inserta n2 a la izq de n1
elif ((esta1[0]==-1) and (esta2[0]!=-1)):#Si està n2 pero no n1
grid[esta2[0]].insert(esta2[1]+1,n1) #Se inserta n1 a la der de n2
elif ((esta1[0]==-1) and (esta2[0]==-1)):#No esta n1 y n2
#Se intenta añadir n1 y n2 al grid vacio
if(len(grid[0])<=1):
grid[0].append(n1);grid[0].append(n2)
elif(len(grid[1])<=1):
grid[1].append(n1);grid[1].append(n2)
elif(len(grid[2])<=1):
grid[2].append(n1);grid[2].append(n2)
else:
print("ERROR: No hay espacio en el grid para n1= ",n1," y n2= ",n2, "con mov= ",mov)
print(grid)
return grid
def esta (grid,n):
res=[-1,-1]
if((len(grid[0])==0) and (len(grid[1])==0) and (len(grid[2])==0)):
return res
for x in range(0,len(grid)):
if(len(grid[x])!=0):
for y in range(0,len(grid[x])):
if(grid[x][y]==n):
res[0]=x
res[1]=y
return res
def centrar (grid,centro):
#Si el mov es 0, n2 queda a la derecha de n1
#Si el mov es 1, n2 queda arriba de n1
#Si el mov es 2, n2 queda debajo de n1
#Si el mov es 3, n2 queda a la izquierda de n1
grid[1].append(centro[0])
for x in range(1,5):
if(centro[x][0]==0):
grid[1].append(centro[x][1])
elif (centro[x][0]==1):
grid[0].insert(1,centro[x][1])
elif (centro[x][0]==2):
grid[2].insert(1,centro[x][1])
elif (centro[x][0]==3):
grid[1].insert(0,centro[x][1])
print("Asi quedó la grid")
print(grid)
return grid |
a024492e898a17c1c0beb3b1dc6f02c2ff5e5b33 | xysey/python100 | /P20.py | 353 | 3.796875 | 4 | '''
Question 20
Level 3
Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
Hints:
Consider use yield
'''
def gen_seven(r):
i = 0
while i < r:
ri = i
i = i + 1
if ri % 7 == 0:
yield ri
for num in gen_seven(100):
print(num) |
acbeffd870b4682008e3b1cc10fd790f35225b0b | ebrahimsalehi1/python_codes | /day181020_graphic.py | 606 | 3.75 | 4 | import turtle
import time
pos = 20
turtle.speed(1)
turtle.goto(1,1)
#turtle.sety(10)
for i in range(1,41):
turtle.forward(50)
turtle.left(90)
if i == 1:
turtle.color("red")
elif i == 2:
turtle.color("green")
elif i == 3:
turtle.color("brown")
elif i == 4:
turtle.color("black")
elif i == 5:
turtle.color("red")
else:
turtle.color("green")
if i%4==0:
pos=pos+50
turtle.setx(pos)
# turtle.bgcolor("white")
# time.sleep(2)
'''
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.right(50)
time.sleep(1)
'''
|
53ce049b13811b428bb84d04ec7ba3eef6357705 | Aasthaengg/IBMdataset | /Python_codes/p03293/s393886000.py | 173 | 3.671875 | 4 | s = input()
t = input()
flag = False
for i in range(len(s)):
if s == t:
flag =True
s = s[-1] + s[0:len(s)-1]
if flag:
print("Yes")
else:
print("No")
|
16d327fe9c580c23480d803b0b6f21a0e778db06 | UCSD-CSE-SPIS-2021/spis21-lab03-Jeremy-Raj | /lab03Warmup_Jeremy.py | 590 | 4.34375 | 4 | import turtle
def draw_picture(the_turtle):
''' Draw a simple picture using a turtle '''
the_turtle.forward(20)
the_turtle.left(40)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
my_turtle = turtle.Turtle() # Create a new Turtle object
draw_picture(my_turtle) # make the new Turtle draw the shape
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtle1.setpos(-50, -50)
turtle2.setpos(200, 100)
turtle1.forward(100)
turtle2.left(90)
turtle2.forward(100) |
7b1783ca0f41176fc39b177b461975abeea283b3 | EduLH/Python | /fibo.py | 212 | 3.640625 | 4 | import time
start = time.time()
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print (fib(894651))
end = time.time()
elapsed = end - start
print ("tempo percorrido de:")
print (elapsed)
|
b561a95c27b1f45823d9fb84b0d75291cb596873 | Edwincamilo/ejercicios-elaborados-2 | /prg 16 funciones.py | 1,107 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 16 18:59:05 2021
@author: 57314
"""
#factura a pagar
def f_titulo():
print("calculo valor factura")
def f_despedida():
print("gracias por su compra")
def f_valorfactura(): #encabezado de la funcion
#desarollo de la funcion
#definion de variablas
ve_nomArt =""
ve_canArt =0
ve_valUnitArt=0.0
cons_porceniva=0.19
vaprosali_netopag=0.0
vaprosali_ivapag=0.0
vaprosali_totalpag=0.0
#entradas
ve_nomArt =input("Articulo:")
ve_canArt =int(input("cantidad:"))
ve_valUnitArt = float(input("valor unitario:"))
#procesos
vaprosali_netopag= ve_canArt * ve_valUnitArt
vaprosali_ivapag = vaprosali_netopag * cons_porceniva
vaprosali_totalpag = vaprosali_netopag+ vaprosali_ivapag
#salidas
print("neto:",vaprosali_netopag)
print("iva:",vaprosali_ivapag)
print("total:",vaprosali_totalpag)
# llamado a la funcion
f_titulo()
f_valorfactura()
f_despedida()
|
71c9db7ef4573085a5741898b36ae53a69ff9938 | Benjamin-Huang910/naughty-cat | /程式概論/week14_ex1.py | 942 | 4.1875 | 4 | #Programming 101
#week14
#ex 1
#可以幫忙檢查傳入的參數num是否可成功轉換成浮點數資料型態的自訂函數
#回傳值:True 代表可以成功轉成浮點數
#回傳值:False 代表無法成功轉成浮點數
#請注意:在此函數中會使用到一個區域變數的名稱為result
def check_float(num):
try:
float(num)
except:
#有發生例外時,將變數result的內容設為False
else:
#沒有發生例外時,將變數result的內容設為True
finally:
#不管有沒有發生例外,最後都將result的內容回傳
while True:
a=input('輸入一個可以成功轉為浮點數的資料:')
if (not check_float(a)):
print('輸入資料有錯誤,請重新', end='')
continue
else:
print('輸入的資料可以成功轉為浮點數', float(a))
break
|
85cfe14767dc56c896fa60e1a2fee86234e59619 | Factumpro/HackerRank | /Python/Practice/Basic Data Types/runner_up.py | 271 | 3.734375 | 4 | #!/usr/bin/env python3
SECOND_PLACE = 1
if __name__ == '__main__':
_ = int(input())
runner_scores = list(set(map(int, input().strip().split(" "))))
# [max, ... , min] -> 0, ... , n
runner_scores.sort(reverse=True)
print(runner_scores[SECOND_PLACE])
|
782999e012f515689eb9b938beb9e995acd6fc40 | Manju9072/pythonpractise | /tic.py | 320 | 4.03125 | 4 | def tictactoeboard(size, col):
for e in range(size):
print(' ---' * col)
print(('|' + " " * 3) * (int(col) + 1))
print(' ---' * col)
print("Welcome to tic tac toe!!!!")
size = int(input("Enter the row board size:"))
col = int(input("Enter the column board size:"))
tictactoeboard(size, col)
|
d74c4aa9303e41cc42b8c21679d409bc7efef382 | SergioMD15/LinkedList-Sorting | /Main.py | 423 | 3.65625 | 4 | import math
import random
from LinkedList import LinkedList
from sorting.Criteria import Criteria
from sorting.Tuples import Tuples
from sorting.Centering import Centering
def generate_array(size):
result = LinkedList()
for i in range(size):
result.push(int(random.randint(0,1)))
return result
l = generate_array(10)
print(l)
l.sort(Tuples(3), True)
print(l)
l.sort(Centering(), False)
print(l) |
2d129fc9da8e05a43dee426aeb5253b074d6aac6 | humat/Python-built-in-functions | /even odd.py | 111 | 4.0625 | 4 | x=int(input("Enter a nuber"))
if x%2==0:
print(x,"Is even number")
else:
print(x,"Is odd number")
|
72948250db04881da120132f3e04d20be0ad4aea | league-python-student/level0-module1-DemirKaya7 | /_05_for_loops/_2_badgers/badgers.py | 183 | 3.984375 | 4 | for i in range(2):
str1 = ""
for i in range(12):
str1 = str1 + "Badger, "
for i in range(2):
str1 = str1 + "Mushroom, "
print(str1)
print("A snake!!!") |
8b4293e7bd7c490645188da8ccd676d0da4a97e4 | GerardProsper/Intermediate-Python-Programming-Course | /Function Arguments.py | 3,045 | 3.765625 | 4 |
# difference between arguements and parameters
def print_name(name): # name here is parameter
print(name)
print_name('Gerard') # Gerard here is arguments
def fool(a,b,c):
print(a,b,c)
fool(1,2,3)
fool(a=1,c=3,b=2) # this is keyword arguments. order doesnt matter
fool(2, b=3, c=5) # this would work but there are errors in different arragement
def fool(a,b,c,d=6): # default arguments must be at the end of parameters
print(a,b,c,d)
fool(1,2,3)
fool(2,3,4,9)
# if mark parameters with one *, can mark any number of positional arguements thru function. this is tuple.
# if mark parameters with two **, can mark any number of keyword arguements thru function. this is dict
# can call whatever I like. after * or **. just using args and kwargs
def foo(a,b, *args, **kwargs):
print(a,b)
for arg in args:
print(arg)
for key in kwargs:
print(key,kwargs[key])
# below is variable length arguemnts
foo(1,2,3,4,5, six=6, seven=7) # 1,2 are positional arguments. 3,4,5 are the args and six=6, seven=7 are kwargs
foo(1,2, six=6, seven=7) # can do
foo(1,2,3,4,5) # can do
def foo(a,b, *,c,d):
print(a,b,c,d)
foo(1,2,c=3,d=4)
def foo(*args,last):
for arg in args:
print(arg)
print(last)
foo(1,2,last=1000)
def foo(a,b,c):
print(a,b,c)
my_list = [0,1,2] #this is list. numbers must match function
foo(*my_list)
my_tuple = (0,1,2) #this is tuple. numbers must match function
foo(*my_tuple)
my_dict = {'a':1,'b':2, 'c':3} #positional arguments must match above. abc
foo(*my_dict)
my_dict = {'a':1,'b':2, 'c':3} #positional arguments must match above. abc
foo(**my_dict)
def foo():
x = number
print('number inside function: ', x)
number = 3
foo()
def foo():
global number
x = number
number = 3 # this is local variable without global above.
print('number inside function: ', x)
number = 0
foo()
print(number)
def foo():
number = 3 # this is local variable without global above. This only lives in this function
number = 0
foo()
print(number) #will print number = 0
def foo():
global number # if want to modify the global number from 0 to 3
number = 3 # this is local variable without global above. This only lives in this function
number = 0
foo()
print(number) # will print number = 3
def foo(x):
x = 5 # mutable objects can be modified in a function
var = 10
foo(var)
print(var) # var = 10
def foo(a_list):
a_list = [200,300,400] # this is local variable. Hence will not change my_list= [1,2,3]
a_list.append(4) # immutable objects within a mutable objects can be changed
a_list[0] = -100
my_list = [1,2,3]
foo(my_list)
print(my_list)
def foo(a_list):
a_list += [200,300,400] # this will change my_list
a_list = a_list + [200,300,400] # this is local variable. Hence will not change my_list= [1,2,3]
my_list = [1,2,3]
foo(my_list)
print(my_list)
|
e2f5c754d64e8066c3669423f9066db332b4f831 | Cbkhare/Codes | /GeekForGeeks_DetectLoopInLinkedLIst.py | 257 | 3.65625 | 4 | def detectLoop(head):
while head:
if head.data=='visited':
return 1
else:
head.data = 'visited'
head=head.next
return 0
'''
https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1
''' |
35b47821f6e335aaef19687549c1f3f7a809f8b0 | jsdelivrbot/Ylwoi | /week03/day_3/purple_steps.py | 394 | 3.859375 | 4 | __author__ = 'ylwoi'
from tkinter import *
root = Tk()
canvas = Canvas(root, width='300', height='300')
canvas.pack()
# reproduce this:
# [https://github.com/greenfox-academy/teaching-materials/blob/master/exercises/drawing/purple-steps/r3.png]
x = 10
y = 10
for i in range(20):
square = canvas.create_rectangle(x, y, x+10, y+10, fill='purple')
x += 10
y += 10
root.mainloop()
|
22fedd57d89b3dedf3784b8a97bac7702480af8d | igijon/sge2021_python | /Ejercicios recuperación/examen_ghibli/Character.py | 1,672 | 3.71875 | 4 |
class Character():
def __init__(self, name, gender = None, age = None, film = None, specie = None):
self.name = name
self.gender = gender
self.age = age
self.film = film
self.specie = specie
@property
def name(self):
return self.__name
@property
def gender(self):
return self.__gender
@property
def age(self):
return self.__age
@property
def film(self):
return self.__film
@property
def specie(self):
return self.__specie
@name.setter
def name(self, name):
self.__name = name
@gender.setter
def gender(self, gender):
self.__gender = gender
@age.setter
def age(self, age):
self.__age = age
@film.setter
def film(self, film):
self.__film = film
@specie.setter
def specie(self, specie):
self.__specie = specie
def __eq__(self, character):
return self.name.__eq__(character.name)
def __str__(self):
clase = type(self).__name__
msg = "{0} => Name: {1}, Gender: {2}, Age: {3}, Film: {4}, specie: {5}"
return msg.format(clase, self.name, self.gender, self.age, self.film.title, self.specie)
def to_dictionary(self):
# Convierte la información de film en un diccionario
character_dict = {}
character_data = {}
character_data["gender"] = self.gender
character_data["age"] = self.age
character_data["film"] = self.film.title
character_data["specie"] = self.specie
character_dict.setdefault(self.name, character_data)
return character_dict |
ae40a0301bcf9785e4ab98e0b02044c888854f12 | cold-pumpkin/FC-Algorithms | /problems/section1/7490.0_만들기.py | 930 | 3.671875 | 4 | # 7490. 0 만들기
import copy
# 연산자 배열 채우기
def recursive(arr, n):
if len(arr) == n:
operators_list.append(copy.deepcopy(arr))
return
# 1) 공백
arr.append(' ')
recursive(arr, n)
arr.pop() # 연산자 조합 길이가 n인 경우 하나 빼기
# 2) 덧셈
arr.append('+')
recursive(arr, n)
arr.pop()
# 3) 뺄셈
arr.append('-')
recursive(arr, n)
arr.pop()
t = int(input())
for _ in range(t):
n = int(input())
nums = [i for i in range(1, n+1)]
operators_list = []
recursive([], n-1) # 연산자 채우기 (연산자 조합은 n-1개로 구성됨)
for operators in operators_list:
expr = ""
# 식 만들기
for i in range(n-1):
expr += str(nums[i]) + operators[i]
expr += str(nums[-1])
if eval(expr.replace(" ", "")) == 0:
print(expr)
print()
|
a662a3dbc476610bba4242e7609e59bd3a5856d7 | mjmccollister/ALGS200x | /MaximumPairwiseProduct.py3 | 216 | 3.703125 | 4 | # Uses python3
n = int(input())
a = [int(x) for x in input().split()]
largest_integer = max(a)
a.remove(largest_integer)
second_largest_integer = max(a)
result = largest_integer * second_largest_integer
print(result) |
8d28ef16fdae0a812f34a4e6123f61bce76dbe0c | The-Jay-M/CODE-NOUN | /python-jerry/lottery.py | 412 | 3.65625 | 4 | from random import randint
doNotPick= []
while (len(doNotPick) < 6):
generate= randint(1, 37)
if (generate in doNotPick):
pass
else:
doNotPick.append(generate)
#To print out values from the doNotPickList we need an index.
#Indexing starts from 0.
print(doNotPick[0])
print(doNotPick[1])
print(doNotPick[2])
print(doNotPick[3])
print(doNotPick[4])
print(doNotPick[5])
|
e2915d6ec52d4bf7bf4c7f2e1ca8cf38c635441a | t1610427/100knock | /chapter1/1syou01.py | 171 | 3.5 | 4 | target="パタトクカシーー"
ans=''
ans += target[0] #1文字目を連結
ans += target[2]
ans += target[4]
ans += target[6]
print("answer:{}".format(ans)) |
b535e91bdbf1e5a4c68ff4358a6c04982ac72f0c | BDafflon/adventofcode2019 | /day3/main.py | 1,009 | 3.671875 | 4 |
def calc_points_with_steps(path):
curx = cury = step = 0
directions = {'R': (1,0), 'L': (-1,0), 'U': (0,1), 'D': (0,-1)}
points = {}
for segment in path:
dx, dy = directions[segment[0]]
for _ in range(int(segment[1:])):
curx += dx
cury += dy
step += 1
if (curx, cury) not in points:
points[(curx, cury)] = step
return points
if __name__ == '__main__':
fichier = open('input.txt', 'r')
wire1_path, wire2_path = fichier.read().split()
wire1_path, wire2_path = wire1_path.split(','), wire2_path.split(',')
wire1_points = calc_points_with_steps(wire1_path)
wire2_points = calc_points_with_steps(wire2_path)
intersection_points = [point for point in wire1_points if point in wire2_points]
part1 = min(abs(x) + abs(y) for (x, y) in intersection_points)
print(part1)
part2 = min(wire1_points[point] + wire2_points[point] for point in intersection_points)
print(part2)
|
18be460d78a4a7177852a40e463d53a7be0c8dfb | miraceti/Python_script | /CodingPrivacy2.py | 486 | 3.6875 | 4 | import tkinter as tk
import PIL
from PIL import Image, ImageTk
root =tk.Tk()
root.title("resize image in label")
root.geometry("300x150")
#1rst approach
photo = tk.PhotoImage(file="mando2.png")
#2nd approach
photo2 = Image.open("mando2.png")
resized_image = photo2.resize((300,150), Image.ANTIALIAS)
converted_image = PIL.ImageTk.PhotoImage(resized_image)
label = tk.Label(root, image= converted_image, width=300, height=150, bg='black', fg='yellow' )
label.pack()
root.mainloop()
|
2e8c15faf3495b5925dadbefd311e30faaa79194 | xiaohuanlin/Algorithms | /Leetcode/1775. Equal Sum Arrays With Minimum Number of Operations.py | 3,283 | 4.40625 | 4 | '''
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.
Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
'''
from typing import *
import unittest
from heapq import heappush, heappop
class Solution:
def minOperations(self, nums1: List[int], nums2: List[int]) -> int:
nums2.sort()
nums1.sort()
total_sum1 = sum(nums1)
total_sum2 = sum(nums2)
if total_sum1 > total_sum2:
diff = total_sum1 - total_sum2
else:
diff = total_sum2 - total_sum1
nums1, nums2 = nums2, nums1
nums1_start = len(nums1) - 1
nums2_start = 0
count = 0
while diff > 0:
if nums1_start >= 0 and nums2_start < len(nums2):
increase = 6 - nums2[nums2_start]
decrease = nums1[nums1_start] - 1
if increase > decrease:
nums2_start += 1
diff -= increase
else:
nums1_start -= 1
diff -= decrease
elif nums1_start < 0 and nums2_start < len(nums2):
increase = 6 - nums2[nums2_start]
nums2_start += 1
diff -= increase
elif nums1_start >= 0 and nums2_start >= len(nums2):
decrease = nums1[nums1_start] - 1
nums1_start -= 1
diff -= decrease
else:
return -1
count += 1
return count
class TestSolution(unittest.TestCase):
def test_case(self):
examples = (
(([1,2,3,4,5,6], [1,1,2,2,2,2]), 3),
)
for first, second in examples:
self.assert_function(first, second)
def assert_function(self, first, second):
self.assertEqual(Solution().minOperations(*first), second,
msg="first: {}; second: {}".format(first, second))
unittest.main()
|
92a92f854c64f234fd322eaa4d7d1ee3c60dcd35 | abaah17/Programming1-examples | /w3s1_pick_your_flag.py | 1,938 | 3.890625 | 4 | # Basic example for keyboard control. 3 keys are linked to 3 functions, each function draws a flag
from aluLib import *
window_width = 1500
window_height = 900
# These functions are the same as the solution
def benin():
left_rectangle_width = window_width / 3
right_rectangle_height = window_height / 2
set_fill_color(0, 1, 0)
draw_rectangle(0, 0, left_rectangle_width, window_height)
set_fill_color(1, 1, 0)
draw_rectangle(left_rectangle_width, 0, 2 * left_rectangle_width, right_rectangle_height)
set_fill_color(1, 0, 0)
draw_rectangle(left_rectangle_width, right_rectangle_height, 2 * left_rectangle_width, right_rectangle_height)
def niger():
rectangle_height = window_height / 3
# Draw top rectangle
set_fill_color(1, 0.5, 0)
draw_circle(window_width/2, window_height/2, window_height/9)
draw_rectangle(0, 0, window_width, rectangle_height)
set_fill_color(0, 1, 0)
draw_rectangle(0, 2 * rectangle_height, window_width, rectangle_height)
def guinea():
rectangle_width = window_width / 3
set_fill_color(1, 0, 0)
draw_rectangle(0, 0, rectangle_width, window_height)
set_fill_color(1, 1, 0)
draw_rectangle(rectangle_width, 0, rectangle_width, window_height)
set_fill_color(0, 1, 0)
draw_rectangle(2 * rectangle_width, 0, rectangle_width, window_height)
# The main function draws flag only when a given key is pressed
def main():
# is_key_pressed takes one character as a parameter, and returns True or False,
# based on whether or not that character was printed in that frame.
if is_key_pressed("b"):
benin()
elif is_key_pressed("n"):
# Clear erases the screen. This is important for the Niger flag.
# What happens if you remove the call to clear?
clear()
niger()
elif is_key_pressed("g"):
guinea()
start_graphics(main, width=window_width, height=window_height) |
152b34f3f9419e16112b70f6c2a1274f146e9791 | amanda-pullan/COSC367-Artificial-Intelligence | /Labs/11 Games/alpha_beta.py | 1,905 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 20:01:21 2020
@author: Amanda
"""
from math import inf
def max_value(tree, alpha, beta):
"""Given a game tree, returns the utility of the root of
the tree when the root is a max node."""
if type(tree) is int:
return tree
v = -inf
for x in tree:
v = max(v, min_value(x, alpha, beta))
alpha = max(v, alpha)
if alpha >= beta:
return v
return v
def min_value(tree, alpha, beta):
"""Given a game tree, returns the utility of the root of
the tree when the root is a min node."""
if type(tree) is int:
return tree
v = inf
for x in tree:
v = min(v, max_value(x, alpha, beta))
beta = min(v, beta)
if alpha >= beta:
return v
return v
def max_action_value(game_tree):
"""Given a game tree, returns a pair where first element is
the best action and the second element is the utility of the
root of the tree when the root is a max node.
"""
if type(game_tree) is int:
return (None, game_tree)
max_actions = []
for i, subtree in enumerate(game_tree):
max_actions.append((i, min_value(subtree)))
max_actions.sort(key=lambda x: -x[1])
return max_actions[0]
def min_action_value(game_tree):
"""Given a game tree, returns a pair where first element is
the best action and the second element is the utility of the
root of the tree when the root is a min node.
"""
if type(game_tree) is int:
return (None, game_tree)
min_actions = []
for i, subtree in enumerate(game_tree):
min_actions.append((i, max_value(subtree)))
min_actions.sort(key=lambda x: x[1])
return min_actions[0]
def alpha_beta_search(tree):
v = max_action_value(tree, -inf, inf)
return v
print(alpha_beta_search([2, [-1, 5], [1, 3], 4])) |
cfccc5ac37858b6c2e4af5940860600517204d4d | v-sukt/misc_code | /pycode2/ex44c.py | 523 | 4.34375 | 4 | #!/usr/bin/env python2.7
"""This example is to demonstrate the inheritance - using parent's behaviour After/before changed child's behaviour
Internally calls tha parent function uspng super()"""
class Parent(object):
def altered(self):
print "Parent's altered()"
class Child(Parent):
def altered(self):
print "\nChild, before Parent altered()"
super(Child, self).altered()
print "Child, after Parent altered()"
child = Child()
parent = Parent()
parent.altered()
child.altered() |
43251bc844c701e640866b166aa62235285ec8b4 | kiwi-33/Programming_1_practicals | /p4-5/p5p4.py | 655 | 4.25 | 4 | number = int(input("Enter a number: "))
if number =0:
print ("Number is equal to 0")
elif 0<number>=20:
print ("Number is greater than 0 and less than or equal to 20")
elif 20<number>= 40:
print ("Number is greater than 20 and less than or equal to 40")
elif 40<number>= 60:
print ("Number is greater than 40 and less than or equal to 60")
elif 60<number>= 80:
print ("Number is greater than 60 and less than or equal to 80")
elif 80<number>= 100:
print ("Number is greater than 80 and less than or equal to 100")
elif number>100:
print ("Number is greater than 100")
elif number =0:
print ("Number is 0")
|
ddc4a671b5ab10d19c8c64702324c99dd9d9575e | smilezjw/LeetCode | /P01_Two Sum/TwoSum.py | 1,359 | 3.609375 | 4 | # _*_ coding:utf8 _*_
__author__ = 'smilezjw'
def twoSum(num, target):
#首先是我自己的写法。。弱爆了
# for n1 in num:
# for n2 in num:
# if n1 + n2 == target:
# index1 = num.index(n1)
# index2 = num.index(n2)
# found = True
# if found is True:
# return (min(index1,index2), max(index1, index2))
# else:
# return 'Not found!'
#一遍扫描num,看Hash表中的数有没有target - x,如果有则直接返回index,否则将x放入hash表中
dict = {} #构建Hash表
for i, n in enumerate(num):
if dict.get(target - n,None) != None:
return (dict[target - n] + 1, i + 1)
dict[n] = i
if __name__ == '__main__':
print twoSum(num=[0, 4, 3, 0], target=0)
print twoSum(num=[2, 7, 11, 15], target=9)
###############################################
# 1. Brute force ---- O(n^2) runtime, O(1) space
# Loop through each element x and find if there is another value that equals to target-x.
# As finding another value requires looping through the rest of value, its runtime complexity is O(n^2)
#
# 2. Hash table ---- O(n) runtime, O(n) space
# We could reduce the runtime complexity of looking aup a value to O(1) using a hash map that
# maps a value to its index. |
029229b707e7245c99049523dcfd845e2ea33a14 | deepakcr26/2017_02_PHILIPS_PYTHON | /Examples/ex12.py | 712 | 3.515625 | 4 | class Phone(object):
def __init__(self):
print("Constructing the Phone object...")
def info(self):
print("Currently no info available in Phone class")
class Camera(object):
def take_photo(self):
print("click click click..")
def take_photo_with_flash(self):
print("Lights ON")
self.take_photo()
__take_photo = take_photo
class MobilePhone(Phone, Camera):
def __init__(self):
super().__init__()
print("Constructing the MobilePhone object...")
def take_photo(self):
super().take_photo()
print("snap snap...")
if __name__ == "__main__":
mp = MobilePhone()
mp.info()
mp.take_photo_with_flash()
|
82eea78112abad83f606572256cc106ea9bdf0d0 | Tenebrar/codebase | /hacker/util.py | 730 | 3.84375 | 4 | def x_max(iterable, amount=1, key=None):
"""
Returns the largest items in the input
:param iterable: An iterable
:param amount: The amount of results
:param key: The key with which to compare items
:return: An iterable containing the 'amount' largest items in the 'iterable'
"""
return sorted(list(iterable), key=key)[:-amount-1:-1]
def x_min(iterable, amount=1, key=None):
"""
Returns the smallest items in the input
:param iterable: An iterable
:param amount: The amount of results
:param key: The key with which to compare items
:return: An iterable containing the 'amount' smallest items in the 'iterable'
"""
return sorted(list(iterable), key=key)[:amount]
|
c35a8a6a1d387bd6cb58116c5d7b4c59f9e980d4 | jankovicgd/gisalgorithms | /kd_tree/test.py | 383 | 4.0625 | 4 | # 1.1 Computational concerns for algorithms
# Listing 1.3: Binary search to find point p0 in a tree
# Import from kd_node
from kd_node import *
# Define points
pts =[Point(6,7), Point(4,6), Point(9,4), Point(2,3), Point(3,7), Point(7,4), Point(9,6)]
print(str(pts))
root = kd_node(p=pts[0])
kd_tree = kd_tree(root)
for p in pts[1:]:
kd_tree.add_point(p)
print(str(kd_tree))
|
3cae0c98b4241809dc85082969c570711b951220 | sudhirmd005/PYTHON-excerise-files- | /dec_with_para.py | 771 | 3.78125 | 4 | # This is the example of decorators with parameter
import time
def deccorator_parameter(*args, **kwargs):
begin = time.time()
print(" this is the inital start of the decorator parameter")
def inside(argu): # defining the wrapper function inside the decorator function
print(" this is begining of the wrapper function")
argu() # call of another function inside wrapper function
print(" this is the decorator argument we were talking about", kwargs['about'])
end = time.time()
print(" end of the wrapper function", argu.__name__, end - begin)
return inside
@deccorator_parameter( about = "exmaple of deccorator_parameter")
def funv():
print(" this text is printed inside the wrapper function")
|
8ecd5cc616ca257aa7c16e4aacbe638d1bab7479 | stebbinscp/Example-Class-Work | /Chicago_Schools_cvs.py | 4,301 | 3.5 | 4 | from math import asin, sin, cos, sqrt, radians, degrees
import csv
from webbrowser import open_new_tab
EARTH_RADIUS = 3961
class School:
def __init__(self, data):
self.id = data.get("School_ID")
self.name = data.get("Short_Name")
self.network = data.get("Network")
self.address = data.get("Address")
self.zip = data.get("Zip")
self.phone = data.get("Phone")
self.grades = data.get("Grades").split(", ")
self.location = Coordinate(data.get("Lat"), data.get("Long"))
return
def open_website(self):
"""Take in the School object and open the url with the specified school ID."""
url = "http://schoolinfo.cps.edu/schoolprofile/SchoolDetails.aspx?SchoolId="
open_new_tab(url+self.id)
def distance(self,coordinate):
"""Take the distance between the School object and another's coordinate."""
coord_lat = radians(coordinate.lat)
coord_long = radians(coordinate.long)
lat = radians(self.location.lat)
longi = radians(self.location.long)
distance = 2*EARTH_RADIUS*asin( sqrt( sin( ( coord_lat-lat)/2)**2 + \
cos(longi)*cos(coord_long)*sin((coord_long-longi)/2)**2))
return distance
def full_address(self):
"""Returns the full address of the School object"""
address = self.address + "\nChicago" + "\nIllinois" + f"\n{self.zip}"
return address
class Coordinate:
def __init__(self, latitude, longitude):
self.lat = float(latitude)
self.long = float(longitude)
self.lat_long = self.as_degrees()
return
def distance(self, coordinate):
"""Function employs the as_degrees function to convert the coordinates given
from degrees to radians in order to employ the Haversine formula to calculate
and return the distance between two schools"""
distance = 2*EARTH_RADIUS*asin( sqrt( sin( ( coordinate.lat_long[0]-self.lat_long[0])/2)**2 + \
cos(self.lat_long[0])*cos(coordinate.lat_long[0])*sin((coordinate.lat_long[1]-self.lat_long[1])/2)**2))
return distance
def as_degrees(self):
"""Employs the math radians function to return a tuple of radian (lat,long)"""
latitude = radians(self.lat)
longitude = radians(self.long)
return (latitude, longitude)
def show_map(self):
url = "http://maps.google.com/maps?q="
open_new_tab(url+str(self.lat)+","+str(self.long))
class CPS:
def __init__(self, filename):
school_dictionaries = []
schools = []
with open(filename, newline='\n') as f:
reader = csv.DictReader(f)
# # for i in range()
for row in reader:
school_dictionaries.append(row)
# each row is a dictionary with the school's info
for item in school_dictionaries:
schools.append(School(item))
# print(schools[1].location.lat)
self.schools = schools
def nearby_schools(self, coordinate, radius=1.0):
"""Function returns a list of school instances within the radius
of the given instance coordinate. The coordinate must
be of the class Coordinate"""
result = []
for school in self.schools:
if school.location.distance(coordinate) <= 1.0:
result.append(school)
return result
def get_schools_by_grade(self, *grades):
"""Function returns a list of school instances which offer all
the grades listed in the grades argument. Grades must be strings."""
result = []
grades_wanted = list(grades)
for school in self.schools:
if all(item in grades for item in grades_wanted) == True:
result.append(school)
return result
def get_schools_by_networks(self, network):
"""Function returns a list of school instances which are within the listed
network. Network must be a string"""
result = []
for school in self.schools:
network = school.network
if network == network:
result.append(school) # doesn't append the school name
return result
if __name__ == "__main__":
obj = CPS("schools.csv") |
90a7cddaa492df26fbac0ef47f1980e16f99b2ff | zhaocheng1996/pyproject | /algorithm_test/saima/股神.py | 799 | 4.09375 | 4 | '''
有股神吗?
有,小赛就是!
经过严密的计算,小赛买了一支股票,他知道从他买股票的那天开始,股票会有以下变化:第一天不变,以后涨一天,跌一天,涨两天,跌一天,涨三天,跌一天...依此类推。
为方便计算,假设每次涨和跌皆为1,股票初始单价也为1,请计算买股票的第n天每股股票值多少钱?
输入
输入包括多组数据;
每行输入一个n,1<=n<=10^9 。
样例输入
1
2
3
4
5
输出
请输出他每股股票多少钱,对于每组数据,输出一行。
样例输出
1
2
1
2
3
'''
while 1 :
x =int(input())
k = 3
n = 3
while x-k>=n:
n+=k
k+=1#k就是减号的数量
if x<3:
print(x)
else:
print(int(x-(k-2)*2))
|
0ee290372503fc1aa25aba4471d8d40dcbc525c6 | monkeylyf/interviewjam | /str/leetcode_Word_Pattern.py | 1,469 | 3.9375 | 4 | """Word pattern
leetcode
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter
in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
"""
class Solution(object):
def wordPattern(self, pattern, string):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
strings = string.split()
if len(pattern) != len(strings):
return False
# A string cannot be mapped to more than one different char.
used = set()
char_pat = [None] * 26
for i, char in enumerate(pattern):
idx = ord(char) - 97
pat = char_pat[idx]
word = strings[i]
if pat is None:
if word in used:
return False
else:
char_pat[idx] = word
used.add(word)
elif char_pat[idx] != strings[i]:
return False
else:
pass
return True
def main():
sol = Solution()
assert sol.wordPattern('abba', 'dog cat cat dog')
if __name__ == '__main__':
main()
|
2b4036f84c1cbe177a97e3a749a4e5e66b09b0fb | Tarun4444/Algorithms | /merge_overlapping_interval.py | 312 | 3.765625 | 4 | def merge(A):
B=[]
A.sort(key=lambda x:x[0])
B.append(A[0])
for i in range(1,len(A)):
if A[i][0] > B[-1][1]:
B.append([ A[i][0],A[i][1] ])
elif B[-1][1] < A[i][1]:
B[-1][1]=A[i][1]
print(B)
merge( [ (1, 10), (2, 9), (3, 8), (4, 7), (5, 6), (6, 6) ])
|
e5df21812c6c5107ce39ea43d4221dab17d66ca8 | ghldbssla/Python | /개념 배우기/day06/Comprehention.py | 388 | 3.765625 | 4 | #comprehention.py
#0~9가 담긴 리스트
#arData=[i for i in range(10)]
#print(arData)
#1~1000중 짝수만 담긴 리스트
#arData=[i for i in range(1,1000,1) if i%2==0]
#print(arData)
#(1,2),(1,4),(1,6),(2,2),(2,4),(2,6),(3,2),(3,4),(3,6)--1
#arData=[(i,j) for i in range(1,4,1) for j in range(2,8,2)]
#print(arData)
#arData=[(i//3+1,(i%3+1)*2) for i in range(9)]
#print(arData)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.