blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4a98e5d20a21a4dd60e06526fccfd887460e8824 | pyao7-code/ops435-Python | /lab7/lab7a.py | 1,678 | 3.625 | 4 | #!/usr/bin/env python3
# Store one IPv4 address
class IPAddress:
# You probably want to construct it as a string, but you may want to store it as the four octets separately:
def __init__(self, address):
self.address = str(address).split('.')
# Is this address from a private subnet? e.g. starting with 192.168. or 10.
def isPrivate(self):
if self.address[0] == '192':
if self.address[1] == '168':
return True
else:
return False
elif self.address[0] == '10':
return True
else:
return False
# Store information about a person, perhaps someone you'll be adding as a user to a system:
class Person:
def __init__(self,name):
self.name = str(name)
self.name_list = []
def add_person (self):
(self.name_list).append(self.name)
return self.name_list
# Store information about different models from a specific manufacturer. Perhaps how many seats they have and how much fuel they use and the price range:
# Doesn't have to be BMW, pick any car or bike manufacturer:
class BMWModel:
def __init__(self,models):
self.models = str(models)
self.info = {}
def add_seat (self,seat,quantity):
self.info[seat] = int(quantity)
return self.info
def add_fuel (self,fuel,number):
self.info[fuel] = int(number)
return self.info
# Store information about a specific car that someone owns.
# Spend some time thinking why this class is different than the one above, and whether it has to be different:
class Car:
def __init__(self,brand,owner):
self.brand = str(brand)
self.owner = str(owner)
def info(self):
return "self.owner: self.brand"
|
1612685e98df2c6a83bf2415fa54206b14713cb8 | tiagolok/PCAP | /read_text_file_at_console.py | 171 | 3.53125 | 4 | # opening tzop.txt in read mode, returning it as a file object
stream = open("tzop.txt", "rt", encoding = "utf-8")
# printing the content of the file
print(stream.read())
|
f482b9ed580f9f365ecf057d9546ea309d5e996a | abdalazzezzalsalahat/amman-python-401d3 | /class-30/demo/hashmap/hashmap.py | 1,957 | 4.1875 | 4 | from linked_list import LinkedList
class Hashmap:
"""
This class simulates the functionality of the hashmap.
Run 'python -m doctest -v hashmap.py' in terminal in action
Hover over Hashmap class definition to also see doctest in action
Try breaking expected values and see what happens
Use doctest WITH unit tests, NOT INSTEAD of unit tests
Some tests:
>>> hashmap = Hashmap(1024)
>>> hashmap.set('ahmad', 30)
>>> hashmap.set('silent', True)
>>> hashmap.set('listen', 'to me')
>>> for item in hashmap._buckets:
... if item:
... item.display()
[['silent', True], ['listen', 'to me']]
[['ahmad', 30]]
"""
def __init__(self, size=1024):
self.size = size
self._buckets = [None] * size
def _hash(self, key):
"""
Accepts the key and returns the index where this key should be stored
"""
sum = 0
for char in key:
sum += ord(char)
h = ( sum * 19) % self.size
return h
def add(self, key, value):
index = self._hash(key)
if not self._buckets[index]:
self._buckets[index] = LinkedList()
self._buckets[index].add([key, value])
def find(self, key):
"""
Accepts a key and returns the value for the key if it exists in our hashmap
"""
index = self._hash(key)
bucket = self._buckets[index]
# traverse the link list
current = bucket.head
while current:
if current.value[0] == key:
return current.value[1]
current = current.next
raise KeyError("Key not found", key)
def delete(self, key):
"""
Delete the value a the key
"""
pass
def contains(self, key):
"""
Return true if there is a value in the hashmap with that key or false otherwise
"""
pass
|
e6dc27dfeaf193cefe1caf9cfe0d72f5ce3d7520 | antoshkaplus/CompetitiveProgramming | /ProjectEuler/001-050/43.1.py | 974 | 3.515625 | 4 | """
The number, 1406357289, is a 0 to 9 pandigital number because it
is made up of each of the digits 0 to 9 in some order,
but it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
"""
divs = [1,1,1,2,3,5,7,11,13,17]
def choose_next_digit(seq,rest,i,divs):
res = 0
if i == 10:
res = int(seq)
else:
s = seq[len(seq)-2:]
for j,r in enumerate(rest):
if not (int(s+r)%divs[i]):
res += choose_next_digit(seq+r,rest[:j]+rest[j+1:],i+1,divs)
return res
rest = "0123456789"
sum = choose_next_digit("",rest,0,divs)
print sum
|
c97559f410414c5a77e41e1df1fd944d191f1096 | yonicarver/ece203 | /Lab/Lab 9/car.py | 556 | 3.640625 | 4 | class Car:
def __init__(self,gal,mpg):
self.mpg = float(mpg)
self.gal = float(gal)
def drive(self,miles):
self.miles = miles
if self.mpg*self.gal >= miles:
print 'Enough gas'
else:
print 'Not enough gas'
def addGas(self,gasin):
self.gal += gasin
def getGasLevel(self):
self.gal -= self.miles/self.mpg
print '%s gallons remaining' % self.gal
hybrid = Car(0,50)
hybrid.addGas(2)
hybrid.drive(75)
hybrid.getGasLevel()
|
b20cb36bbd69caca2b628cfa3804b668ecffc417 | agustinavila/Curso-Python-UNSAM | /Clase02/diccionario_geringoso.py | 889 | 3.953125 | 4 | # Agustin Avila
# tinto.avila@gmail.com
# 17/8/21
def conversor_geringoso(palabra):
vocales = 'aAeEiIoOuU'
palabra_gerin = ''
for caracter in palabra:
palabra_gerin += caracter
if caracter in vocales:
palabra_gerin += 'p' + caracter.lower()
return palabra_gerin
print("Este programa genera un diccionario de palabras con su equivalente en geringoso.")
frase = str(input("Por favor, ingrese una frase: "))
palabras = frase.split(" ") # Genera una lista con las palabras de la frase
palabras_dict = {} # Genera el diccionario vacio
for palabra in palabras:
palabras_dict[palabra] = conversor_geringoso(palabra) # Asigna a cada palabra su equivalente geringoso
print(palabras_dict)
# Ejemplo de salida:
# Por favor, ingrese una frase: banana manzana mandarina
# {'banana': 'bapanapanapa', 'manzana': 'mapanzapanapa', 'mandarina': 'mapandaparipinapa'}
|
f02bc45f11a546a48311cca2923114d7913d13ef | ConnorC11/Min_Edit_Distance | /minEditDist.py | 1,044 | 3.96875 | 4 | '''
Function minEditDistance that returns the minimum edit distance
between two words
Usage:
minEditDistance(str1,str2)
'''
def minEditDistance(str1, str2):
if str1 is None or str2 is None:
return "strings can't be None"
n = len(str1)
m = len(str2)
if n < 1:
return m
if m < 1:
return n
distance = [[0 for i in range(0,m+1)]for k in range(0,n+1)]
# Initialization:
# the zeroth row and col is the distance from the empty string
distance[0][0] = 0
for i in range(1,n+1):
distance[i][0] = distance[i-1][0] + 1
for j in range(1,m+1):
distance[0][j] = distance[0][j-1] + 1
# Recurrence relation
for i in range(1,n+1):
for j in range(1,m+1):
sub = 2
if str1[i-1] == str2[j-1]:
sub = 0
distance[i][j] = min(distance[i-1][j]+1,
distance[i-1][j-1]+sub,
distance[i][j-1]+1)
# Termination
return distance[n][m]
|
166202bff46dfbbded6ddf23a04978a98e1e1e89 | naruto001/python | /01python_test/22.py | 563 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def quadratic(a,b,c):
q=b*b-4*a*c
if q>0:
x1=(-b+math.sqrt(q))/a/2
x2=(-b-math.sqrt(q))/a/2
return x1,x2
elif q==0:
x1=-b/a/2
x2=x1
return x1,x2
else:
pass
return ()
print('input a,b,c :')
a=float(input('a:'))
b=float(input('b:'))
c=float(input('c:'))
q=quadratic(a,b,c)
q=set(list(q))
# print('q =',q)
if len(q)==2:
for x in q:
print(x)
elif len(q)==1:
for x in q:
print(x)
else:
print('None') |
f724f4d8c50a6b3435f8f5b9524d00458114aa14 | here0009/LeetCode | /Python/1182_ShortestDistancetoTargetColor.py | 3,660 | 4.03125 | 4 | """
You are given an array colors, in which there are three colors: 1, 2 and 3.
You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.
Example 1:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]]
Output: [3,0,3]
Explanation:
The nearest 3 from index 1 is at index 4 (3 steps away).
The nearest 2 from index 2 is at index 2 itself (0 steps away).
The nearest 1 from index 6 is at index 3 (3 steps away).
Example 2:
Input: colors = [1,2], queries = [[0,3]]
Output: [-1]
Explanation: There is no 3 in the array.
Constraints:
1 <= colors.length <= 5*10^4
1 <= colors[i] <= 3
1 <= queries.length <= 5*10^4
queries[i].length == 2
0 <= queries[i][0] < colors.length
1 <= queries[i][1] <= 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-target-color
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from bisect import bisect_left
from collections import defaultdict
class Solution:
def shortestDistanceColor(self, colors, queries):
index_dict = defaultdict(list)
for i,v in enumerate(colors):
index_dict[v].append(i)
res = []
# print(index_dict)
for i,c in queries:
if c not in index_dict:
res.append(-1)
else:
lst = index_dict[c]
j = bisect_left(lst, i)
diff = float('inf')
if j < len(lst):
diff = min(diff, abs(lst[j] - i))
if j > 0:
diff = min(diff, abs(lst[j-1] -i))
# print(i, j, diff)
res.append(diff)
return res
from bisect import bisect_left
from collections import defaultdict
class Solution:
def shortestDistanceColor(self, colors, queries):
index_dict = defaultdict(list)
for i,v in enumerate(colors):
index_dict[v].append(i)
res = []
# print(index_dict)
for i,c in queries:
if c not in index_dict:
res.append(-1)
else:
lst = index_dict[c]
j = bisect_left(lst, i)
res.append(min((abs(lst[x] - i) for x in [j, j-1] if 0 <= x < len(lst))))
return res
from collections import defaultdict
class Solution:
def shortestDistanceColor(self, colors, queries):
length = len(colors)
dp_left = [[float('inf')]*length for _ in range(4)]
dp_right = [[float('inf')]*length for _ in range(4)]
dp_left[colors[0]-1][0] = 0
dp_right[colors[-1]-1][-1] = 0
for i in range(1, length):
for j in range(3):
dp_left[j][i] = dp_left[j][i-1] + 1
dp_left[colors[i]-1][i] = 0
for i in range(length-2, -1, -1):
for j in range(3):
dp_right[j][i] = dp_right[j][i+1] + 1
dp_right[colors[i]-1][i] = 0
# for row in dp_left:
# print(row)
# for row in dp_right:
# print(row)
res = []
for i, c in queries:
tmp = min(dp_left[c-1][i], dp_right[c-1][i])
if tmp == float('inf'):
res.append(-1)
else:
res.append(tmp)
return res
S = Solution()
colors = [1,1,2,1,3,2,2,3,3]
queries = [[1,3],[2,2],[6,1]]
print(S.shortestDistanceColor(colors, queries))
colors = [1,2]
queries = [[0,3]]
print(S.shortestDistanceColor(colors, queries))
|
36af7634eba1cff56f26cfa67e800ba66f5c63fb | Swagat-Kumar/Competitive_Codes_Python | /BasicsOfStringManipulation/UpUp.py | 475 | 3.765625 | 4 | st = list(input())
ans = ''
word = ''
for s in st:
if s.isalpha() or s == '[':
word += s
else:
if len(word) != 0:
if len(word) != 1:
word = word[0].upper()+word[1:]
else:
word = word[0].upper()
ans += word
word = ''
ans += s
if len(word) != 0:
if len(word) != 1:
word = word[0].upper()+word[1:]
else:
word = word[0].upper()
ans += word
print(ans)
|
b8593ff8e10c963ad2a3ddaebc862311c1786f66 | cetinkerem/CodeHS_Answers | /1615.py | 683 | 3.859375 | 4 | import random
# These lists will be used as tests in your check_values function
computer_list = [1,2,3,5];
user_list = [2,7,3,4];
def check_values(user, computer):
colors = []
shuffled = user[:]
random.shuffle(shuffled)
for number in shuffled:
if number in computer:
input_number_pos = user.index(number)
computer_number_pos = computer.index(number)
if input_number_pos == computer_number_pos:
colors.append("RED")
else:
colors.append("WHITE")
else:
colors.append("BLACK")
return colors
print check_values(user_list, computer_list)
|
899d98c6f87f40d00f6dc88a805b9f028133b0ee | johnhshapiro/Algorithms | /assignment3/5eight_queens.py | 3,475 | 4.15625 | 4 | """John Shapiro
5. Eight Queens
Adapted from https://github.com/sol-prog/N-Queens-Puzzle
Finds all 92 solutions of the 8 queens problem using back tracking.
Times how long it takes to find all 92 solutions when using random starting positions for various numbers of k < 9 queens.
"""
import random
import time
import copy
solutions = 0
boards = []
def solve(start_row):
"""Solve the n queens puzzle and print the number of solutions"""
global solutions
global boards
boards = []
solutions = 0
while solutions < 92:
positions = legal_starting_k_queens(start_row)
put_queen(positions, start_row)
def legal_starting_k_queens(start_row):
"""Check if the starting positions of k glued queens are legal
Arguments:
start_row {int} -- Number of rows to glue random queens on
Returns:
[int] -- List of legal starting positions
"""
while True:
# place k queens
positions = random.sample(range(8), start_row)
positions.extend([-1] * (8 - start_row))
current_row = 0
for row in range(start_row):
if check_place(positions, current_row, positions[row]):
current_row = current_row + 1
if current_row == start_row:
return positions
def put_queen(positions, target_row):
"""
Try to place a queen on target_row by checking all N possible cases.
If a valid place is found the function calls itself trying to place a queen
on the next row until all N queens are placed on the NxN board.
"""
global solutions
global boards
# Base (stop) case - all N rows are occupied
if target_row == 8:
# show_full_board(positions)
# show_short_board(positions)
if positions not in boards:
boards.append(copy.copy(positions))
solutions += 1
else:
# For all N columns positions try to place a queen
for column in range(8):
# Reject all invalid positions
if check_place(positions, target_row, column):
positions[target_row] = column
put_queen(positions, target_row + 1)
def check_place(positions, ocuppied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed queens (check column and diagonal positions)
"""
for i in range(ocuppied_rows):
if positions[i] == column or \
positions[i] - i == column - ocuppied_rows or \
positions[i] + i == column + ocuppied_rows:
return False
return True
def show_full_board(positions):
"""Show the full NxN board"""
for row in range(8):
line = ""
for column in range(8):
if positions[row] == column:
line += "Q "
else:
line += ". "
print(line)
print("\n")
def show_short_board(positions):
"""
Show the queens positions on the board in compressed form,
each number represent the occupied column position in the corresponding row.
"""
line = ""
for i in range(8):
line += str(positions[i]) + " "
print(line)
def run_tests():
"""Run each number of k glued queens 10 times and print the elapsed time.
"""
for test in range(9):
start = time.time()
for i in range(10):
solve(test)
elapsed = time.time() - start
print("{:.4}".format(elapsed))
run_tests() |
050a194e6e48f008de64fe71619704b256ee54c1 | client95/s.p.algorithm | /week_2/07_is_existing_target_number_binary.py | 296 | 3.90625 | 4 | finding_target = 2
finding_numbers = [0, 3, 5, 6, 1, 2, 4]#순차배열이 아님
#이진탐색을 할 때는 정렬이 되어 있어야함
def is_exist_target_number_binary(target, numbers):
return 1
result = is_exist_target_number_binary(finding_target, finding_numbers)
print(result)
|
1ea1c761c1363d6630370bdff6a9b820af7ff03f | Noki777/PYTHONEXERCISES | /klienthdictionary.py | 389 | 4.125 | 4 | print ("welcome")
Nokilist =[]
add= input("ADD SOMETHING INTO THE LIST YES OR NO?:")
while add.lower() == "y":
item = input("Enter your item to the lisT:")
Nokilist.append(item)
add = input("Want to add your Shopping list ? YES OR NO:")
print(">")
print("Here is your alphabetized List")
Nokilist.sort()
for listitem in Nokilist:
print(">"+listitem)
|
1a835e03b4902fe3321682d7960068675fa469f5 | tseiiti/curso_em_video | /mundo_1/ex011.py | 510 | 3.578125 | 4 | from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 011:
Faça um programa que leia a largura e a altura de uma parede em
metros, calcule a sua área e a quantidade de tinta necessária para
pintá-la, sabendo que cada litro de tinta, pinta uma área de 2m².
''')
n1 = float(input('Digite a largura da parede: '))
n2 = float(input('Digite a altura da parede: '))
print('a área é: {:.2f}'.format(n1 * n2))
print('precisa de {:.2f} litros de tinta'.format(n1 * n2 / 2))
|
c3baf4cee558d36f29eba20cf0a8d8cb51c1826c | pavdmyt/GolangTraining | /my_solutions/section_14_15_exercises/06_project_euler_problem/euler7.py | 558 | 3.90625 | 4 | """
Problem 7. 10001st prime.
http://static.projecteuler.net/problem=7
"""
import math
def is_prime(num):
"""
Checks that given number is a prime number.
"""
if num <= 3:
return num == 2 or num == 3
for i in range(5, int(math.sqrt(num)) + 1, 6):
if num % i == 0 or num % (i + 2) == 0:
return False
return True
def main():
counter = 1
num = 1
while counter < 10001:
num += 2
if is_prime(num):
counter += 1
print(num)
if __name__ == '__main__':
main()
|
1a291a48eac89b50c0a2c1ddf5fd560f93f36be8 | itskeithstudent/Programming-and-Scripting-52167-Weekly-Assignments | /Week 6 Assignment.py | 2,069 | 4.625 | 5 | # Keith Ryan
# Week 6 Assignment
# function to get square root of user supplied number
#this function takes an original number and gets the square root of it
def sqrt(original_num):
print(f"\nYou entered - {original_num}")
#set square_root equal to half of the original number, this var will update as it is reassigned as part of calc. and will continue to do so till it is equal to temp
square_root = original_num/2
temp = 0
#temp is reassigned once in the loop to be equal to square_root
while (square_root!=temp):
temp = square_root
print(temp)
#by repeatedly approximating a value we get closer and closer to the square root, we can say we have found the square root when the result
#of the square_root calculation is the same as it was on the last loop
#e.g. say we are getting square root of 9 but we've looped to point where when temp is 3 (meaning last loops square_root value was also 3)
# ((9/3) + 3)/2 => 6/2 => 3
square_root = ((original_num/temp) + temp)/2
print(square_root)
#num takes a float value as the input
num = float(input("Enter a num to get square root of it: "))
sqrt(num)
#The above doesn't take too many loops to execute, please see below for some examples
'''
You entered - 9.0
4.5
3.25
3.0096153846153846
3.000015360039322
3.0000000000393214
3.0
3.0
You entered - 9.999
4.9995
3.49975
3.178405609329238
3.1621612670224426
3.1621195426076047
3.1621195423323263
3.1621195423323263
You entered - 100000000000.0
50000000000.0
25000000001.0
12500000002.5
6250000005.25
3125000010.625
1562500021.3125
781250042.6562495
390625085.32812124
195312670.66403267
97656591.33179264
48828807.664106764
24415427.817737076
12209761.79434379
6108975.981158149
3062672.6683637337
1547661.9443316166
806137.7689977181
465093.0222119024
340051.88661601284
317062.32795380044
316228.8643712705
316227.7660187454
316227.7660168379
316227.7660168379
'''
#could also do this as sqrt(int(input("Enter a num to get square root of it: "))), but I think this is less readable |
2fade0326ace63c592ce8d233cc84ee87e9d82f2 | Aasthaengg/IBMdataset | /Python_codes/p02629/s503507784.py | 275 | 3.5 | 4 | def solve():
# ref. https://drken1215.hatenablog.com/entry/2020/06/21/225500
N = int(input())
ans = ''
while N > 0:
N -= 1
N,digit = divmod(N,26)
ans += chr(ord('a') + digit)
print(ans[::-1])
if __name__ == "__main__":
solve() |
5cd51dd6703f5dc07a65f9114fee8b45bfefb084 | pvcraven/arcade_book | /unused/xx_review/test_03.py | 685 | 3.640625 | 4 | # Write a function called "f" that will pass all the tests below:
# --- Tests. Do not change anything below this line. ---
# Write your code above the line to pass all the tests.
if f(10, 10, 1) == 20:
print("Test 1 passed")
else:
print("Test 1 failed")
if f(15, 10, 1) == 25:
print("Test 2 passed")
else:
print("Test 2 failed")
if f(10, 10, 2) == 10:
print("Test 3 passed")
else:
print("Test 3 failed")
if f(10, 10, 10) == 2:
print("Test 4 passed")
else:
print("Test 4 failed")
if f(4, 6, 2) == 5:
print("Test 5 passed")
else:
print("Test 5 failed")
if f(150, 50, 50) == 4:
print("Test 6 passed")
else:
print("Test 6 failed")
|
2a5c50df487f6701640e8eb8db4799955d76bcff | MRALAMs/first-project | /reza1/cp3 | 889 | 3.53125 | 4 | #! /usr/bin/python3
class player:
def __init__ (self):
self.level=1
self.hp=100
def __str__ (self):
return ('this is a {}'.format(self.race))
def levelup(self):
self.level+=1
self.hp+=10
class human(player):
def __init__ (self):
player. __init__ (self)
self.hp=200
class elf(player):
def levelup(self):
player.levelup(self)
self.level +=1
self.hp +=5
class superH(human,elf):
pass
ali = human()
mamad = elf()
reza = superH()
print("health point reza ",reza.hp)
print("level reza ",reza.level)
reza.levelup()
print("level reza ",reza.level)
print("health point reza ",reza.hp)
print("health point reza ",mamad.hp)
mamad.levelup()
print("level mamad ",mamad.level)
print("health point mamad ",mamad.hp)
print("health point ali ",ali.hp)
ali.levelup()
print("health point ali ",ali.hp)
|
3fb1b2993424cc0eb7d1147a63632313cdaf1ee0 | AshWije/Neural-Networks-In-Python | /WithTensorFlow/MNISTFashion_CNN.py | 2,861 | 3.859375 | 4 | # MNISTFashion_CNN.py
#
# Description:
# Creates a convolutional neural network model in TensorFlow designed for
# the MNIST-fashion data set reduced to 6,000 images and shrunk to size 7x7.
#
# The size is shrunk in order to better understand the methods that can be
# utilized for a neural network to perform well with limited data.
#
# The model's layer details are discussed below:
# 1. MaxPool2D, 4x4 <- reduce images to 7x7 size
# 2. Conv2D, 2x2, 128
# - ReLU activation
# 3. Conv2D, 2x2, 64
# - ReLU activation
# 4. Conv2D, 2x2, 32
# - ReLU activation
# 5. Dropout, 0.4
# 6. Flatten
# 7. Dense, 128
# - ReLU activation
# 8. Dropout, 0.5
# 9. Dense, 10
# - Softmax activation
#
# Post parameter and architecture tuning, this model was shown to perform the
# best. After being trained for 125 epochs with Adam as the optimizer and sparse
# categorical cross entropy as the loss, the final accuracy achieved is 81.47%.
import tensorflow as tf
import numpy as np
# For timing
import time
start_time = time.time();
# Set seeds for pseudo-randomness
from numpy.random import seed
seed(1)
tf.random.set_seed(1)
# Reading training data
print("Reading training data")
x_train = np.loadtxt("trainX.csv", dtype="uint8")
.reshape(-1,28,28,1) # (6000,28,28,1)
y_train = np.loadtxt("trainY.csv", dtype="uint8") # (6000)
# Pre processing training data
print("Preprocessing training data")
preprocess = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.Rescaling(1.0/255.0)
])
x_train = preprocess(x_train)
# Create training model
model = tf.keras.models.Sequential([
tf.keras.layers.MaxPool2D(4, 4, input_shape=(28,28,1)),
tf.keras.layers.Conv2D(128, (2,2), padding='same', kernel_initializer='he_normal', activation=tf.nn.relu),
tf.keras.layers.Conv2D(64, (2,2), padding='same', activation=tf.nn.relu),
tf.keras.layers.Conv2D(32, (2,2), padding='same', activation=tf.nn.relu),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Training
print("Training")
model.fit(x_train, y_train, epochs=125)
# Reading testing data
print("Reading testing data")
x_test = np.loadtxt("testX.csv", dtype="uint8")
.reshape(-1,28,28,1)
y_test = np.loadtxt("testY.csv", dtype="uint8")
# Pre processing testing data
print("Preprocessing testing data")
x_test = preprocess(x_test)
# Evaluating
print("Evaluating")
model.evaluate(x_test, y_test) |
e05e1084e589383fdeefd5eff456577bcd7fa4f1 | nihalgaurav/Python | /Python_Assignments/Assignment_4/Ques1.py | 300 | 4.25 | 4 | # Ques 1. Write a program to create a tuple with different data types and do the following operations.
# Find the length of tuples
t=('Poonam','Nikhil',48,52,'Avleen',4.5,5.8,100,'Priyank',1000000.00,26357,2.5)
print("\n")
print(t)
print("\n")
print("Lenght of Tuple is: ",len(t)) |
9ee8a05bef4398de2e4b628b3660ecf38a98037b | JenniferCallahan/LTP2 | /Assignment 2/rat methods.py | 2,296 | 4.3125 | 4 | class Rat:
""" A rat caught in a maze. """
# methods have self as first parameter, by convention -- this refers to
#the object being initialized, here a rat
def __init__(self, symbol, row, col):
""" (Rat, str, int, int) -> NoneType
The first parameter represents the rat to be initialized, the second
parameter represents the 1-character symbol for the rat, the third
parameter represents the row where the rat is located, and the fourth
parameter represents the column where the rat is located.
>>> ratty = Rat('L', 1, 3)
>>> ratty.symbol
'L'
>>> ratty.row
1
>>> ratty.col
3
>>> ratty.num_sprouts_eaten
0
"""
# Initialize the rat's 4 instance variables -- create a variable by this
# name inside the object that 'self' refers to
self.symbol = symbol
self.row = row
self.col = col
self.num_sprouts_eaten = 0
def set_location(self, row_loc, col_loc):
"""(Rat, int, int) -> NoneType
The first parameter represents a rat, the second represents a row,
and the third represents a column."""
#Set the rat's row and col instance variables to the given row
#and column.
self.row = row_loc
self.col = col_loc
def eat_sprout(self):
"""(Rat) -> NoneType
The first parameter represents a rat. Add one to the rat's instance
variable num_sprouts_eaten."""
self.num_sprouts_eaten += 1
def __str__(self):
"""(Rat) -> str
The first parameter represents a rat. Return a string representation
of the rat, in this format:
symbol at (row, col) ate num_sprouts_eaten sprouts.
>>>rat1 = Rat('R', 1, 3)
>>>rat1.__str__()
'R at (1,3) ate 2 sprouts.'
"""
return '{0} at ({1},{2}) ate {3} sprouts.'.format(self.symbol, self.row,\
self.col, self.num_sprouts_eaten)
# Do not put a newline character ('\n') at the end of the string
# how do I check this?
#>>> ratty = Rat('L', 1 ,3)
#>>> ratty.row
#1
#>>> ratty.symbol
#'L'
#>>> ratty.col
#3
#>>> ratty.num_sprouts_eaten
#0
#>>> ratty.eat_sprout()
#>>> ratty.num_sprouts_eaten
#1
#>>> ratty.eat_sprout()
#>>> ratty.num_sprouts_eaten
#2
#>>> ratty.set_location(2,4)
#>>> ratty.row
#2
#>>> ratty.col
#4
#>>> ratty.__str__()
#'L at (2,4) ate 2 sprouts.'
if __name__ == '__main__':
import doctest
doctest.testmod()
|
10021110021a6c1acabb8cc9e94a5aaa301df8eb | Praful-a/Python-Programming | /hackerRank/if_else.py | 281 | 3.84375 | 4 | if __name__ == '__main__':
n = int(input().strip())
if (n%2 != 0):
print("Weird")
elif (n%2 == 0):
if(n>=2 or n < 5):
print("Not Weird")
elif (n>=6 or n <= 20):
print("Weird")
else:
print("Not Weird")
|
a033d6d2d492e64b1d3b14fc0699ca0ace8c7819 | Santigio/Daily_Coding | /Calculator/calculator.py | 1,139 | 4.1875 | 4 |
Run = True
Exit = False
while Run:
button = int(input("Press 1(add), 2(subtract), 3(divide), 4(multiply)"))
User_input = int(input("Enter a number "))
User_input1 = int(input("Enter another number "))
def Addition(user1, user2):
return user1 + user2
def Subtration(user1, user2):
return user1 - user2
def Division(user1, user2):
return user1 / user2
def Multiplication(user1, user2):
return user1 * user2
if button == 1:
print(User_input, "+", User_input1, "=",
Addition(User_input, User_input1))
elif button == 2:
print(User_input, "-", User_input1, "=",
Subtration(User_input, User_input1))
elif button == 3:
print(User_input, "/", User_input1, "=",
Division(User_input, User_input1))
elif button == 4:
print(User_input, "*", User_input1, "=",
Multiplication(User_input, User_input1))
Question = input("Do you still want to continue? ")
if Question == "n" or "no":
quit()
else:
if Question == "yes" or "y":
continue
|
8e3fb08422279cc71390b76a4d0333f495c2670a | ChristerNilsson/Lab | /2016/041-MonteCarlo/montecarlo.py | 5,148 | 3.828125 | 4 | # kalaha med MonteCarlo
import random
import time
class Kalaha:
def __init__(self,size):
self.reset(size)
self.board = []
self.turn = 0 # or 7
def factor(self):
return 2 * self.turn / 7 - 1
#return 1 if self.turn==0 else -1
def reset(self,size):
self.board = [size] * 14
self.board[6] = 0
self.board[13] = 0
self.turn = 0
return self.board
def display(self):
print self.board[7:][::-1]
print " ",self.board[0:7]
def choice(self, iPit): # returns one position iPit = 0..5
pos = iPit + self.turn
count = self.board[pos]
if count == 0:
return False
self.board[pos] = 0
pos += 1
while count > 0:
if pos != 13 - self.turn:
self.board[pos] += 1
count -= 1
pos += 1
pos %= 14
return True
def repetition(self,i):
return (i + self.board[i+self.turn]) % 13 == 6
def flip(self):
self.turn = 7 - self.turn
def move(self, i):
if self.board[i+self.turn] == 0:
return False
if self.repetition(i):
self.choice(i)
else:
self.choice(i)
self.flip()
return True
def randomMove(self): # ej repetitioner.
a = [index for index in range(6) if self.board[index+self.turn] > 0]
if len(a) == 0:
return False
c = random.sample(a,1)[0]
#print c
#self.display()
if (c + self.board[c+self.turn]) % 13 == 6:
self.choice(c)
else:
self.choice(c)
self.flip()
return True
# self.randomMove()
def randomThread(self):
while self.randomMove():
continue
return self.board[6]-self.board[13]
def copy(self):
obj = Kalaha(0)
obj.board = self.board[:]
obj.turn = self.turn
return obj
def monteCarlo(self,n):
lst = [0] * 6
copy = self.copy()
for i in range(6):
if copy.choice(i):
for j in range(n):
score = copy.randomThread()
#lst[i] += score
#copy.display()
if score > 0:
lst[i] += 1
elif score < 0:
lst[i] -= 1
copy = self.copy()
else:
lst[i] = 999999
return lst
def score(self):
return self.board[6] - self.board[13]
def getLegalMoves(self):
return []
def minimax(self, level):
if level == 0:
return [self.score(), -1]
bestval = [-999999,-1]
for iMove in range(6):
cpy = self.copy()
#cpy.display()
if cpy.move(iMove):
val = self.factor() * cpy.minimax(level-1)
if val >= bestval[0]:
bestval = [val,iMove]
return bestval
# def moves(self):
# lst = []
# a = [index for index in range(6) if self.board[index+self.turn] > 0]
# copy = Kalaha(0)
# for i in a:
# if (i + self.board[i+self.turn]) % 13 == 6:
# copy.board = self.board[:]
# copy.choice(i)
# lst.append([i]+copy.moves())
# else:
# lst.append([i])
# return lst
def bestIndex(self,lst):
mini=0
for i in range(len(lst)):
if lst[mini]>lst[i]:
mini=i
return mini
#return min((v, i) for i, v in enumerate(lst))[1]
def run(self):
self.reset(4)
#self.board = [6,5,4,3,2,1,0,6,5,4,3,2,1,0]
self.turn = 7
#self.display()
while True:
# Fi flyttar
start = time.time()
while self.turn == 7:
#lst = self.monteCarlo(2000)
iMove = self.minimax(8)[1]
if iMove == -1:
print "Game over"
return
self.move(iMove)
self.display()
print time.time()-start
# Vi flyttar
while self.turn == 0:
self.move(input(':'))
self.display()
def test(self):
assert self.reset(4) == [4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 0]
assert self.bestIndex([5,4,1,2,7,0]) == 5
assert self.bestIndex([184, 191, 178, 136, 148, 127]) == 5
self.reset(4)
#assert self.choice(0) == [0,5,5,5,5,4,0,4,4,4,4,4,4,0]
#self.reset(4)
#assert self.choice(2) == [4,4,0,5,5,5,1,4,4,4,4,4,4,0]
#self.reset(4)
# self.board = [6,5,4,3,2,1,0,4,4,4,4,4,4,0]
# print self.moves() #== [[0],[1],[2,0],[2,1],[2,3],[2,4],[2,5],[3],[4],[5]]
# print len(self.moves())
#print self.randomThread()
#print self.monteCarlo(1000)
kalaha = Kalaha(4)
kalaha.test()
kalaha.reset(4)
kalaha.turn = 7
kalaha.randomMove()
#kalaha.display()
kalaha.run() |
d4ad647979d37fc90ff8ea4b1d6cd3c64ba66286 | JRoehrig/caeli | /caeli/time_series.py | 19,637 | 3.609375 | 4 | import calendar
import pandas as pd
from datetime import datetime
from dateutil.relativedelta import relativedelta
# ======================= YEAR ================================================
def replace_year(dt, year):
"""Replace the year in ``dt`` by ``year``. If dt has the last day in the month, keep also the last day of the
month for leap years
:param dt:
:type dt:
:param year:
:type year:
:return:
:rtype:
"""
dt = pd.Timestamp(dt)
if is_leap_day(dt):
if calendar.isleap(year):
dt0 = dt.replace(year=year)
else:
dt0 = dt.replace(year=year, day=28)
else:
if calendar.isleap(year) and dt.day == 28 and dt.month == 2:
dt0 = dt.replace(year=year, day=29)
else:
dt0 = dt.replace(year=year)
return dt0
def is_leap_day(dt):
"""Check whether ``dt`` is the 29.02
:param dt: datetime
:type dt: datetime, pd.Timestamp, np.datetime64
:return: True/False
:rtype: bool
"""
dt = pd.Timestamp(dt)
return dt.day == 29 and dt.month == 2
def last_day_of_month(dt):
try:
return [(pd.Timestamp(t) + pd.tseries.offsets.MonthEnd(n=0)).day for t in dt]
except (TypeError, ValueError):
return (pd.Timestamp(dt) + pd.tseries.offsets.MonthEnd(n=0)).day
def is_last_day_of_month(dt):
"""Check whether day in ``dt`` is the last day of the month
:param dt: datetime
:type dt: datetime, pd.Timestamp, np.datetime64
:return: True/False
:rtype: bool
"""
return pd.Timestamp(dt).day == last_day_of_month(dt)
def increment_months(dt, months=1, microseconds=0):
"""Increment ``dt`` by ``months``. Default is to increment one month.
Return a ``pd.Timestamp``.
:param dt: timestamp
:type dt: datetime, pd.Timestamp, np.datetime64
:param months: number of months to increment. Negative values are allowed. Default months = 1
:type months: int
:param microseconds: microseconds to add to the right interval: 0 for closed, -1 for right opened interval
:type microseconds: int
:return: ts incremented by ``months``
:rtype: pd.Timestamp
"""
# Don't use pd.Timedelta:
# pd.Timestamp('2000-12-30 07:30') + pd.Timedelta(1, unit='M') == Timestamp('2001-01-29 17:59:06')
dt = pd.Timestamp(dt)
ts1 = pd.Timestamp(dt.to_pydatetime() + relativedelta(months=months, microseconds=microseconds))
if is_last_day_of_month(dt):
return ts1.replace(day=1) + pd.tseries.offsets.MonthEnd(n=1)
else:
return ts1
def monthly_intervals(indices, months=None, aggregation=1, start_at='beg',
closed_left=True, closed_right=True):
"""Return a list of tuples [from, to], where the intervals correspond to the begin and end of
aggregated months (default aggregation=1 means monthly intervals). The aggregation may be also negative.
:param indices: sorted list of timestamps
:type indices: pd.DatetimeIndex, list
:param months: output months for the intervals
:type months: None or list
:param aggregation: number of aggregated months. Default 1 (monthly)
:type aggregation: int
:param start_at: date and time to start. Only day and time are used, year and month are only placeholders
and will be discarded. start_at='end' for the end of the first month in the time series.
start_at='beg' for the first day of the month at 00:00:00. start_at=None is equivalent to start_at='beg'
:type start_at: datetime.datetime, str
:param closed_left: left close interval
:type closed_left: bool
:param closed_right: right close interval
:type closed_right: bool
:return: list of intervals [[begin0, end0], [begin1, end1], ..., [beginN, endN]]
:rtype: list of [pd.Timestamp, pd.Timestamp]
For the examples below the following `indices` will be used:
.. code-block::
>>> import numpy as np
>>> import pandas as pd
>>> from caeli.time_series import monthly_intervals
>>> index = pd.date_range('1990-01-01 07:30', '2020-01-01 07:30', freq='1d')
>>> index
DatetimeIndex(['1990-01-01 07:30:00', '1990-01-02 07:30:00',
'1990-01-03 07:30:00', '1990-01-04 07:30:00',
'1990-01-05 07:30:00', '1990-01-06 07:30:00',
'1990-01-07 07:30:00', '1990-01-08 07:30:00',
'1990-01-09 07:30:00', '1990-01-10 07:30:00',
...
'2019-12-23 07:30:00', '2019-12-24 07:30:00',
'2019-12-25 07:30:00', '2019-12-26 07:30:00',
'2019-12-27 07:30:00', '2019-12-28 07:30:00',
'2019-12-29 07:30:00', '2019-12-30 07:30:00',
'2019-12-31 07:30:00', '2020-01-01 07:30:00'],
dtype='datetime64[ns]', length=10958, freq='D')
Examples:
Using default values. Note that the time series starts at 07:30 but as per default the month starts at 00:00.
Therefore, the first month is ignored.
.. code-block::
>>> itv = monthly_intervals(index, months=None, aggregation=1, start_at='beg',
closed_left=True, closed_right=True)
>>> print('{}, ..., {}'.format(itv[0], itv[-1]))
[Timestamp('1990-02-01 00:00:00'), Timestamp('1990-03-01 00:00:00')], ...,
[Timestamp('2019-12-01 00:00:00'), Timestamp('2020-01-01 00:00:00')]
Setting start_at=1999-01-01 07:30'. YYYY-MM ('1999-01') is a place holder.
.. code-block::
>>> itv = monthly_intervals(index, months=None, aggregation=1, start_at='1999-01-01 07:30',
closed_left=True, closed_right=True)
>>> print('{}, ..., {}'.format(itv[0], itv[-1]))
[Timestamp('1990-01-01 07:30:00'), Timestamp('1990-02-01 07:30:00')], ...,
[Timestamp('2019-12-01 07:30:00'), Timestamp('2020-01-01 07:30:00')]
closed_right=False.
.. code-block::
>>> itv = monthly_intervals(index, months=None, aggregation=1, start_at='1999-01-01 07:30',
closed_left=True, closed_right=False)
>>> print('{}, ..., {}'.format(itv[0], itv[-1]))
[Timestamp('1990-01-01 07:30:00'), Timestamp('1990-02-01 07:29:59.999999')], ...,
[Timestamp('2019-12-01 07:30:00'), Timestamp('2020-01-01 07:29:59.999999')]
aggregation=2.
.. code-block::
>>> itv = monthly_intervals(index, months=None, aggregation=2, start_at='1999-01-01 07:30',
closed_left=True, closed_right=False)
>>> print('{}, ..., {}'.format(itv[0], itv[-1]))
[Timestamp('1990-01-01 07:30:00'), Timestamp('1990-03-01 07:29:59.999999')], ...,
[Timestamp('2019-11-01 07:30:00'), Timestamp('2020-01-01 07:29:59.999999')]
months=[1, 4, 7, 10].
.. code-block::
>>> itv = monthly_intervals(index, months=[1, 4, 7, 10], aggregation=3,
start_at='1999-01-01 07:30', closed_left=True, closed_right=False)
>>> itv[:5]
[[Timestamp('1990-01-01 07:30:00'), Timestamp('1990-04-01 07:29:59.999999')],
[Timestamp('1990-04-01 07:30:00'), Timestamp('1990-07-01 07:29:59.999999')],
[Timestamp('1990-07-01 07:30:00'), Timestamp('1990-10-01 07:29:59.999999')],
[Timestamp('1990-10-01 07:30:00'), Timestamp('1991-01-01 07:29:59.999999')],
[Timestamp('1991-01-01 07:30:00'), Timestamp('1991-04-01 07:29:59.999999')]]
Negative aggregation (aggregation=-3). Note that the first aggregation
[1989-12-31 07:30:00, 1990-02-01 07:29:59.999999] is ignored because the time series starts at 1990-01-01 07:30:00.
.. code-block::
>>> itv = monthly_intervals(index, months=[2, 5, 8, 11], aggregation=-3,
start_at='1999-01-01 07:30', closed_left=True, closed_right=False)
>>> itv[:5]
[[Timestamp('1990-02-01 07:30:00'), Timestamp('1990-05-01 07:29:59.999999')],
[Timestamp('1990-05-01 07:30:00'), Timestamp('1990-08-01 07:29:59.999999')],
[Timestamp('1990-08-01 07:30:00'), Timestamp('1990-11-01 07:29:59.999999')],
[Timestamp('1990-11-01 07:30:00'), Timestamp('1991-02-01 07:29:59.999999')],
[Timestamp('1991-02-01 07:30:00'), Timestamp('1991-05-01 07:29:59.999999')]]
"""
if not months:
months = range(1, 13)
index0 = indices[0]
index1 = indices[-1]
if start_at is None or start_at == 'beg':
start_at = datetime(index0.year, index0.month, 1, 0, 0, 0, 0)
elif start_at == 'end':
start_at = increment_months(index0).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
index1 = increment_months(index1).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
if aggregation < 0:
index1 = increment_months(index1, aggregation)
ts0 = replace_year(start_at, index0.year)
tuples = list()
while ts0 <= index1:
if ts0.month in months:
inc = increment_months(ts0, aggregation)
tuples.append([ts0, inc] if aggregation > 0 else [inc, ts0])
ts0 = increment_months(ts0, 1)
if not closed_right:
tuples = [[ts0, ts1 - pd.Timedelta(1, unit='us')] for ts0, ts1 in tuples]
if not closed_left:
tuples = [[ts0 + pd.Timedelta(1, unit='us'), ts1] for ts0, ts1 in tuples]
while tuples[0][0] < index0:
tuples = tuples[1:]
while tuples[-1][1].replace(hour=0, minute=0, second=0, microsecond=0) > index1:
tuples = tuples[:-1]
return tuples
def monthly_series(sr, rule='sum', months=None, aggregation=1, start_at=None,
closed_left=True, closed_right=False, label='right',
is_sorted=False, time_format='d'):
"""Return the series resampled to the months listed in ``months``,
taking ``accum`` adjacent months. The default resampling rule is ``sum``.
:param sr: pandas.Series with DateTimeIndex as index. The series at any frequency will be aggregated to month(s)
:type sr: pandas.Series, pandas.DataFrame
:param rule: resample rule. Default *rule='sum'*
:type rule: str
:param months: see :func:`monthly_intervals`
:param aggregation: see :func:`monthly_intervals`
:param start_at: see :func:`monthly_intervals`
:param closed_left: see :func:`monthly_intervals`
:param closed_right: see :func:`monthly_intervals`
:param label: 'right' for setting the index at the end and 'left' for setting the index at the begin of the
interval in the time series. Default label='right'
:type label: str
:param is_sorted: True if the input time series is alredy sorted, otherwise False. Default is_sorted = False
:type is_sorted: bool
:param time_format: 'd' (day/date): round hour, minute, sencond, and milliseconds to 0; 'h' (hour): round minute,
second, and milliseconds to 0, 'm' (minute)': round second and milliseconds to 0, 's' (second): round
milliseconds to 0; None: do not round anything
:type time_format: str, None
:return: (**pandas.DataFrame, pandas.Series**): monthly time series
For the examples below the following time series will be used:
.. code-block::
>>> import numpy as np
>>> import pandas as pd
>>> from caeli.time_series import monthly_series
>>> np.random.seed(1)
>>> index = pd.date_range('1990-01-01 07:30', '2020-01-01 07:30', freq='1d')
>>> p = np.random.normal(2, 0.1, size=len(index))
>>> p[p < 0.0] = 0.0
>>> sr_daily = pd.Series(p, index=index)
>>> sr_daily
1990-01-01 07:30:00 2.162435
1990-01-02 07:30:00 1.938824
...
2019-12-31 07:30:00 1.937972
2020-01-01 07:30:00 2.081355
Freq: D, Length: 10958, dtype: float64
Right labeled, showing date only:
.. code-block::
>>> sr_monthly = monthly_series(sr_daily, aggregation=2, start_at='1999-01-01 07:30')
>>> sr_monthly
1990-03-01 117.961372
1990-04-01 118.789945
...
2019-12-01 122.096353
2020-01-01 123.361334
Length: 359, dtype: float64
Right labeled, showing the full date/time:
.. code-block::
>>> sr_monthly = monthly_series(sr_daily, aggregation=2, start_at='1999-01-01 07:30',
time_format=None)
>>> sr_monthly
1990-03-01 07:29:59.999999 117.961372
1990-04-01 07:29:59.999999 118.789945
...
2019-12-01 07:29:59.999999 122.096353
2020-01-01 07:29:59.999999 123.361334
Length: 359, dtype: float64
Left labeled, showing date only:
.. code-block::
>>> sr_monthly = monthly_series(sr_daily, aggregation=2, start_at='1999-01-01 07:30',
label='left')
>>> sr_monthly
1990-01-01 117.961372
1990-02-01 118.789945
...
2019-10-01 122.096353
2019-11-01 123.361334
Length: 359, dtype: float64
Left labeled, showing the full date/time:
.. code-block::
>>> sr_monthly = monthly_series(sr_daily, aggregation=2, start_at='1999-01-01 07:30',
label='left', time_format=None)
>>> sr_monthly
1990-01-01 07:30:00 117.961372
1990-02-01 07:30:00 118.789945
...
2019-10-01 07:30:00 122.096353
2019-11-01 07:30:00 123.361334
Length: 359, dtype: float64
"""
if not is_sorted:
sr = sr.sort_index()
idx = 1 if label == 'right' else 0
intervals_list = monthly_intervals(sr.index, months=months, aggregation=aggregation, start_at=start_at,
closed_left=closed_left, closed_right=closed_right)
tdf = []
for beg_end in intervals_list:
value = getattr(slice_by_timestamp(sr, beg_end[0], beg_end[1]), rule)()
tdf.append([beg_end[idx], value])
tdf = list(zip(*tdf))
try:
sr1 = pd.concat(tdf[1][:], axis=1).transpose().set_index(pd.DatetimeIndex(tdf[0]))
except TypeError:
sr1 = pd.Series(tdf[1], index=tdf[0])
sr1.name = sr.name
if time_format == 'd':
sr1.index = sr1.index.map(lambda t: t.replace(hour=0, minute=0, second=0, microsecond=0))
elif time_format == 'h':
sr1.index = sr1.index.map(lambda t: t.replace(minute=0, second=0, microsecond=0))
elif time_format == 'm':
sr1.index = sr1.index.map(lambda t: t.replace(second=0, microsecond=0))
elif time_format == 's':
sr1.index = sr1.index.map(lambda t: t.replace(microsecond=0))
return sr1
def months_split_annually(sr, rule='sum', months=None, aggregation=1, start_at=None,
closed_left=True, closed_right=False, label='left',
is_sorted=False, time_format='d', prefix='M'):
"""Return a pandas.DataFrame with aggregated months as columns and year as index.
:param sr: pandas.Series with DateTimeIndex as index
:type sr: pandas.Series or pandas.DataFrame
:param rule: see :func:`monthly_series`
:param months: see :func:`monthly_intervals`
:param aggregation: see :func:`monthly_intervals`
:param start_at: see :func:`monthly_intervals`
:param closed_left: see :func:`monthly_intervals`
:param closed_right: see :func:`monthly_intervals`
:param label: see :func:`monthly_intervals`
:param is_sorted: see :func:`monthly_intervals`
:param time_format: see :func:`monthly_intervals`
:param prefix: Prefix for columns names. Default prefix='M'
:type prefix: str
:return: (**pandas.DataFrame**) with aggregated months as columns and year as index
For the examples below the following time series will be used:
.. code-block::
>>> import numpy as np
>>> import pandas as pd
>>> from caeli.time_series import months_split_annually
>>> np.random.seed(1)
>>> index = pd.date_range('1990-01-01 07:30', '2020-01-01 07:30', freq='1d')
>>> p = np.random.normal(2, 0.1, size=len(index))
>>> p[p < 0.0] = 0.0
>>> sr_daily = pd.Series(p, index=index)
>>> sr_daily
1990-01-01 07:30:00 2.162435
1990-01-02 07:30:00 1.938824
...
2019-12-31 07:30:00 1.937972
2020-01-01 07:30:00 2.081355
Freq: D, Length: 10958, dtype: float64
.. code-block::
>>> spy = months_split_annually(sr_daily, aggregation=2, start_at='1999-01-01 07:30')
>>> print(spy)
M01-02 M02-03 ... M11-12 M12-01
year ...
1990 117.961372 118.789945 ... 121.819112 123.028979
1991 117.760247 118.953375 ... 121.958717 123.601324
... ... ... ... ... ...
2018 117.549323 117.780231 ... 121.336530 122.549497
2019 116.797959 117.721573 ... 123.361334 NaN
[30 rows x 12 columns]
M01-02 M02-03 ... M11-12 M12-01
year ...
1990 117.961372 118.789945 ... 121.819112 123.028979
1991 117.760247 118.953375 ... 121.958717 123.601324
... ... ... ... ... ...
2018 117.549323 117.780231 ... 121.336530 122.549497
2019 116.797959 117.721573 ... 123.361334 NaN
[30 rows x 12 columns]
"""
if not months:
months = range(1, 13)
df = monthly_series(sr, rule=rule, months=months, aggregation=aggregation, start_at=start_at,
closed_left=closed_left, closed_right=closed_right, label=label,
is_sorted=is_sorted, time_format=time_format)
try:
df = df.to_frame()
except AttributeError:
pass
name = df.columns[0]
df['month'] = df.index.month
df['year'] = df.index.year
df1 = df.pivot(index='year', columns='month', values=name)
months1 = list(range(1, 13))
if aggregation > 1:
columns = ['{}{}-{}'.format(prefix, str(m).zfill(2),
str(months1[(m + aggregation - 2) % 12]).zfill(2)) for m in months]
elif aggregation < 1:
columns = ['{}{}-{}'.format(prefix, str(months1[(m + aggregation) % 12]).zfill(2),
str(m).zfill(2)) for m in months]
else:
columns = ['{}{}'.format(prefix, str(m).zfill(2)) for m in months]
df1.columns = columns
return df1
def slice_by_timestamp(df, beg_timestamp=pd.Timestamp.min, end_timestamp=pd.Timestamp.max):
"""Slice the data frame from index starting at beg_timestamp to end_timestamp, including the latter.
:param df: data frame
:type df: pandas.DataFrame or pandas.Series
:param beg_timestamp: begin of slice
:type beg_timestamp: datetime.datetime, pandas.timestamp, or numpy.datetime64
:param end_timestamp: end of slice (inclusive)
:type end_timestamp: datetime.datetime, pandas.timestamp, or numpy.datetime64
:return: (**pandas.DataFrame or pandas.Series**) sliced data frame
"""
beg = df.index.searchsorted(beg_timestamp, side='left')
end = df.index.searchsorted(end_timestamp, side='right')
return df.iloc[beg:end]
|
30213b10a85e8e231f7a0cf3076c75a239dafe22 | codingpython7/test-repository | /ListTesting.py | 340 | 3.890625 | 4 | List = []
Running = True
while(Running == True):
user = input("Please Put In A Number")
if(user == "stop"):
break
user = int(user)
List.append(user)
print(List)
Steps_Total = len(List)
i=0
Total = 0
while(i != Steps_Total):
Total += List[i]
i += 1
Total_Avg = Total / Steps_Total
print(Total_Avg)
|
e00a63ea54c8813c3699f1d570323de758cf9cba | grodrigues3/InterviewPrep | /Leetcode/givePerms.py | 385 | 3.5625 | 4 | import math
global digits
digits = []
def getPermutation(values,n, k):
global digits
if values == []:
return
n1Fact = 1
for i in range(1,n):
n1Fact *= i
firstDig = values[int(math.ceil(k*1. / n1Fact))-1]
print firstDig
values.remove(firstDig)
digits += [firstDig]
getPermutation(values,n-1, k%n1Fact)
values = range(1,4)
i = 3
getPermutation(values,3, i)
print digits
|
c6f4074ea62eddc110c4782c3e43d40acb9a8b4a | dvdalilue/ci2692_ene_mar_2017 | /proyecto_2/lista.py | 1,428 | 3.578125 | 4 | class NodoLista:
def __init__(self, e, s, a):
self.elemento = e
self.siguiente = s
self.anterior = a
class ListaReproduccion:
def __init__(self):
self.proxima = None
self.numero_nodos = 0
def agregar_final(self,e):
aux = NodoLista(e,None, None)
if self.numero_nodos == 0:
self.proxima = aux
self.proxima.siguiente = self.proxima
self.proxima.anterior = self.proxima
else:
aux.anterior = self.proxima.anterior
aux.anterior.siguiente = aux
aux.siguiente = self.proxima
self.proxima.anterior = aux
self.numero_nodos += 1
def agregar(self,e):
self.agregar_final(e)
self.proxima = self.proxima.anterior
def eliminar(self,tituloCancion):
assert tituloCancion != "", "El titulo no puede ser vacío"
aux = self.proxima
i = 0
while True:
if aux.elemento.titulo == tituloCancion:
break
elif i > self.numero_nodos:
raise Exception('La canción no se encuentra en la lista')
aux = aux.siguiente
i += 1
aux.anterior.siguiente = aux.siguiente
aux.siguiente.anterior = aux.anterior
self.numero_nodos -= 1
if self.numero_nodos == 0:
self.proxima = None
return aux |
b63f1283d86bbfffb2e7055139be0bf89eb6e052 | justinclark-dev/CSC110 | /code/Chapter-4/combined_spiral_solution.py | 1,349 | 4.5625 | 5 | # This program draws a design using repeated circles.
import turtle
# Named constants
NUM_CIRCLES = 36 # Number of circles to draw
RADIUS = 25 # Radius of each circle
CIRCLE_ANGLE = 10 # Angle to turn when drawing circles
CIRCLE_START_X = 0 # Starting X coordinate for lines
CIRCLE_START_Y = 0 # Starting Y coordinate for lines
LINE_START_X = -200 # Starting X coordinate for lines
LINE_START_Y = 0 # Starting Y coordinate for lines
NUM_LINES = 36 # Number of lines to draw
LINE_LENGTH = 400 # Length of each line
LINE_ANGLE = 170 # Angle to turn
ANIMATION_SPEED = 0 # Animation speed
# Set the animation speed.
turtle.speed(ANIMATION_SPEED)
# Move the turtle to its initial position to draw the circles.
turtle.hideturtle()
turtle.penup()
turtle.goto(CIRCLE_START_X, CIRCLE_START_Y)
turtle.pendown()
# Draw 36 circles, with the turtle tilted
# by 10 degrees after each circle is drawn.
for x in range(NUM_CIRCLES):
turtle.circle(RADIUS)
turtle.left(CIRCLE_ANGLE)
# Move the turtle to its initial position to draw the lines.
turtle.hideturtle()
turtle.penup()
turtle.goto(LINE_START_X, LINE_START_Y)
turtle.pendown()
# Draw 36 lines, with the turtle tilted
# by 170 degrees after each line is drawn.
for x in range(NUM_LINES):
turtle.forward(LINE_LENGTH)
turtle.left(LINE_ANGLE)
|
ce354ccece659447d64d69bc0fb9cb0e3f990f68 | 506independent-2/python-code-all-mine | /stand alones/test 0006 secure dice.py | 4,526 | 4.28125 | 4 | from secrets import *
print ("secure random generator, a 506independent program")
#makes the variables
canc = False
high = 2
num = 0
while canc == False:
choice = input("what do you want to generate? a single random number"
" in the range you choose (s), as many"
"separate secure random numbers as you want, in a"
" range you choose (3), make a hex with as many bytes "
"as you choose(h)"
"or generate a token with as many bytes as you"
" choose (t). you can also see about, (a). maybe you"
" want to enter the DICE LOOP (dl)")
#ensures your choice is processed
if choice == "s":
high = int(input("what will be the highest number?"))
num = randbelow (high)
print (num)
if choice == "t":
high = int(input("how many bytes is your token?"))
num = token_bytes (high)
print (num)
if choice == "h":
high = int(input("how many bytes is your hex?"))
num = token_hex(high)
print (num)
if choice == "3":
rang = int(input("how many random numbers do YOU want to"
" GENERATE?"))
choice = input("do you want to choose the cap for all the "
"numbers at once(a), or meet them induvidually(i)?")
if choice == "a":
high = int(input(" what is the cap?"))
for i in range(rang):
if choice == "i":
high = int(input("what is the cap for this number?"))
num = randbelow (high)
print (num)
else:
num = randbelow (high)
print (num)
#changing the choice is essantial, otherwise it will play the about page
choice = "d"
if choice == "a":
print ("this dice was designed as a secure dice, for when you need secure random generation.")
print ("imagine this. you're playing a board game, and someone decided to bring a cheat dice. you then lose.")
if choice == "dl":
#makes the variables befor they are used
mode = "fill"
enter = "fill"
mode = int(input(" what mode do you want? 10, 8, 6, 5, 2 or choose(1)?"))
enter = input("you have decided to enter the DICE LOOP. to enter, just enter the word in, and you are in. otherwise,"
"you will be kicked out")
if enter == "in":
print ("you poor soul, you ahve entered the loop! e to exit if you got here by accident!")
if mode == 10:
while not enter == "e":
num = randbelow (10)
print (num)
enter = input("press enter when you are ready to re-roll")
if mode == 8:
while not enter == "e":
num = randbelow (8)
print (num)
enter = input("press enter when you are ready to re-roll")
if mode == 6:
while not enter == "e":
num = randbelow (6)
print (num)
enter = input("press enter when you are ready to re-roll")
if mode == 5:
while not enter == "e":
num = randbelow (5)
print (num)
enter = input("press enter when you are ready to re-roll")
if mode == 2:
while not enter == "e":
num = randbelow (2)
print (num)
enter = input("press enter when you are ready to re-roll")
if mode == 1:
high = int(input("what is the cap number?"))
while not enter == "e":
num = randbelow (high)
print (num)
enter = input("press enter when you are ready to re-roll")
else:
pass
#turns the canc into python readable Trues and Falses.
canc = input("again(y/n)")
if canc == "y":
canc = False
#hundredth line?!
if canc == "Y":
can = False
if canc == "n":
canc = True
if canc == "N":
canc = True
#when you use the python runthing, then this wont close the runthing instantly. stops when you hit enter.
input("thanks for trying my second dice!") |
e319a39e00f334d0b41f7fff0cac3222ca3289f1 | KunaalNaik/YT_Basic_Apps | /cluster.py | 778 | 3.6875 | 4 | # Import Libraries
import streamlit as st
import pandas as pd
#import numpy as np
import plotly.express as px
import seaborn as sns
import matplotlib.pyplot as plt
# Import Data
df = pd.read_csv('Mall_Customers.csv')
df_Short = df[['Spending_Score', 'Income']]
# Add App Titles and Add a Sidebar
st.title('Cluster Analysis')
st.sidebar.title('K Means Parameters')
# Sidebar Controls
st.sidebar.number_input('Input K', min_value=1, max_value=12)
# Plot Scatter Plot using Income and Spending Score
st.header('Income and Spending Score Plot')
fig = px.scatter(df_Short, x='Spending_Score', y='Income')
st.plotly_chart(fig)
st.header('Cluster Data')
if st.checkbox('Show dataframe'):
st.write(df)
#st.dataframe(df)
# Good Link https://morioh.com/p/7066169a0314
|
daee12eb4ec377ba532e7a162e614039ad9cdd48 | SillyFox12/FreeCodeCamp_Projects | /Greater.py | 324 | 3.796875 | 4 | compare = 3.4 * 10.0 ** 7.0
a = 9.2 * 10.0 ** 4.0
b = 8.7 * 10.0 ** 6.0
c = 3.4 * 10.0 ** 5.0
d = 3.1 * 10.0 ** 8.0
if a > compare:
print("The answer is A")
elif b > compare:
print("The answer is B")
elif c > compare:
print("The answer is C")
elif d > compare:
print("The answer is D")
|
d7a4368f6481609e2ca579fb1689d16b7b2d4b83 | adampehrson/Kattis | /venv/bin/I_repeat_myself.py | 306 | 3.609375 | 4 | cases = int(input())
for x in range(cases):
sentence = input()
for y in range(1, len(sentence)+1):
temp = sentence[:y]
newtemp = temp
while len(temp) < len(sentence):
temp += temp
if sentence in temp:
print(len(newtemp))
break
|
3ec9accf294d61078fdfe02b971684044087c14a | jongpark1234/Python | /pyExample_26.py | 1,050 | 3.96875 | 4 | # Function
def printInfo():
print("Hello, My name is JongPark.")
print("I am good at Python.")
print("I am attending Daegu Software Meister High School.")
printInfo() # Hello, My name is JongPark.
# I am good at Python.
# I am attending Daegu Software Meister High School.
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return round(num1 / num2, 2)
def printall(num1, num2):
print(add(num1, num2), sub(num1, num2), mul(num1, num2), div(num1, num2))
printall(5, 13) # 18 -8 65 0.38
def introduce(name, age, lan1, lan2, lan3):
print("My name is {}. I am {} years old. I can handle {}, {}, and {}.".format(name, age, lan1, lan2, lan3))
introduce("JongPark", 17, "Python", "C", "JavaScript") # My name is JongPark. I am 17 years old. I can handle Python, C, and JavaScript.
num = 2 # global variable
def double():
global num
num *= 2
for i in range(10):
print(num)
double() |
f0f20ef0e03cd1b2774f34d016576d21986b3985 | aspadm/labworks | /module5/texts_se.py | 6,994 | 3.6875 | 4 | # Кириллов Алексей, ИУ7-12
# Вариант №24
# Текст задан массивом строк; найти: самое длинное слово в каждой строке,
# количество слов во всём тексте/в последних двух строках,
# наиболее часто встречающееся слово.
# Заменить арифметическое действие (+,-) на результат.
# Выравнивать строки по ширине (число пробелов между словами строки отличается
# на 1 или меньше).
# Добавить замену одного слова другим во всём тексте; удалить из первых трёх
# строк заданное слово.
# Версия БЕЗ использования возможностей языка
text = """Сегодня +15 градусов
тепла
и это -
ложь.
Вот.
Так вот."""
def splitl(s):
k = []
z = ''
for i in range(len(s)):
if s[i]!='\n':
z += s[i]
else:
k.append(z)
z = ''
k.append(z)
return k
def splits(s):
k = []
z = ''
for i in range(len(s)):
if s[i]!=' ':
z += s[i]
elif len(z):
k.append(z)
z = ''
k.append(z)
return k
def dz(s):
if s[-1]==',' or s[-1]=='.':
s = s[:-1]
return s
def summ(s):
k = list()
for i in range(len(s)):
k += s[i]
return k
def calc(s):
if len(s) <= 1: # Если дефис/пустая строка
return s
if '+' in s or '-' in s:
digits = ''
expr = [1]
if s[0] == '-':
s = s[1:]
expr[0] = -1
for i in range(len(s)):
if s[i] == '+' or s[i] == '-':
digits += ' '
expr.append(1 if s[i] == '+' else -1)
else:
digits += s[i]
try:
digits = list(map(int,digits.split()))
except ValueError:
return s
if len(digits) == len(expr):
x = 0
for i in range(len(digits)):
x += digits[i]*expr[i]
s = str(x)
return s
def lenm(s,a = 0,b = 0):
if b == 0:
b = len(s)-1
k = 0
for i in range(a,b+1):
k += len(s[i])
return k
def printm(s,lab=''):
print(lab)
for i in range(len(s)):
for j in range(len(s[i])):
print(s[i][j],end=' ')
print()
print()
def printv(s,lab=''):
print(lab)
for i in range(len(s)):
print(dz(s[i]))
print()
def printh(s,n=0):
p = list() # Длина строки
z = list() # Новые пробелы
for i in range(len(s)): # Находим длины строк
p.append(len(summ(s[i])))
k = max(p)
if n < k+len(s[p.index(k)])-1: # Задаём ширину вывода
n = k+len(s[p.index(k)])-1
for i in range(len(s)):
a = n - p[i] # Находим число пробелов
b = len(s[i]) # Число слов
if b > 1:
z.append([' '*(a//(b-1))]*(b-1)) # Минимальное число пробелов
z[i].append('')
for j in range(a - a//(b-1)*(b-1)):
z[i][j%(b-2)] += ' ' # Дополняем текст по ширине
else:
z.append([' '*a])
for i in range(len(s)):
for j in range(len(s[i])):
if len(s[i]) == 1:
print(z[i][j]+s[i][j],end='')
else:
print(s[i][j]+z[i][j],end='')
print()
print()
def printr(s):
p = list() # Длина строки
for i in range(len(s)): # Находим длины строк
p.append(len(summ(s[i])))
k = max(p)
for i in range(len(s)):
print(' '*(k-p[i]-len(s[i])+1+len(s[p.index(k)])),end='')
for j in range(len(s[i])):
print(s[i][j],end=' ')
print()
print()
# Ввод текста
if input('Вводить текст заново? (д/н)<н>: ') == 'д':
print('Введите текст построчно; пустая строка прервёт ввод')
text = list()
while True:
s = list(input().split())
if len(s) > 0:
text.append(s)
else:
break
else:
text = splitl(text)
for i in range(len(text)):
text[i] = splits(text[i])
printm(text,'Заданный текст:')
print('С выравниванием по ширине:')
printh(text,0)
print('С выравниванием по правому краю:')
printr(text)
wcount = lenm(text) # Количество слов в тексте
lwords = [0]*len(text)
lwc3es = 0
lwc3es = lenm(text,len(text)-2) # Количество слов в последних 3х строках
for i in range(len(text)):
for j in range(len(text[i])):
if len(dz(text[i][j])) > len(dz(text[i][lwords[i]])):
lwords[i] = j
for i in range(len(text)):
lwords[i] = text[i][lwords[i]]
texta = summ(text)
cword = 0
for i in range(wcount):
if texta.count(texta[i]) > texta.count(texta[cword]):
cword = i
cword = texta[cword]
printv(lwords,'Самые длинные слова по строкам:')
for i in range(len(text)):
for j in range(len(text[i])):
text[i][j] = calc(text[i][j])
print('Всего слов:',wcount)
print('Слов в последних 2х строках:',lwc3es)
print('Наиболее частое слово:',cword)
print('\nС выполненной заменой математических выражений:')
printh(text)
zam = list()
zam.append(input('Заменить слово '))
zam.append(input('словом '))
for i in range(len(text)):
for j in range(len(text[i])):
if (dz(text[i][j])) == (zam[0]):
if text[i][j][-1]==',' or text[i][j][-1]=='.':
text[i][j] = zam[1]+text[i][j][-1]
else:
text[i][j] = zam[1]
print('\nС выполненной заменой:')
printh(text)
ud = input('Удалить из первых 3х строк слово ')
for i in range(3):
while ud in text[i]:
text[i].remove(ud)
while ud+'.' in text[i]:
text[i][text[i].index(ud+'.')] = text[i][text[i].index(ud+'.')][-1]
while ud+',' in text[i]:
text[i][text[i].index(ud+',')] = text[i][text[i].index(ud+',')][-1]
print('\nИтоговый текст:')
printh(text)
|
5196324d23a99848b1353a38b0d9b1aefe072929 | Moortiii/aoc-2020 | /day13/part_1.py | 941 | 3.671875 | 4 | from collections import defaultdict
with open("input.txt", "r") as f:
data = [line.strip() for line in f.readlines()]
earliest_time = int(data[0])
intervals = [int(d) for d in data[1].split(',') if d != 'x']
smallest_interval = min(intervals)
travel_times = defaultdict(list)
for interval in intervals:
if interval == 'x':
continue
iterations = (earliest_time // smallest_interval) + 5
for i in range(iterations):
travel_times[interval].append(i * interval)
options = []
for interval in intervals:
i = earliest_time
while True:
if i in travel_times[interval]:
options.append((i, interval))
break
i += 1
print(options)
best_option = min(options, key=lambda x: x[0])
arrival_time = best_option[0]
bus_to_take = best_option[1]
print("Time to wait:", arrival_time - earliest_time)
print("Output:", (arrival_time - earliest_time) * bus_to_take) |
38a8650448347cf59e18e3d3ca5cdcd2149a278e | Bellroute/algorithm | /python/book_python_algorithm_interview/ch23/maximum_subarray.py | 936 | 3.625 | 4 | # 리트코드 53. Maximum Subarray
import sys
from typing import List
class Solution:
# 내 풀이
def maxSubArray(self, nums: List[int]) -> int:
answer = value = nums[0]
for i in range(1, len(nums)):
value = max(value + nums[i], nums[i])
answer = max(answer, value)
return answer
# 책 풀이 1. 메모이제이션
# 내 풀이에서 공간 복잡도 측면에서 더 효율적임
def maxSubArray_1(self, nums: List[int]) -> int:
for i in range(1, len(nums)):
nums[i] += nums[i - 1] if nums[i - 1] > 0 else 0
return max(nums)
# 책 풀이 2. 카데인 알고리즘
def maxSubArray_2(self, nums: List[int]) -> int:
best_sum = -sys.maxsize
current_sum = 0
for num in nums:
current_sum = max(num, current_sum + num)
best_sum = max(best_sum, current_sum)
return best_sum
|
68bb1aa322d1651eaa10b86cf4ceb3c8097510b6 | clickok/Code-Snippets | /Image-Magick/isolate_leds.py | 1,777 | 3.9375 | 4 | #!/python3
"""
Find and isolate LEDs (or other sufficiently bright lights) in a series of PNG
images for use in other scripts.
For example, we seek to find the LEDs of a robot to be composited in
order to draw its path, if we have a series of PNGs corresponding to frames in
a movie of the robot moving around.
1. Apply "-black-threshold" to images
2. Convert black regions to transparent
Usage:
python isolate_leds.py INPUT_DIR OUTPUT_DIR
"""
import os
import os.path
import sys
import subprocess
def main():
# For debugging
MONITOR = True
if MONITOR:
IF_MON = "-monitor"
else:
IF_MON = ""
# Variables affecting image processing
THRESHOLD = "50%"
# Make sure that
try:
INPUT_DIR = os.path.abspath(sys.argv[1])
OUTPUT_DIR = os.path.abspath(sys.argv[2])
assert(os.path.isdir(INPUT_DIR))
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
except AssertionError as e:
print("\nERROR: Input directory was not a valid directory\n")
raise e
except Exception as e:
raise e
print("Operating on images in:", INPUT_DIR, "saving results in", OUTPUT_DIR)
# Convert Red and Green pixels below threshold to black following:
# `$ mogrify -channel Red,Green -black-threshold 50% OUTPUT_DIR/*.png`
print("Converting pixels below threshold to black")
subprocess.call(["mogrify", IF_MON, "-path", OUTPUT_DIR, "-channel", "Red,Green",
"-black-threshold", THRESHOLD, INPUT_DIR+"/*.png"])
# Convert black regions to transparent following:
# `$ mogrify -fuzz 5% -transparent black OUTPUT_DIR/*.png`
print("Converting black regions to transparent")
subprocess.call(["mogrify", IF_MON, "-transparent", "black", OUTPUT_DIR+"/*.png"])
if __name__ == "__main__":
if len(sys.argv) < 3:
print(__doc__)
exit()
main() |
19d98ee46c84bbfd0612a97561010acc15fa5971 | nadlej/Python | /Class_09/singlelist.py | 4,039 | 3.828125 | 4 | import unittest
class Node:
"""Klasa reprezentująca węzeł listy jednokierunkowej."""
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data) # bardzo ogólnie
class SingleList:
"""Klasa reprezentująca całą listę jednokierunkową."""
def __init__(self):
self.length = 0 # nie trzeba obliczać za każdym razem
self.head = None
self.tail = None
def is_empty(self):
# return self.length == 0
return self.head is None
def count(self): # tworzymy interfejs do odczytu
return self.length
def insert_head(self, node):
if self.head: # dajemy na koniec listy
node.next = self.head
self.head = node
else: # pusta lista
self.head = self.tail = node
self.length += 1
def insert_tail(self, node): # klasy O(N)
if self.head: # dajemy na koniec listy
self.tail.next = node
self.tail = node
else: # pusta lista
self.head = self.tail = node
self.length += 1
def remove_head(self): # klasy O(1)
if self.is_empty():
raise ValueError("pusta lista")
node = self.head
if self.head == self.tail: # self.length == 1
self.head = self.tail = None
else:
self.head = self.head.next
node.next = None # czyszczenie łącza
self.length -= 1
# klasy O(N)
# Zwraca cały węzeł, skraca listę.
# Dla pustej listy rzuca wyjątek ValueError.
def remove_tail(self):
if self.is_empty() is None:
raise ValueError('pusta lista')
elif self.count() == 1:
node = self.head
self.head = self.tail = None
self.length -= 1
return node
else:
node = self.head
r_tail = self.tail
while node.next is not self.tail:
node = node.next
self.tail = node
self.length -= 1
return r_tail
# klasy O(1)
# Węzły z listy other są przepinane do listy self na jej koniec.
# Po zakończeniu operacji lista other ma być pusta.
def merge(self, other):
if self.is_empty():
self.head = other.head
self.tail = other.tail
self.length = other.length
other.head = other.tail = None
other.length = 0
else:
self.tail.next = other.head
self.tail = other.tail
self.length += other.length
other.head = other.tail = None
other.length = 0
# czyszczenie listy
def clear(self):
while self.head != self.tail:
self.remove_head()
print(self.head)
self.head = self.tail = None
self.length = 0
class Test(unittest.TestCase):
def setUp(self):
self.alist = SingleList()
self.alist.insert_head(Node(11))
self.alist.insert_head(Node(22))
self.alist.insert_tail(Node(33))
self.blist = SingleList()
self.blist.insert_head(Node(100)) # [11]
self.blist.insert_head(Node(44)) # [11]
self.clist = SingleList()
def testLen(self):
self.assertEqual(self.alist.length, 3)
self.assertEqual(self.alist.count(), 3)
self.assertEqual(self.blist.count(), 2)
self.assertEqual(self.clist.count(), 0)
def testMerge(self):
self.alist.merge(self.blist)
self.assertEqual(self.alist.count(), 5)
self.assertEqual(self.alist.remove_tail().data, 100)
self.clist.merge(self.alist)
self.assertEqual(self.clist.count(), 4)
self.assertEqual(self.clist.remove_tail().data, 44)
self.assertEqual(self.clist.remove_tail().data, 33)
def testClear(self):
self.clist.clear()
self.assertEqual(self.clist.count(), 0)
if __name__ == '__main__':
unittest.main()
|
92219590df32c0d4dae6d1e98a28071261d2ff4f | pavanmsvs/hackeru-python | /while-name.py | 102 | 4.125 | 4 | name = ""
while(name!='your name'):
name=input("enter your name \n")
print("Thank you") |
e343bbe00815ea5037d81e317174928e3eb432df | KarimAbdelazizCodes/hangman | /app.py | 2,188 | 4.0625 | 4 | import random
# keep track of words already used before, so that they user doesn't get the same word again
used_words = []
# Generate a random word at the start of each game
# I created a function for it just for the sake of readability
def randomize():
return random.choice(open("data.txt").read().splitlines())
def hangman():
print('''
Welcome to Hangman
You have 7 attempts until your defeat is declared
You cannot guess a letter more than once''')
# word which the user has to guess
word = randomize()
# check if the randomised word was already used in a previous game
if word in used_words:
word = randomize()
# keeps track of the letters guessed by the user to display on the screen
tracker = list(map(lambda x: '_', word))
# keep track of guessed letters - using a set so that there won't be duplicates
guesses = set()
game_running = True
attempts = 7
while game_running:
print(f'\nLives: {attempts}')
prompt = input('Guess a letter: ').lower()
if prompt in word and prompt not in guesses:
guesses.add(prompt)
for idx, letter in enumerate(word):
if letter == prompt:
tracker[idx] = letter
print(' '.join(tracker))
print(f'Your guesses: {guesses}')
elif len(prompt) > 1 or not prompt or not prompt.isalpha():
print('Invalid entry')
elif prompt not in guesses:
attempts -= 1
guesses.add(prompt)
print(' '.join(tracker))
print(f'Your guesses: {guesses}')
else:
print(f'You\'ve already guessed \'{prompt}\'')
# declares win or defeat
if attempts == 0:
print(f'\nYou lose!\n'
f'The word was: {word}')
break
elif ''.join(tracker) == word:
print('\nCongrats! You have won!\n'
f'The word was indeed \'{word}\'')
break
# prompt to play again
prompt = input('Play again? (Y/N): ').lower()
if prompt == 'y':
hangman()
else:
print('Goodbye! :)')
hangman()
|
21052621ebbd14c4af0920b742b5c2dbbe44a827 | faddy/ds-with-python | /ds/main/strings_arrays/int_to_bin.py | 445 | 3.53125 | 4 | from data_structures.stacks import Stack
def dec_to_bin(n):
if not isinstance(n, (int, long)): raise Exception('Not an int value')
st = Stack()
while n != 0:
st.push(n % 2)
n = n/2
b = ''
while not st.is_empty():
b += str(st.pop())
return b
def test():
print dec_to_bin(5)
print dec_to_bin(0)
print dec_to_bin(8)
print dec_to_bin(15)
if __name__ == '__main__':
test()
|
86b2550483c6dd89680e9231b59b0929cc1096bd | mach1982/python_experiments | /wizard.py | 263 | 3.671875 | 4 | def wizard_name(fname,lname,mname=''):
if mname:
full_name =fname+' '+ mname +' '+lname
elif lname:
full_name =fname+' '+lname
else:
full_name.title()
return(full_name)
w=wizard_name("Harry","Potter","James")
print(w)
|
0e6a454bd206ee16df57c3f7f2981e7ebd284d89 | hieutran106/leetcode-ht | /leetcode-python/easy/_206_reverse_linked_list/solution.py | 472 | 4 | 4 | from utils.my_list import ListNode
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
# process each list node until the end
while curr:
# store next node to a temporary variable
temp = curr.next
# point back to previous node
curr.next = prev
# then move forward
prev = curr
curr = temp
return prev
|
c40b13afae5d363d1ec2e976f9af5ad667db1f78 | blue0712/blue | /demo65.py | 287 | 3.703125 | 4 | class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
pass
def calculate_area(self):
return self.width * self.height
r1 = Rectangle(5, 7)
r2 = Rectangle(2, 9)
print(r1.calculate_area(), r2.calculate_area()) |
a3405c89c34926856d599f747f2957aa36d86bf4 | Jellux/personal-project | /Physics class project.py | 1,185 | 3.765625 | 4 | train_mass = 22680
train_acceleration = 10
train_distance = 100
bomb_mass = 1
def f_to_c(f_temp):
c_temp = (f_temp - 32) * 5/9
return c_temp
#We test our function
f100_in_celsius = f_to_c(100)
def c_to_f(c_temp):
f_temp = c_temp * (9/5) + 32
return f_temp
#Same thing as above
c0_in_fahrenheit = c_to_f(0)
#Define a function that takes in mass and acceleration
def get_force():
result_force = train_mass*train_acceleration
return result_force
#Save the result in a variable
train_force = get_force()
print('The GE train supplies '+str(train_force)+ ' Newtons of force.')
#Define a function that takes in mass and c
def get_energy():
c = 3*10**8
result_energy = bomb_mass*c
return result_energy
#Save the result in a variable
bomb_energy = get_energy()
print('A 1kg bomb supplies '+str(bomb_energy)+ ' Joules')
#Define a function that takes in mass, acceleration and distance
def get_work():
result_work = train_force*train_distance
return result_work
#Save the result in a variable
train_work = get_work()
print('The GE train does '+str(train_work)+ ' Joules of work over '+str(train_distance)+ ' meters.')
|
a366fd3ba418421ebb98ad9302946021b30559c8 | dreadnaught-ETES/school | /edward_swain_primes.py | 1,341 | 4.09375 | 4 | import math
num=int(input("Want to find out if a number is prime? Enter a number here: "))
nroot=int(math.sqrt(num))
start=2
stop=nroot+1
if num==2:
print("Your number is prime and special. 2 is the only even prime number.")
if num > 1:
for i in range(2, nroot):
if (num%i)==0:
print(num,"isn't Prime, since" ,i, "times",num//i,"equals",num,".")
break
if (num%i)!=0:
print(num,"is Prime. Lucky You.")
break
else:
print("Honey, keep it out of the negatives, and nobody wants to divide by zero.")
#ok so the problem i am running into with this is that the range is excluding everything but 2 if i enter it as "for i in range(2,nroot)..."
#my other option was to try a specific number such as the square root of a ridiculous number....that didnt work...for the same reasons.
#trying to test the exclusion didnt work. i tried nroot=int(math.sqrt(num)+1) to see if it was an exclusion problem.
#but for some reason... nothing works. the program only works if the the input is divisible by 2....
#i even tried altering the indentations but that just generated an error. the only other thing i can list as responsible for the issue...
#is the i in range coding itself... i tried to redefine start and stop points...that didnt work either...
|
950864ee22a6f6378d3a9a4ee3cc0e2e24c1e246 | newtheatre/lumina | /src/lumina/util/email.py | 903 | 4.1875 | 4 | def mask_email(email: str) -> str:
"""
Masks an email address by replacing the address and domain with *s
leaving only two characters of each plus the last part of the domain.
For example:
fred.bloggs@gmail.com -> fr***@gm***.com
"""
if email.count("@") != 1:
raise ValueError("Invalid email address, should have exactly one @")
address, domain = email.split("@")
if not address:
raise ValueError("Invalid email address, address should not be empty")
if not domain:
raise ValueError("Invalid email address, domain should not be empty")
domain_fore, _, domain_tld = domain.rpartition(".")
if not domain_fore:
raise ValueError("Invalid email address, cannot work out domain")
if not domain_tld:
raise ValueError("Invalid email address, cannot work out domain tld")
return f"{address[:2]}***@{domain_fore[:2]}***.{domain_tld}"
|
739d81d8e51302e7de6547e7b924f7494093d88e | marionl4b/Macgyver_Escape | /main.py | 4,389 | 3.609375 | 4 | # Macgyver Escape a labyrinth game using pygame
# !/usr/bin/env python3
# coding: utf-8
from labyrinth import *
from settings import *
class GameWrapper:
""" init the game loop """
def __init__(self):
self.screen = SCREEN
pygame.display.set_caption(TITLE)
self.clock = pygame.time.Clock()
self.running = True
self.game_over = False
# init functions of labyrinth
self.labyrinth = Labyrinth()
def game_loop(self):
""" run the game """
while self.running:
self.clock.tick(FPS)
while self.game_over:
self.end_game_screen()
self.events()
self.update()
self.draw()
def events(self):
""" init process input loop """
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.labyrinth.move('up')
elif event.key == pygame.K_DOWN:
self.labyrinth.move('down')
elif event.key == pygame.K_LEFT:
self.labyrinth.move('left')
elif event.key == pygame.K_RIGHT:
self.labyrinth.move('right')
def update(self):
""" logic """
if self.labyrinth.end_game():
self.game_over = True
def draw(self):
""" render graphics """
self.screen.fill(GREEN)
self.labyrinth.show_board_game()
pygame.display.flip()
def start_screen(self):
""" screen displayed once at the begining of the game"""
load_music('8-Bit Tunes MacGyver Theme.mp3')
pygame.mixer.music.play(loops=-1)
start_bg = load_img('start_bg.png')
start_bg_rect = start_bg.get_rect()
self.screen.blit(start_bg, start_bg_rect)
draw_text(TITLE, FONT_BOLD, 24, WHITE, WIDTH/2, 300)
draw_text("Make the Gate Keeper sleep to escape from the maze ", FONT, 18, WHITE, WIDTH / 2, 360)
draw_text("Press Arrows to move", FONT, 18, WHITE, WIDTH / 2, 400)
draw_text("Press Any key to start", FONT, 18, WHITE, WIDTH / 2, 420)
pygame.display.flip()
wait_start = True
while wait_start:
self.clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
wait_start = False
self.running = False
elif event.type == pygame.KEYUP:
wait_start = False
self.game_loop()
def end_game_screen(self):
""" display victory or game over screen and let the player restart a game"""
if self.labyrinth.game_over:
self.screen.fill(ORANGE)
go_bg = load_img('go_bg.png')
go_bg_rect = go_bg.get_rect()
self.screen.blit(go_bg, go_bg_rect)
self.screen.blit(go_bg, go_bg_rect)
draw_text("GAME OVER!", FONT_BOLD, 32, WHITE, WIDTH / 2, HEIGHT / 3)
draw_text("Press 'y' to restart and 'n' to quit", FONT, 18, WHITE, WIDTH / 2, 210)
else:
self.screen.fill(GREEN)
win_bg = load_img('win_bg.png')
win_bg_rect = win_bg.get_rect()
self.screen.blit(win_bg, win_bg_rect)
self.screen.blit(win_bg, win_bg_rect)
draw_text("YOU WIN!", FONT_BOLD, 32, WHITE, WIDTH / 2, HEIGHT / 3)
draw_text("Press 'y' to restart and 'n' to quit", FONT, 18, WHITE, WIDTH / 2, 210)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.game_over = False
self.running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_n:
self.game_over = False
self.running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_y:
self.game_over = False
self.labyrinth.set_new_board_game()
def main():
""" execute pygame game """
pygame.init()
pygame.mixer.init()
game = GameWrapper()
game.start_screen()
game.game_loop()
pygame.quit()
quit()
if __name__ == '__main__':
main()
|
f906d731a2ad9d3022a80b18a5e9f8b00610791c | fahira5/guvi | /fahiprime.py | 117 | 3.640625 | 4 | b=int(input())
n=0
for i in range(2,b//2+1):
if(b%i==0):
n=n+1
if(n<=0):
print("yes")
else:
print("no")
|
84571e36b6745dbaab2f7041e06ccaabab8395c3 | M0G1/learning_python | /typing_use.py | 1,887 | 3.984375 | 4 | """
Some examples of using type in python 3.9
And my own test
"""
from typing import Any, TypeVar, NewType, NamedTuple, Callable
import time
import numpy as np
def sum_(vector: list[float]):
sum_val: float = 0
for val in vector:
sum_val += val
return sum_val
TYPE_FILE = "game_with_types.txt"
TIME_FORMAT = "%Y.%m.%d %H:%M:%S"
def main():
with open(TYPE_FILE, "a") as file:
print(f"\nTime of starting {time.strftime(TIME_FORMAT, time.localtime())}", file=file)
vec = [1, 2, 3, 4, 5]
print(f"sum of {vec} is {sum_(vec)}", file=file)
d: dict[int, str] = dict()
d[2] = "5"
d["2"] = 2
print("What is going on? It is working or not?", file=file)
print(d, file=file)
print("This dictionary declare like dict[int, str]", file=file)
# There is needed classes List, Dict from typing
BeastId = NewType("BeastId", int)
print(BeastId(666), file=file)
T = TypeVar("T")
G = TypeVar("G")
Pair = NamedTuple("Pair", (("var1", T), ("var2", G)))
print("New Type", Pair, file=file)
# https://stackoverflow.com/questions/61569324/type-annotation-for-callable-that-takes-kwargs
def fu(func: Callable) -> Callable:
def ans(*args, **kwargs):
print("I'm a decorator", file=file)
func(*args, **kwargs)
print("The creator have remembered gagna style song")
return ans
foo = fu(print)
foo("Decorator + typing")
# ====================================== NumPy =========================================================
# https://numpy.org/devdocs/reference/arrays.dtypes.html#arrays-dtypes
vec_c = np.dtype((np.complex, (2,)))
print("New NumPy type" + str(vec_c), file=file)
if __name__ == '__main__':
main()
|
06c7a2f13c1df93a2a09c30df277b46744480bc5 | atharva07/python-files | /comprehensions.py | 455 | 3.828125 | 4 | # list comprehension
h_letters = []
for letter in 'human':
h_letters.append(letter)
print(h_letters)
h_letters = [letter for letter in 'human']
print(h_letters)
number_list = [x for x in range(20) if x % 2 == 0]
print(number_list)
num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
obj = ["Even" if x % 2 == 0 else "odd" for x in range(10)]
print(obj)
# transpose of matrix
a = [1,4,2,41,24,35,55]
del a[5]
print(a)
|
97636b639dcaf6acb7657517fc8dea7570c8ccfd | mabdulqa/BME160 | /Lab3/proteinParams.py | 6,836 | 3.78125 | 4 | #!/usr/bin/env python3
# Name: Mohammad Abdulqader (mabdulqa)
# Group Members: None
'''
The program overview: ProteinParam.py is a class file with an attached main file that runs
on command line that should be able to take any protein sequence you give it and will give the
sequence length, molar and mass extinction, pI (isoelectric point), molar mass, and amino acid
composition.
'''
class ProteinParam:
'''
The following class ProteinParam is a class that gives the following
paramerters for any given protein sequence:
- amino acid count
- amino acid composition
- pI
- molecular weight
- molar and mass extinction
The class is run by running python ProtienParam.py and then you input any given sequence.
'''
# These tables are for calculating:
# molecular weight (aa2mw), along with the mol. weight of H2O (mwH2O)
# absorbance at 280 nm (aa2abs280)
# pKa of positively charged Amino Acids (aa2chargePos)
# pKa of negatively charged Amino acids (aa2chargeNeg)
# and the constants aaNterm and aaCterm for pKa of the respective termini
# Feel free to move these to appropriate methods as you like
# As written, these are accessed as class attributes, for example:
# ProteinParam.aa2mw['A'] or ProteinParam.mwH2O
aa2mw = {
'A': 89.093, 'G': 75.067, 'M': 149.211, 'S': 105.093, 'C': 121.158,
'H': 155.155, 'N': 132.118, 'T': 119.119, 'D': 133.103, 'I': 131.173,
'P': 115.131, 'V': 117.146, 'E': 147.129, 'K': 146.188, 'Q': 146.145,
'W': 204.225, 'F': 165.189, 'L': 131.173, 'R': 174.201, 'Y': 181.189
}
mwH2O = 18.015
aa2abs280 = {'Y': 1490, 'W': 5500, 'C': 125}
aa2chargePos = {'K': 10.5, 'R': 12.4, 'H': 6}
aa2chargeNeg = {'D': 3.86, 'E': 4.25, 'C': 8.33, 'Y': 10}
aaNterm = 9.69
aaCterm = 2.34
def __init__(self, protein):
'''
This block creates the dictionary which contains all the aa in the sequence and how many times it is in
the sequence.
'''
myProtien = str.upper(protein) # name the input
real = self.aa2mw.keys() # real is a list of the keys of aa
data = [] # empty list that will only add if the aa is in the aa2mw key list.
for amino in myProtien:
if amino in real:
data.append(amino)
space = ''.join(data).split() #seperates the sequence with spaces
self.newData = ''.join(space).upper() #joins the sequence togehter with the spaces and caps the sequence
self.AAtotal = 0 # initial count for total of aa, set to 0 so stuff doesnt break.
self.compostion = {aa: 0 for aa in 'ACDEFGHIKLMNPQRSTVWY'} # dictionary which will house aa: #of aa in seq
for aacid in real:
self.compostion[aacid] = data.count(aacid)
def aaCount(self):
'''
Gives how long the sequence is.
'''
for count in self.compostion.keys():
self.AAtotal += self.compostion[count]
return self.AAtotal
def pI(self):
'''
Gives the stable pH of the sequence for it to be neutral.
'''
high = 14.0
low = 0.0
while ((high - low) > 0.01):
mid = (high + low) / 2
thisCharge = self._charge_(mid)
if thisCharge < 0:
high = mid
else:
low = mid
return mid
def aaComposition(self):
'''
Gives the composition of the sequence.
'''
return self.compostion
def _charge_(self, pH):
'''
Gives the pH of the sequence to be used to find pI.
'''
posCharge = 0
negCharge = 0
nterm = (10 ** self.aaNterm) / ((10 ** self.aaNterm) + (10 ** pH)) # finds the nTerminus value
cterm = (10 ** self.aaCterm) / ((10 ** self.aaCterm) + (10 ** pH)) # finds the cTerminus value
posTerm = 0
negTerm = 0
for aa in self.newData:
if aa in self.aa2chargePos.keys(): # so its done by finding the numerator and denominator seperately
topPos = 10 ** (self.aa2chargePos[aa])
bottomPos = (10 ** self.aa2chargePos[aa]) + (10 ** pH)
posCharge += topPos / bottomPos # then dividing them and adding them to posCharge
if aa in self.aa2chargeNeg.keys(): # then repeat for negative charge
topNeg = 10 ** pH
bottomNeg = (10 ** self.aa2chargeNeg[aa]) + (10 ** pH)
negCharge += topNeg / bottomNeg
posTerm = posCharge + nterm
negTerm = negCharge + cterm
return posTerm - negTerm
def molarExtinction(self):
'''
Gives the molar extinction of the sequence.
'''
molarExt = 0
for aa in self.newData:
if aa in self.aa2abs280.keys():
molarExt += self.aa2abs280[aa]
return molarExt
def massExtinction(self):
'''
Gives the mass extinction of the sequence.
'''
myMW = self.molecularWeight()
return self.molarExtinction() / myMW if myMW else 0.0
def molecularWeight(self):
'''
Gives molecular mass of the sequence.
'''
mass = 0
if self.AAtotal != 0:
dehydrate = (len(self.newData) - 1)
for amino in self.newData:
mass += self.aa2mw.get(amino)
return mass - (dehydrate * self.mwH2O)
else:
return 0.0
# Please do not modify any of the following. This will produce a standard output that can be parsed
import sys
def main():
'''
The main function will produce the desired output; printing out all of the parameters
mentioned earlier. It is made so the standard output can be parsed.
'''
inString = input('protein sequence?')
while inString:
myParamMaker = ProteinParam(inString)
myAAnumber = myParamMaker.aaCount()
print("Number of Amino Acids: {aaNum}".format(aaNum=myAAnumber))
print("Molecular Weight: {:.1f}".format(myParamMaker.molecularWeight()))
print("molar Extinction coefficient: {:.2f}".format(myParamMaker.molarExtinction()))
print("mass Extinction coefficient: {:.2f}".format(myParamMaker.massExtinction()))
print("Theoretical pI: {:.2f}".format(myParamMaker.pI()))
print("Amino acid composition:")
myAAcomposition = myParamMaker.aaComposition()
keys = list(myAAcomposition.keys())
keys.sort()
if myAAnumber == 0: myAAnumber = 1 # handles the case where no AA are present
for key in keys:
print("\t{} = {:.2%}".format(key, myAAcomposition[key] / myAAnumber))
inString = input('protein sequence?')
if __name__ == "__main__":
main()
|
396daf903f438c18201ce6699f455d95708ddeec | jLoven/tensorflow_test | /test1.py | 517 | 3.5 | 4 | # 10 October 2017
# Jackie Loven
import tensorflow as tf
# Each node takes zero or more tensors as inputs and produces a tensor as an output
sess = tf.Session()
# two floating point tensors:
node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
node3 = tf.add(node1, node2)
print("node3:", node3)
print("sess.run(node3):", sess.run(node3))
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
adder_node = a + b # + provides a shortcut for tf.add(a, b)
|
4788fe0bd77bcc1d2086d2d2a54c7e75da2387b6 | addi-sp-sp-4/wordsnack-solver | /solver.py | 1,361 | 4.1875 | 4 | from typing import *
from sys import argv
def is_part_anagram(word: str, charset: str) -> bool:
"""
Checks if `word` can be formed with the characters from `charset`.
Every character in `charset` can only be used once, so:
For `word` = "cookie" and `charset` = "eocik" returns False
For `word` = "cookie" and `charset` = "eociko" returns True
"""
for character in word:
if character not in charset:
return False
charset = charset.replace(character, '', 1)
return True
def main() -> None:
charset = argv[1]
wordlist = argv[2]
min_wordlen = int(argv[3]) if len(argv) == 4 else 2
with open(wordlist, 'r') as wlist:
found = []
while True:
read_word = wlist.readline()
# EOF
if read_word == '':
break
# Remove newline since it is unneeded
read_word = read_word[:-1]
if len(read_word) < min_wordlen:
continue
if is_part_anagram(read_word, charset):
found.append(read_word)
found = sorted(found, key=lambda x: len(x), reverse=True)
for word in found:
print("[+] {}:{}".format(len(word), word))
pass
if __name__ == "__main__":
main()
|
21ba87ae4324f1c20a2308e4ddebdf6b48f75a34 | Raipagnin/Python.exercises | /ex18.py | 192 | 3.71875 | 4 | # calcule seno, coseno e tangente de um angulo dado
import math
ang = float(input('Digite o valor do angulo: '))
print('O valor do angulo sendo {}, o SENO eh {}'.format(ang, math.asin(ang)))
|
07e8631eb58f02aaee1a58ee222180a339fa1129 | LZDOscar/LeetCode | /tree/67AddBinary.py | 2,271 | 3.5625 | 4 | class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num1 = a
num2 = b
len1 = len(num1)-1
len2 = len(num2)-1
result = ''
flag = 0
while(len1>=0 and len2>=0):
temp = int(num1[len1]) + int(num2[len2]) + flag
flag = temp // 2
temp = temp % 2
result += str(temp)
len1 -= 1
len2 -= 1
while(len1>=0):
temp = int(num1[len1]) + flag
flag = temp // 2
temp = temp % 2
result += str(temp)
len1 -= 1
while(len2>=0):
temp = int(num2[len2]) + flag
flag = temp // 2
temp = temp % 2
result += str(temp)
len2 -= 1
if(flag):
result += '1'
return result[::-1]
// not use // and %
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num1 = a
num2 = b
len1 = len(num1)-1
len2 = len(num2)-1
result = ''
flag = 0
while(len1>=0 and len2>=0):
temp = flag
flag = 0
if num1[len1] == '1' and num2[len2] == '1':
flag = 1
elif (num1[len1] == '0' and num2[len2] == '0'):
flag = 0
else:
flag = 0
temp += 1
if(temp == 2):
flag = 1
temp = 0
result += str(temp)
len1 -= 1
len2 -= 1
while(len1>=0):
temp = flag
flag = 0
if num1[len1] == '1':
temp += 1
if(temp == 2):
flag = 1
temp = 0
result += str(temp)
len1 -= 1
while(len2>=0):
temp = flag
flag = 0
if num2[len2] == '1':
temp += 1
if(temp == 2):
flag = 1
temp = 0
result += str(temp)
len2 -= 1
if(flag):
result += '1'
return result[::-1]
|
d49b441f6d4de4a7a85308b37e2e52e82e38af58 | griffinhiggins/100AlgorithmsChallenge | /Completed/py/palindromeRearranging/palindromeRearranging.py | 395 | 3.6875 | 4 | def palindromeRearranging(s):
sList = list(s)
sSet = set(s)
oddCount = 0
for i in sSet:
if sList.count(i) % 2 == 1:
oddCount += 1
if oddCount > 1:
return False
return True
print(palindromeRearranging("a"))
print(palindromeRearranging("ab"))
print(palindromeRearranging("aaabbb"))
print(palindromeRearranging("aabb"))
|
03f3959acdbfda8de2e3a1ffdceb37a4ea3f2c76 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2407/60648/267164.py | 446 | 3.5625 | 4 | class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = map(int,date.split('-'))
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year%4==0 and year%100!=0) or (year%400==0) : months[2] += 1
res = 0
for i in range(month): res += months[i]
res += day
return res
if __name__=="__main__":
s=input()
x=Solution().dayOfYear(s)
print(x) |
5e666a9cf9d682f287bc67e313baa9946a367612 | poojamadan96/code | /Inheritance/superClassConstructor.py | 462 | 4.09375 | 4 | #super class constructor
# In default case the constructor of dervided class is fired
class base:
def __init__(self):
print("fire House")
def show(self):
print("HEllo")
class derived(base):
def __init__(self):
super().__init__() # It will call teh constructor of base class first and then will call it sel
print("Fire Derived")
def display(self):
print("Welcome")
ob=derived()
ob.show()
ob.display()
'''fire House
Fire Derived
HEllo
Welcome
'''' |
bcd95d774a989f244c0b040f6f92682bac925ce6 | Deepbiogroup/affiliation_parser | /affiliation_parser/parser/parse_email.py | 513 | 3.8125 | 4 | import re
def parse_email(affil_text: str):
"""Find email from given string
email format RFC is extremely complicated:
https://www.ietf.org/rfc/rfc5322.txt
a simple re from http://emailregex.com/
"""
texts = affil_text.split(' ')
match = re.search(r"([a-zA-Z0-9.+_-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)",
texts[-1])
if match is not None:
email = match.group()
# email.rstrip('.')
else:
email = ""
return email
|
a35a319192bcec6c9e5506b28b26b79181d7ad81 | carfri/D0009E-lab | /labb3-1.py | 1,531 | 3.5625 | 4 | # -*- coding: cp1252 -*-
print('Vlkommen till den ultimata labb menyn!')
print
print('1: bounce')
print('2: tvrsumma')
print('3: newton-raphson')
print('4: avsluta programmet')
def bounce(stuts):
if stuts !=0:
print stuts,
bounce(stuts-1)
print stuts,
return
else:
print stuts,
def numsum(n):
if n > 0:
n = n % 10 + numsum(n/10)
k=n
def derivative(f, x, h):
k =(1.0/(2*h))*(f(x+h)-f(x-h))
return k
def solve(f, x0, h):
lastX = x0
new = 0.0
while (abs(lastX - new) > h) or lastX==new:
new = lastX
lastX = lastX - f(lastX)/derivative(f, lastX, h)
return lastX
def f(x):
return x**2-1
def numsum(n):
if n > 0:
n = n % 10 + numsum(n/10)
k=n
return n
loop = 1
while loop ==1:
print
val = input('vlj vilket programm som ska kras: ')
val = int(val)
if val == 1:
stuts = input('mata in talet du vill studsa: ')
stuts = int(stuts)
bounce(stuts)
elif val == 2:
n = input('mata in det tal du vill berkna tvrsumman av: ')
print numsum(n)
elif val == 3:
x0 = input('mata in startvrdet: ')
x0 = int(x0)
h = 0.1
print solve(f, x0, h)
elif val == 4:
loop = 0
else:
print('mata in ett vrde 1-4.')
|
613819c4af928d41a9341d8fa28eac9ba4064b4e | Geoffrey-Kong/CCC-Solutions | /'11/Junior/CCC '11 J2 - Who Has Seen The Wind?.py | 333 | 3.8125 | 4 | h = int(input())
M = int(input())
t = 1
while True:
A = (-6 * (t ** 4)) + (h * (t ** 3)) + (2 * (t ** 2) + t
if A <= 0:
print("The balloon first touches ground at hour:")
print(t)
break
elif t == M:
print("The balloon does not touch ground in the given time.")
break
elif A != 0:
t += 1
|
614cb0ac0868e8187149582cba87370db8be93f8 | sourabbanka22/Competitive-Programming-Foundation | /Trie/trieConstruction.py | 1,379 | 3.9375 | 4 | # Do not edit the class below except for the
# populateSuffixTrieFrom and contains methods.
# Feel free to add new properties and methods
# to the class.
class Trie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateTrieFrom(self, string):
# Write your code here.
current = self.root
for char in string:
if char not in current:
current[char] = {}
current = current[char]
current[self.endSymbol] = True
def contains(self, string):
# Write your code here.
pass
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuffixTrieFrom(self, string):
# Write your code here.
current = self.root
for index1 in range(len(string)):
for index2 in range(index1, len(string)):
if string[index2] not in current:
current[string[index2]] = {}
current = current[string[index2]]
current[self.endSymbol] = True
current = self.root
def containsSuffix(self, string):
# Write your code here.
current = self.root
for char in string:
if char not in current:
return False
current = current[char]
if self.endSymbol in current:
return True
else:
return False
|
d17e9e431e2d28a6835f8c4b794eff7b7c755843 | b72u68/coding-exercises | /Project Euler/p1.py | 192 | 3.984375 | 4 | # Multiples of 3 and 5
def main():
sum = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
if __name__ == "__main__":
print(main())
|
a0e3e16a99160ed3cf36633313c6dea9a7ef04f1 | mohanraj1311/leetcode-2 | /containerWithMostWater/main.py | 847 | 3.859375 | 4 | # Given n non-negative integers a1, a2, ..., an, where each represents a
# point at coordinate (i, ai). n vertical lines are drawn such that the
# two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which
# together with x-axis forms a container, such that the container contains
# the most water.
# Note: You may not slant the container.
class Solution:
# @return an integer
def maxArea(self, height):
l, r = 0, len(height) - 1
currMax = min(height[l], height[r]) * (r - l)
while l < r:
currMax = max(currMax, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return currMax
if __name__ == '__main__':
s = Solution()
print s.maxArea([2, 4, 1, 3])
|
dbaba95f7871432c4035864b26f1d724e76dad1c | tahoeivanova/excersices_and_memory_examples | /Documents/MY_PYTHON/memory/practice.py | 895 | 4.09375 | 4 | # Найти площадь и периметр прямоугольного треугольника по двум заданным катетам.
class Triangle:
__slots__ = ('x', 'y')
# два катета
def __init__(self, x, y):
self.x = x
self.y = y
# Площадь треугольника равна половине площади прямоуглоьника, сторонами которого являются катеты.
def square(self):
return self.x * self.y / 2
# Периметр - сложение всех сторон треугольника.
def perimeter(self):
# Найдем гипотенузу.
c = (self.x**2 + self.y**2)**0.5
return c + self.x + self.y
if __name__ == '__main__':
triangle = Triangle(1,2)
print(triangle.square())
print(round(triangle.perimeter(),2))
|
74f99073cfec31c23d193f1f919dbd32ef76773b | sakthi5006/epi-python | /Arrays/5.3-multiplyarb.py | 1,198 | 3.953125 | 4 | # Write a program that takes two arrays representing integers and returns
# an array of integers representing their product.
# for example take 193707721 x -761838257287 = -147573952589676412927
# inputs are in array format and function will return [-1, 4, 7, 5, 7...] so on
A = [1,2,0]
B = [1,2,9]
C = [0, 0]
def multArb(A, B):
# set the sign according to the first digit's sign
sign = -1 if (A[0] < 0) ^ (B[0] < 0) else 1
# make all ints we work with positive
A[0], B[0] = abs(A[0]), abs(B[0])
# make an array sized to be the length of A and B together since that's the max from multiplying
res = [0] * (len(A) + len(B))
# starting from the end of both
for i in reversed(range(len(A))):
for j in reversed(range(len(B))):
print(res)
res[i + j + 1] += A[i] * B[j]
print(res)
res[i + j] += res[i + j + 1] // 10
print(res)
res[i + j + 1] %= 10
print(res)
# removes the leading zeroes or returns 0 if there's nothing to go through
res = res[next((i for i, x in enumerate(res) if x != 0), len(res)):] or [0]
return [sign * res[0]] + res[1:]
print(multArb(A, B))
|
0f91698e1112f9e0d2c3cd3d707b505ae1edd3c7 | MarcosLazarin/Curso-de-Python | /ex024.py | 329 | 3.9375 | 4 | #Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'Santo'.
cidade = str(input('Digite o nome de uma cidade: ')).strip()
n = cidade.upper().split()
print('SANTO' in n[0])
#Pode ser resolvido assim também:
cidade = str(input('Digite a cidade:')).strip()
print(cidade[:5].upper() == 'SANTO') |
04ab2955ab2ad791fa3acf8b0549729886162dd4 | slavenran/time_calculator | /time_calculator.py | 1,948 | 3.875 | 4 | def add_time(start, duration, day = ''):
new_time = ''
day_index = None
time, am_pm = start.split()
start_h = int(time.split(':')[0])
start_m = int(time.split(':')[1])
duration_h = int(duration.split(':')[0])
duration_m = int(duration.split(':')[1])
final_day = ''
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
days_lower = [x.lower() for x in days]
if day != '': day_index = days_lower.index(day.lower())
minutes = start_h*60+start_m+duration_h*60+duration_m
leftover_minutes = minutes%60
hours = minutes//60
if am_pm == 'PM':
hours += 12
leftover_hours = hours%24
day_count = hours//24
final_daytime = 'AM'
final_minutes = str(leftover_minutes)
if day_index != None:
final_day = day_index+day_count
if final_day > 6:
final_day = final_day - (final_day//7 * 7)
final_day = ', ' + days[final_day]
if leftover_hours >= 12:
leftover_hours -= 12
final_daytime = 'PM'
if leftover_hours == 0:
leftover_hours = 12
if leftover_minutes < 10:
final_minutes = '0' + final_minutes
new_time = str(leftover_hours) + ':' + final_minutes + ' ' + final_daytime + final_day
if day_count > 0:
if day_count == 1:
new_time += ' (next day)'
else: new_time += f' ({day_count} days later)'
print(new_time)
add_time("3:00 PM", "3:10")
# Returns: 6:10 PM
add_time("11:30 AM", "2:32", "Monday")
# Returns: 2:02 PM, Monday
add_time("11:43 AM", "00:20")
# Returns: 12:03 PM
add_time("10:10 PM", "3:30")
# Returns: 1:40 AM (next day)
add_time("11:43 PM", "24:20", "tueSday")
# Returns: 12:03 AM, Thursday (2 day_count later)
add_time("6:30 PM", "205:12")
# Returns: 7:42 AM (9 day_count later)
add_time("8:16 PM", "466:02", "tuesday") |
136309a43fd2d80cf39e5e5e73ff645d778edbc6 | akshat343/Python-Programming | /Random Python Programs/fibonacci1.py | 246 | 3.828125 | 4 | def fibbonacchiseries(n):
if n ==1:
return 0
elif n==2:
return 1
else:
return fibbonacchiseries(n-1)+fibbonacchiseries(n-2)
n= int(input("entre ur number"))
print("fibbonacchi series : ",fibbonacchiseries(n))
|
9ec103bea01c8232d6cf4805f010efc3c1e54e84 | xfhy/LearnPython | /廖雪峰老师的教程/1. 基础/使用dict(字典)和set.py | 953 | 4.21875 | 4 | '''
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
'''
d = {"1":"1"}
print(d)
print(d["1"])
# key是1 值是1 key类型可以不一致
d = {"1":1,"2":2,"3":3,4:'4'}
print(d["2"])
d[4] = "5" # 修改
d[6] = '6' # 增加
# print(d[7]) key不存在 则会报错
print('7' in d) # 判断key是否存在字典中,避免不存在key时的报错
# 是通过dict提供的get()方法,如果key不存在,可以返回None,或者自己指定的value:
d.get("1") #
d.get("1",-1)
# 删除
d.pop("1")
print(d)
'''
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
要创建一个set,需要提供一个list作为输入集合:
'''
s = set([1,2,3,3]) #多余的元素会被过滤 顺序是无序的
s.add("1") #同一集合可存入多种类型的元素
print(s) # {1, 2, 3} |
9acd4f37e9a0108cd4aa471e96af97cc60b225b3 | gokou00/python_programming_challenges | /coderbyte/NumberSearch.py | 433 | 3.90625 | 4 | def NumberSearch(string):
numArr = []
count = 0
for x in string:
if x.isdigit():
numArr.append(int(x))
#count +=1
if x.isalpha():
count+= 1
arrSum = sum(numArr)
#print(arrSum)
#print(count)
#print( round(arrSum/float(count)) )
return int(round(arrSum/float(count)))
print(NumberSearch("Hello6 9World 2, Nic8e D7ay!")) |
0dd94f9aaa783a317c8c38d84770bf91f94b3105 | mohmilki/IF1311-10220013 | /perulangan.py | 164 | 4.0625 | 4 | #perulangan for
for i in range (0,5,1):
print("for loop, i=", i)
#perulangan While
i = 0
while (i <=5):
print("While loop, i = ", i)
i += 1 |
57dee3cfacf429eec7cacd240b76859d723769ae | rarezhang/data_structures_and_algorithms_in_python | /exercises/ch05_array_based_sequences/ch5_exercise.py | 9,332 | 3.703125 | 4 | """
exercises
"""
import sys
import ctypes
import random
# R-5.4
# Our DynamicArray class, as given in Code Fragment 5.3, does not support
# use of negative indices with getitem . Update that method to better
# match the semantics of a Python list.
# R-5.6
# Give an improved implementation
# of the insert method, so that, in the case of a resize, the elements are
# shifted into their final position during that operation, thereby avoiding the
# subsequent shifting
# C-5.16
# Implement a pop method for the DynamicArray class, given in Code Fragment
# 5.3, that removes the last element of the array, and that shrinks the
# capacity, N, of the array by half any time the number of elements in the
# array goes below N / 4.
class DynamicArray:
"""
a dynamic array class akin to a simplified python list
"""
def __init__(self):
"""
create an empty array
:return:
"""
self._n = 0 # count actual elements
self._capacity = 1 # default array capacity
self._A = self._make_array(self._capacity) # low-level array
def __len__(self):
"""
return # of elements stored in the array
:return:
"""
return self._n
def __getitem__(self, k):
"""
# R-5.4
return element at index k
:param k: index k
:return:
"""
if 0 <= k < self._n:
return self._A[k] # retrieve from array
elif -self._n <= k <= -1:
return self._A[k + self._n]
else:
raise IndexError('Invalid Index')
def append(self, obj):
"""
add object to end of the array
:param obj:
:return:
"""
if self._n == self._capacity: # not enough room
self._resize(2*self._capacity) # double capacity
self._A[self._n] = obj
self._n += 1
def _resize(self, c): # nonpublic utity
"""
# C-5.16
resize internal array to capacity c
:param c:
:return:
"""
B = self._make_array(c) # new (bigger) array
for k in range(self._n): # for each existing value
B[k] = self._A[k]
self._A = B # use the bigger array
self._capacity = c
def insert(self, k, value):
"""
# R 5.6
need two (non-nested) loops.
:param k:
:param value:
:return:
"""
if self._n == self._capacity:
B = self._make_array(2 * self._capacity)
for j in range(0, k):
B[j] = self._A[j]
for j in range(self._n, k, -1):
B[j] = self._A[j - 1]
self._A = B
self._capacity = 2 * self._capacity
else:
for j in range(self._n, k, -1):
self._A[j] = self._A[j-1]
self._A[k] = value
self._n += 1
def remove(self, value):
"""
remove first occurrence of value (or raise ValueError)
do not consider shrinking the dynamic array in this version
:param value:
:return:
"""
for k in range(self._n):
if self._A[k] == value:
for j in range(k, self._n -1):
self._A[j] = self._A[j+1]
self._A[self._n - 1] = None # garbage collection
self._n -= 1
return # exit immediately if find one
raise ValueError('vale not found') # only reached if no match
def remove_all(self, value):
"""
# C-5.25
removes all occurrences of value from the given list
:param value:
:return:
"""
B = self._make_array(self._capacity)
count = 0
for k in range(self._n):
if self._A[k] != value:
B[count] = self._A[k]
count += 1
self._A = B
self._n = count
def pop(self):
"""
# C-5.16
removes the last element of the array
shrinks the capacity of the array
:return: last element of the array
"""
p = self._A[self._n - 1] # the last element of the array
self._A[self._n - 1] = None # garbage collection
self._n -= 1
if 0 < self._n < self._capacity * 0.25:
self._resize(int(0.5 * self._capacity)) # shrink capacity
return p
def _make_array(self, c): # nonpublic utility
"""
return new array with capacity c
:param c:
:return:
"""
return (c * ctypes.py_object)() # see ctypes documentation
dynamic_array = DynamicArray()
print("create dynamic array object", dynamic_array, dynamic_array._n, dynamic_array._capacity)
dynamic_array.append(4)
print("append a new element", dynamic_array, dynamic_array._n, dynamic_array._capacity)
dynamic_array.insert(0, 489)
dynamic_array.insert(0, 21)
dynamic_array.insert(1, 25)
dynamic_array.insert(1, 23)
dynamic_array.insert(1, 23)
print("insert a new element at index:0", dynamic_array, dynamic_array._n, dynamic_array._capacity)
print("test positive indices:", dynamic_array[0], dynamic_array[1])
print("test negative indices:", dynamic_array[-1], dynamic_array[-2])
print("remove all occurrences of value", dynamic_array.remove_all(23))
# [21,25,489,4]
print("pop out last item:", dynamic_array.pop())
print("pop out last item:", dynamic_array.pop())
print("pop out last item:", dynamic_array.pop())
print("pop out last item:", dynamic_array.pop())
# R-5.7
# Let A be an array of size n ≥ 2 containing integers from 1 to n − 1, inclusive,
# with exactly one repeated. Describe a fast algorithm for finding the
# integer in A that is repeated.
def find_1_repeat(A):
"""
:param A: an array of size n>=2
:return:
"""
len_A = len(A)
assert len_A >= 2, 'A should be an array of size n>=2'
sum_real = (len_A -1 ) * len_A / 2 # n(n+1)/2
sum_A = sum(A)
return sum_A - sum_real
ay = [1,2,3,2]
print('the integer that is repeated: {}'.format(find_1_repeat(ay)))
# R-5.10
# Caesar cipher
class CaesarCipher:
"""
class for doing encryption and decryption using a Caesar cipher
"""
def __init__(self, shift):
"""
construct Caesar cipher using given integer shift for rotation
:param shift:
:return:
"""
self._forward = "".join([chr((k+shift)%26 + ord('A')) for k in range(26)]) # will store as string
self._backward = "".join([chr((k-shift)%26 + ord('A')) for k in range(26)]) # since fixed
cc_test = CaesarCipher(1)
print(cc_test._forward, cc_test._backward)
# R-5.11
def sum_standard_control(A):
"""
:param A: python list of lists
:return:
"""
n = len(A)
sum_A = 0
for a in A:
if len(a) != n:
raise ValueError('should be n x n list')
for aa in a:
sum_A += aa
return sum_A
A = [[1,2,3],[4,5,6],[7,8,0]]
print('the sum of A: {}'.format(sum_standard_control(A)))
# R-5.12
def sum_list_comprehension(A):
"""
:param A: python list of lists
:return:
"""
return sum([sum(a) for a in A])
print('the sum of A: {}'.format(sum_list_comprehension(A)))
# C-5.14
# takes a Python list and rearranges it so that every possible ordering is equally likely
A = [1,2,3,4,5]
print(A)
random.shuffle(A) # shuffle from random module, return None
print(A)
# you own version of shuffle:
# Consider randomly shuffling the deck one card at a time
def random_shuffle(A):
"""
:param A: python list
:return: shuffled A
"""
len_A = len(A)
for i in range(len_A):
j = random.randrange(len_A)
A[i], A[j] = A[j], A[i]
return A
random_shuffle(A)
print(A)
# C-5.26
# Let B be an array of size n ≥ 6 containing integers from 1 to n − 5, inclusive,
# with exactly five repeated. Describe a good algorithm for finding the
# five integers in B that are repeated
# hints: It might help to sort B.
def find_n_repeat(B):
"""
:param B: python list, n>=6, with exactly five repeated
:return:
"""
B = sorted(B)
for i in range(len(B)-1):
if B[i] == B[i+1]:
return B[i]
B = [1,1,1,1,1,1]
print('find n repeat:', find_n_repeat(B))
B = [2,2,2,2,2,2,1,3]
print('find n repeat:', find_n_repeat(B))
# C-5.27
# Given a Python list L of n positive integers, each represented with k =
# ceiling(log n) + 1 bits, describe an O ( n ) -time method for finding a k-bit integer
# not in L.
# C-5.29
# natural join
def natural_join(A, B):
"""
:param A: table A (x, y)
:param B: table B (y, z)
:return: (x, y, z)
"""
C = list()
for a in A:
for b in B:
if a[1] == b[0]:
C.append((a[0], a[1], b[1]))
return C
table_A = [('wenli', '001'), ('alex', '002'), ('cate', '003')]
table_B = [('001', 'A'), ('002', 'B'), ('003', 'D')]
print(natural_join(table_A, table_B))
# Be sure to allow for the case where every pair (x , y) in A and
# every pair (y , z) in B have the same y value.
table_A = [('wenli', '001'), ('alex', '001'), ('cate', '001')]
table_B = [('001', 'A'), ('001', 'B'), ('001', 'D')]
print(natural_join(table_A, table_B))
# C-5.31
def sum_recursion(A):
"""
:param A: python list of lists
:return:
"""
pass
|
f46a01c1622a761cf10194d3170a02b5d21518e9 | SoyamDarshan/Python_data_structures_and_algorithms- | /BinarySearchTree.py | 2,643 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 21:48:58 2019
@author: soyam
"""
class BinarySearchTree:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __init__(self):
self.root = None
def is_root_empty(self):
return self.root is None
def find_position(self, data):
curr = self.root
while curr:
prev = curr
if data <= curr.data:
if curr.left is None:
break
curr = curr.left
else:
if curr.right is None:
break
curr = curr.right
return curr, prev
def add_node(self, data):
new_node = self.Node(data)
if self.is_root_empty():
self.root = new_node
else:
curr, prev = self.find_position(data)
curr = new_node
if(data <= prev.data):
prev.left = curr
else:
prev.right = curr
def print_preorder(self, root):
if root:
print(root.data)
self.print_preorder(root.left)
self.print_preorder(root.right)
def preorder(self):
print("preorder")
self.print_preorder(self.root)
def print_inorder(self, root):
if root:
self.print_inorder(root.left)
print(root.data)
self.print_inorder(root.right)
def inorder(self):
print("inorder")
self.print_inorder(self.root)
def print_postorder(self, root):
if root:
self.print_postorder(root.left)
self.print_postorder(root.right)
print(root.data)
def postorder(self):
print("postorder")
self.print_postorder(self.root)
def print_leaf_nodes(self, root):
if root:
self.print_leaf_nodes(root.left)
self.print_leaf_nodes(root.right)
if root.left is None and root.right is None:
print(root.data)
def print_leaf(self):
print("leaf nodes")
self.print_leaf_nodes(self.root)
if __name__ == '__main__':
name = BinarySearchTree()
name.add_node(16)
name.add_node(5)
name.add_node(11)
name.add_node(17)
name.add_node(19)
name.add_node(31)
name.add_node(12)
name.add_node(17)
name.add_node(21)
name.preorder()
name.inorder()
name.postorder()
name.print_leaf()
|
ed2eb97269c3dc59ee3d3980e6b2524b410f737c | RocqJones/data-structures-Hackerank-problem-solving | /1.arrays/arr.py | 393 | 3.609375 | 4 | import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
a.reverse()
return a
if __name__ == '__main__':
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
reverseArray(arr)
# res = reverseArray(arr)
"""
Sample input
4
1 4 3 2
Sample output
2 3 4 1
""" |
91e30d602dadae4e5c02e4f9cf3f17a0c7233d61 | gitbxo/puzzles | /knapsack/src/knapsack.py | 7,532 | 4.15625 | 4 | '''
Knapsack problem
This solves the multi-dimensional knapsack problem
To run, use the following command:
python3 knapsack.py
The flag --print-stack will print the calls to solve_knapsack:
python3 knapsack.py --print-stack
'''
import sys
PRINT_LOOP = False
PRINT_STACK = False
def check_fit(item, remaining):
for r in range(len(item)):
if item[r] > remaining[r]:
return False
return True
def solve_knapsack(items, capacity):
'''solve_knapsack
items is a list of tuples containing: name, value, w1, w2, ...
capacity is a list of capacities: c1, c2, ...
The sum of w1 for selected items may not exceed c1
Similarly, sum of w2 for selected items may not exceed c2, ...
returns tuple of selected items and value with remaining capacity
'''
if PRINT_STACK:
print(f'Called solve {[i[0] for i in items]} for ' + str(
capacity if len(capacity) > 1 else capacity[0]))
selected = []
# First item is value, rest is remaining capacity
remaining = [0] + [c for c in capacity]
if not capacity:
selected, remaining = ([], ['no capacity provided'])
if PRINT_STACK:
print(f'returning {selected} {remaining}')
return selected, remaining
if not items:
selected, remaining = ([], ['no items provided'])
if PRINT_STACK:
print(f'returning {selected} {remaining}')
return selected, remaining
# Exclude items that don't fit
items = [i for i in items if check_fit(i[2:], capacity)]
if not items:
selected, remaining = ([], ['no items fit'])
if PRINT_STACK:
print(f'returning {selected} {remaining}')
return selected, remaining
for i in range(len(items)):
if PRINT_LOOP:
print(f'Called loop {i} for {items[i]} {[j[0] for j in items]} {selected}')
does_fit = check_fit(items[i][2:], remaining[1:])
if does_fit:
for r in range(len(capacity)):
remaining[1 + r] -= items[i][2 + r]
remaining[0] += items[i][1]
selected.append(items[i][0])
continue
# Does not fit
if not selected:
# if there is nothing selected, skip item
continue
if i == 1 and items[0][1] >= items[i][1]:
# Does not fit and selected item has higher value
continue
# Find max of first i items with reduced capacity
if PRINT_LOOP:
print(f'Checking {items[i]} against {selected}')
too_big = False
new_capacity = [0] * len(capacity)
for c in range(len(capacity)):
new_capacity[c] = capacity[c] - items[i][2 + c]
if new_capacity[c] < 0:
# item i is too big, skip it
too_big = True
break
if too_big:
continue
new_selected, new_remaining = ([], [])
new_items = [j for j in items[:i] if check_fit(j[2:], new_capacity)]
max_value = sum([j[1] for j in [items[i]] + new_items])
if max_value <= remaining[0]:
# including item i will not give more value
continue
elif len(new_items) == 1:
new_selected = [new_items[0][0]]
new_remaining = [new_items[0][1]] + [
new_capacity[c] - new_items[0][2 + c]
for c in range(len(new_capacity))]
elif new_items:
new_selected, new_remaining = solve_knapsack(new_items, new_capacity)
if new_selected and new_remaining[0] + items[i][1] > remaining[0]:
# including item i gives more value
new_remaining[0] += items[i][1]
remaining = new_remaining
selected = new_selected + [items[i][0]]
elif items[i][1] > remaining[0]:
# including item i gives more value
remaining = [items[i][1]] + new_capacity
selected = [items[i][0]]
if PRINT_STACK:
print(f'returning {selected} {remaining}')
return (selected, remaining)
def validate_and_solve_knapsack(items, capacity):
'''validate_and_solve_knapsack
validates parameters and calls solve_knapsack
items is a list of tuples containing: name, value, w1, w2, ...
capacity is a list of capacities: c1, c2, ...
The sum of w1 for selected items may not exceed c1
Similarly, sum of w2 for selected items may not exceed c2, ...
returns tuple of selected items and value with remaining capacity
'''
if type(capacity).__name__ not in ['list', 'tuple']:
return ([], ['capacity must be a list of int'])
capacity_type = list(set([type(c).__name__ for c in capacity]))
if len(capacity_type) != 1 or capacity_type[0] != 'int':
return ([], ['capacity must be a list of int'])
num_weights = len(capacity)
if num_weights <= 0:
return ([], ['there must be at least one weight'])
if min(capacity) <= 0:
return ([], ['all weights must be +ve'])
if not items:
return ([], ['must have at least one item'])
if len(set([i[0] for i in items])) != len(items):
return ([], ['item names are not unique'])
item_length = [len(i) for i in items]
if (min(item_length) != num_weights + 2) or (
max(item_length) != num_weights + 2):
return ([], [f'items must have name, value and {num_weights} weights'])
for item in items:
item_type = list(set([type(i).__name__ for i in item[1:]]))
if len(item_type) != 1 or item_type[0] != 'int':
return ([], ['all item values and weights must be int'])
if min([i[1] for i in items]) <= 0:
return ([], ['all item values must be > 0'])
if min([min(i[2:]) for i in items]) < 0:
return ([], ['all item weights must be >= 0'])
# Use greedy algorithm - sort by max value and then by least weight
sorted_items = sorted(items, key=lambda x : (-x[1], sum(x[2:])))
return solve_knapsack(sorted_items, capacity)
def print_knapsack(sack):
return f'value = {sack[1][0]}, items = ' + str(
sorted(sack[0]))
if __name__ == '__main__':
if '--print-loop' in sys.argv:
PRINT_LOOP = True
if '--print-stack' in sys.argv:
PRINT_STACK = True
print(print_knapsack(validate_and_solve_knapsack(
[('A', 1, 1), ('A', 6, 2), ('C', 10, 3), ('D', 16, 5)], (7,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 10, 10), ('B', 11, 11), ('C', 12, 12)], (30,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 10, 10), ('B', 11, 11), ('C', 12, 12)], (33,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 20, 15), ('B', 13, 8), ('C', 11, 8), ('D', 5, 5)], (20,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 11, 8), ('B', 13, 8), ('C', 20, 15), ('D', 5, 5)], (20,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 3, 3), ('B', 5, 5), ('C', 3, 3)], (6,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 1, 1), ('B', 6, 2), ('C', 10, 3), ('D', 16, 5)], (7,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 1, 1), ('B', 6, 2), ('C', 10, 3), ('D', 16, 5)], (6,))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 1, 1, 3), ('B', 6, 2, 2), ('C', 10, 3, 5), ('D', 16, 5, 4)],
(7, 7))))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 2, 1, 20),
('B', 2, 1, 25),
('C', 3, 2, 30),
('D', 2, 3, 35),
('E', 5, 3, 40),
('F', 6, 3, 40),
('G', 2, 3, 45),
('H', 5, 3, 45),
('I', 7, 4, 50)],
(20, 245)
)))
print(print_knapsack(validate_and_solve_knapsack(
[('A', 10, 2, 512, 10),
('B', 20, 4, 256, 15),
('C', 30, 8, 128, 20),
('D', 40, 16, 64, 25),
('E', 50, 32, 32, 30),
('F', 60, 64, 16, 35),
('G', 70, 128, 8, 40),
('H', 80, 140, 4, 45),
('I', 90, 160, 2, 50),
('J', 100, 180, 1, 55)],
(300, 300, 100)
)))
|
f93a8c83bc5f9e7e93a7894aedc5d5e114df4a93 | Morgassa/Code_Wars | /Beginner Series #3 Sum of Numbers.py | 274 | 3.609375 | 4 | def get_sum(a,b):
list=[]
i = min(a, b)
f = max(a, b)
list.append(i)
while list[-1] < f:
i = i+1
list.append(i)
# print(list)
return sum(list)
# def get_sum(a,b):
# eae
# sdsd
# return sum(range(min(a, b), max(a, b) + 1)) |
d02f76a6488876373683edc2804918f24c594b53 | zidbon-z/pyProjects | /mtg/mtg.py | 22,230 | 3.703125 | 4 |
from tkinter import *
#from PIL import ImageTk,Image
import sqlite3
root = Tk()
root.title('Magic the Gathering Card Catalog')
root.geometry("400x210")
# Databases
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
#Create table (only use once to create the table, then comment out)
'''
c.execute("""CREATE TABLE catalog (
card_name text,
card_type text,
card_race text,
card_class text,
card_color text,
card_manacost integer,
card_power integer,
card_toughness integer,
card_oracle text,
card_deck text,
card_deck_quantity integer
)""")
'''
# Create a window that lists all cards in catalog
def list_cards():
global list_cards_w
list_cards_w = Tk()
list_cards_w.title('All Cards in Catalog')
list_cards_w.geometry('400x800')
# Create a title for the Window
lcards_window_label = Label(list_cards_w, text="List of All Cards in Catalog", font=('Arial, 20'))
lcards_window_label.grid(row=0, column=0, columnspan=2)
# Create titles for the Columns
c_title_id_label = Label(list_cards_w, text="ID", width=20)
c_title_id_label.grid(row=1, column=0, ipady=10)
c_title_name_label = Label(list_cards_w, text="Card Name ", width=30)
c_title_name_label.grid(row=1, column=1, ipady=10)
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
# Query the Database
c.execute("SELECT *, oid FROM catalog")
show_cards = c.fetchall()
#print(show_cards)
# Loop Thru Results
print_cards = ''
print_cards_id = ''
print_cards_name = ''
for card in show_cards:
# Format the query output
print_cards_id += str(card[11]) + "\n"
query_label = Label(list_cards_w, text=print_cards_id)
query_label.grid(row=2, column=0)
print_cards_name += str(card[0]) + "\n"
query_label2 = Label(list_cards_w, text=print_cards_name)
query_label2.grid(row=2, column=1)
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Create a button to close the list window
close_list_btn = Button(list_cards_w, text="Close", command=close_list)
close_list_btn.grid(row=3, column=1, pady=10, padx=10, ipadx=50)
# Create a Window to Add a Card
def add_card():
global add_card_w
add_card_w = Tk()
add_card_w.title('Add a Card to Catalog')
add_card_w.geometry("400x400")
# Create Global Variables for Text Box Names
global c_name
global c_type
global c_race
global c_class
global c_color
global c_manacost
global c_power
global c_toughness
global c_oracle
global c_deck
global c_deck_quantity
# Create a title for the Window
acards_window_label = Label(add_card_w, text="Add a Card to Catalog", font=('Arial, 20'))
acards_window_label.grid(row=0, column=0, columnspan=2)
# Create Text Boxes
c_name = Entry(add_card_w, width=30)
c_name.grid(row=1, column=1, padx=20, pady=(10, 0))
c_type = Entry(add_card_w, width=30)
c_type.grid(row=2, column=1,)
c_race = Entry(add_card_w, width=30)
c_race.grid(row=3, column=1,)
c_class = Entry(add_card_w, width=30)
c_class.grid(row=4, column=1,)
c_color = Entry(add_card_w, width=30)
c_color.grid(row=5, column=1,)
c_manacost = Entry(add_card_w, width=30)
c_manacost.grid(row=6, column=1,)
c_power = Entry(add_card_w, width=30)
c_power.grid(row=7, column=1,)
c_toughness = Entry(add_card_w, width=30)
c_toughness.grid(row=8, column=1,)
c_oracle = Entry(add_card_w, width=30)
c_oracle.grid(row=9, column=1,)
c_deck = Entry(add_card_w, width=30)
c_deck.grid(row=10, column=1,)
c_deck_quantity = Entry(add_card_w, width=30)
c_deck_quantity.grid(row=11, column=1)
# Create Text Box Lables
c_name_label = Label(add_card_w, text="Card Name")
c_name_label.grid(row=1, column=0, pady=(10, 0))
c_type_label = Label(add_card_w, text="Card Type")
c_type_label.grid(row=2, column=0)
c_race_label = Label(add_card_w, text="Card Race")
c_race_label.grid(row=3, column=0)
c_class_label = Label(add_card_w, text="Card Class")
c_class_label.grid(row=4, column=0)
c_color_label = Label(add_card_w, text="Card Color")
c_color_label.grid(row=5, column=0)
c_manacost_label = Label(add_card_w, text="Card Mana Cost")
c_manacost_label.grid(row=6, column=0)
c_power_label = Label(add_card_w, text="Card Power")
c_power_label.grid(row=7, column=0)
c_toughness_label = Label(add_card_w, text="Card Toughness")
c_toughness_label.grid(row=8, column=0)
c_oracle_label = Label(add_card_w, text="Card Oracle")
c_oracle_label.grid(row=9, column=0)
c_deck_label = Label(add_card_w, text="Deck")
c_deck_label.grid(row=10, column=0)
c_deck_quantity_label = Label(add_card_w, text="Quantity in Deck")
c_deck_quantity_label.grid(row=11, column=0)
# Create a Button to Save a Card in the Add Card Window
add_btn = Button(add_card_w, text="Save", command=submit)
add_btn.grid(row=12, column=0, columnspan=2, pady=10, padx=10, ipadx=50)
# Create a button to close the add window
close_add_btn = Button(add_card_w, text="Close", command=close_add)
close_add_btn.grid(row=13, column=0, columnspan=2, pady=10, padx=10, ipadx=50)
# Create a window to delete a card
def delete_window():
global delete_w
delete_w = Tk()
delete_w.title('Delete a Card')
delete_w.geometry("400x175")
# Create Global Variables
global c_delete
# Create a title for the Window
dcards_window_label = Label(delete_w, text="Delete a Card from Catalog", font=('Arial, 20'))
dcards_window_label.grid(row=0, column=0, columnspan=2)
# Create Text Box Labels in the Delete Window
c_delete_label = Label(delete_w, text="ID of Card to Delete")
c_delete_label.grid(row=1, column=0)
# Create Text Box in the Delete Window
c_delete = Entry(delete_w, width=30)
c_delete.grid(row=1, column=1)
# Create Delete Button
delete_btn = Button(delete_w, text="Delete Card", command=delete)
delete_btn.grid(row=2, column=1, pady=10, padx=10, ipadx=50)
# Create a button to close the delete window
close_delete_btn = Button(delete_w, text="Close", command=close_delete)
close_delete_btn.grid(row=3, column=1, pady=10, padx=10, ipadx=50)
# Create Delete Function
def delete():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
# Delete a Card
c.execute("DELETE from catalog WHERE oid = " + c_delete.get())
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Clear the Delete ID Box
c_delete.delete(0, END)
# Create a Window to Edit a card
def edit():
global editor
editor = Tk()
editor.title('Edit a Card')
editor.geometry("400x400")
# Create Global Variables
global editor_id
global editor_c_name
global editor_c_type
global editor_c_race
global editor_c_class
global editor_c_color
global editor_c_manacost
global editor_c_power
global editor_c_toughness
global editor_c_oracle
global editor_c_deck
global editor_c_deck_quantity
# Create a title for the Window
ecards_window_label = Label(editor, text="Edit a Card from Catalog", font=('Arial, 20'))
ecards_window_label.grid(row=0, column=0, columnspan=2)
# Create Text Box Label for Card ID
editor_id_label = Label(editor, text="ID of Card to Edit")
editor_id_label.grid(row=1, column=0)
# Create Text Box for Card ID
editor_id = Entry(editor, width=10)
editor_id.grid(row=1, column=1)
# Create Text Box Labels in the Editor Window
editor_c_name_label = Label(editor, text="Card Name")
editor_c_name_label.grid(row=2, column=0, pady=(10, 0))
editor_c_type_label = Label(editor, text="Card Type")
editor_c_type_label.grid(row=3, column=0)
editor_c_race_label = Label(editor, text="Card Race")
editor_c_race_label.grid(row=4, column=0)
editor_c_class_label = Label(editor, text="Card Class")
editor_c_class_label.grid(row=5, column=0)
editor_c_color_label = Label(editor, text="Card Color")
editor_c_color_label.grid(row=6, column=0)
editor_c_manacost_label = Label(editor, text="Card Mana Cost")
editor_c_manacost_label.grid(row=7, column=0)
editor_c_power_label = Label(editor, text="Card Power")
editor_c_power_label.grid(row=8, column=0)
editor_c_toughness_label = Label(editor, text="Card Toughness")
editor_c_toughness_label.grid(row=9, column=0)
editor_c_oracle_label = Label(editor, text="Card Oracle")
editor_c_oracle_label.grid(row=10, column=0)
editor_c_deck_label = Label(editor, text="Deck")
editor_c_deck_label.grid(row=11, column=0)
editor_c_deck_quantity_label = Label(editor, text="Quantity in Deck")
editor_c_deck_quantity_label.grid(row=12, column=0)
# Create Text Boxes in the Editor Window
editor_c_name = Entry(editor, width=30)
editor_c_name.grid(row=2, column=1, padx=20, pady=(10, 0))
editor_c_type = Entry(editor, width=30)
editor_c_type.grid(row=3, column=1,)
editor_c_race = Entry(editor, width=30)
editor_c_race.grid(row=4, column=1,)
editor_c_class = Entry(editor, width=30)
editor_c_class.grid(row=5, column=1,)
editor_c_color = Entry(editor, width=30)
editor_c_color.grid(row=6, column=1,)
editor_c_manacost = Entry(editor, width=30)
editor_c_manacost.grid(row=7, column=1,)
editor_c_power = Entry(editor, width=30)
editor_c_power.grid(row=8, column=1,)
editor_c_toughness = Entry(editor, width=30)
editor_c_toughness.grid(row=9, column=1,)
editor_c_oracle = Entry(editor, width=30)
editor_c_oracle.grid(row=10, column=1,)
editor_c_deck = Entry(editor, width=30)
editor_c_deck.grid(row=11, column=1,)
editor_c_deck_quantity = Entry(editor, width=30)
editor_c_deck_quantity.grid(row=12, column=1)
# Create an ID Select Button for the Edit Window
select_id_btn = Button(editor, text="Select", command=select_id)
select_id_btn.grid(row=1, column=3)
# Create a Save Button
save_btn = Button(editor, text="Save", command=editor_submit)
save_btn.grid(row=13, column=0, columnspan=2, padx=5, pady=10, ipadx=100)
# Create a button to close the edit window
close_edit_btn = Button(editor, text="Close", command=close_edit)
close_edit_btn.grid(row=14, column=0,columnspan=2, pady=5, padx=10, ipadx=100)
# Create a Window for Decks
def deck_window():
global deck_name
global deck_w
deck_w =Tk()
deck_w.title('Decks')
deck_w.geometry("800x800")
# Create a title for the Window
deck_window_label = Label(deck_w, text="Stuff About Decks", font=('Arial, 20'))
deck_window_label.grid(row=0, column=0, columnspan=9)
# Create titles for the columns
d_title_id_label = Label(deck_w, text="ID", width=5)
d_title_id_label.grid(row=2, column=0, ipady=10)
d_title_name_label = Label(deck_w, text="Name", width=10)
d_title_name_label.grid(row=2, column=1, ipady=10)
d_title_type_label = Label(deck_w, text="Type", width=10)
d_title_type_label.grid(row=2, column=2, ipady=10)
d_title_race_label = Label(deck_w, text="Race", width=10)
d_title_race_label.grid(row=2, column=3, ipady=10)
d_title_class_label = Label(deck_w, text="Class", width=10)
d_title_class_label.grid(row=2, column=4, ipady=10)
d_title_color_label = Label(deck_w, text="Color", width=10)
d_title_color_label.grid(row=2, column=5, ipady=10)
d_title_manacost_label = Label(deck_w, text="Mana Cost", width=10)
d_title_manacost_label.grid(row=2, column=6, ipady=10)
d_title_power_toughness_label = Label(deck_w, text="P/T", width=10)
d_title_power_toughness_label.grid(row=2, column=7, ipady=10)
d_title_deck_label = Label(deck_w, text="Deck", width=10)
d_title_deck_label.grid(row=2, column=8, ipady=10)
d_title_deck_quantity_label = Label(deck_w, text="Qty", width=10)
d_title_deck_quantity_label.grid(row=2, column=9, ipady=10)
# Create deck entry label
deck_entry_label = Label(deck_w, text="Name of deck to view")
deck_entry_label.grid(row=1, column=0, columnspan=3)
# Create deck entry box
deck_name = Entry(deck_w, width=30)
deck_name.grid(row=1, column=3, columnspan=3)
# Create deck submit button
deck_submit_btn = Button(deck_w, text="Submit", command=deck_submit)
deck_submit_btn.grid(row=1, column=6)
# Create a button to close the Decks window
close_decks_btn = Button(deck_w, text="Close", command=close_decks)
close_decks_btn.grid(row=14, column=0,columnspan=4, pady=5, padx=10, ipadx=100)
def deck_submit():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
card_id = deck_name.get()
# Query the Database
c.execute("SELECT *, oid FROM catalog WHERE card_deck = " + "'" + card_id + "'")
show_cards = c.fetchall()
# Loop Thru Results
print_card_id = ''
print_card_name = ''
print_card_type = ''
print_card_race = ''
print_card_class = ''
print_card_color = ''
print_card_manacost = ''
print_card_strong_tough = ''
print_card_deck = ''
print_card_quantity = ''
for card in show_cards:
# Format the query output
print_card_id += str(card[11]) + "\n"
deck_output_id = Label(deck_w, text=print_card_id)
deck_output_id.grid(row=3, column=0)
print_card_name += str(card[0]) + "\n"
deck_output_name = Label(deck_w, text=print_card_name)
deck_output_name.grid(row=3, column=1)
print_card_type += str(card[1]) + "\n"
deck_output_type = Label(deck_w, text=print_card_type)
deck_output_type.grid(row=3, column=2)
print_card_race += str(card[2]) + "\n"
deck_output_race = Label(deck_w, text=print_card_race)
deck_output_race.grid(row=3, column=3)
print_card_class += str(card[3]) + "\n"
deck_output_class = Label(deck_w, text=print_card_class)
deck_output_class.grid(row=3, column=4)
print_card_color += str(card[4]) + "\n"
deck_output_color = Label(deck_w, text=print_card_color)
deck_output_color.grid(row=3, column=5)
print_card_manacost += str(card[5]) + "\n"
deck_output_manacost = Label(deck_w, text=print_card_manacost)
deck_output_manacost.grid(row=3, column=6)
print_card_strong_tough += str(card[6]) + "/" + str(card[7]) + "\n"
deck_output_strong_tough = Label(deck_w, text=print_card_strong_tough)
deck_output_strong_tough.grid(row=3, column=7)
print_card_deck += str(card[9]) + "\n"
deck_output_deck = Label(deck_w, text=print_card_deck)
deck_output_deck.grid(row=3, column=8)
print_card_quantity += str(card[10]) + "\n"
deck_output_quantity = Label(deck_w, text=print_card_quantity)
deck_output_quantity.grid(row=3, column=9)
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Clear textbox
deck_name.delete(0, END)
# Create Select ID Function
def select_id():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
card_id = editor_id.get()
# Query the Database
c.execute("SELECT * FROM catalog WHERE oid = " + card_id)
show_cards = c.fetchall()
for card in show_cards:
editor_c_name.insert(0, card[0])
editor_c_type.insert(0, card[1])
editor_c_race.insert(0, card[2])
editor_c_class.insert(0, card[3])
editor_c_color.insert(0, card[4])
editor_c_manacost.insert(0, card[5])
editor_c_power.insert(0, card[6])
editor_c_toughness.insert(0, card[7])
editor_c_oracle.insert(0, card[8])
editor_c_deck.insert(0, card[9])
editor_c_deck_quantity.insert(0, card[10])
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Create Editor Submit Function
def editor_submit():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
edit_card_id = editor_id.get()
c.execute("""UPDATE catalog SET
card_name = :name,
card_type = :type,
card_race = :race,
card_class = :class,
card_color = :color,
card_manacost = :manacost,
card_power = :power,
card_toughness = :toughness,
card_oracle = :oracle,
card_deck = :deck,
card_deck_quantity = :deck_quantity
WHERE oid = :oid""",
{
'name': editor_c_name.get(),
'type': editor_c_type.get(),
'race': editor_c_race.get(),
'class': editor_c_class.get(),
'color': editor_c_color.get(),
'manacost': editor_c_manacost.get(),
'power': editor_c_power.get(),
'toughness': editor_c_toughness.get(),
'oracle': editor_c_oracle.get(),
'deck': editor_c_deck.get(),
'deck_quantity': editor_c_deck_quantity.get(),
'oid': edit_card_id
})
# Commit Changes
conn.commit()
# Close Connection
conn.close()
#Clear The Text Boxes
editor_c_name.delete(0, END)
editor_c_type.delete(0, END)
editor_c_race.delete(0, END)
editor_c_class.delete(0, END)
editor_c_color.delete(0, END)
editor_c_manacost.delete(0, END)
editor_c_power.delete(0, END)
editor_c_toughness.delete(0, END)
editor_c_oracle.delete(0, END)
editor_c_deck.delete(0, END)
editor_c_deck_quantity.delete(0, END)
editor_id.delete(0, END)
# Create Submit Function
def submit():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
#Insert Into Table
c.execute("INSERT INTO catalog VALUES (:c_name, :c_type, :c_race, :c_class, :c_color, :c_manacost, :c_power, :c_toughness, :c_oracle, :c_deck, :c_deck_quantity)",
{
'c_name': c_name.get(),
'c_type': c_type.get(),
'c_race': c_race.get(),
'c_class': c_class.get(),
'c_color': c_color.get(),
'c_manacost': c_manacost.get(),
'c_power': c_power.get(),
'c_toughness': c_toughness.get(),
'c_oracle': c_oracle.get(),
'c_deck': c_deck.get(),
'c_deck_quantity': c_deck_quantity.get()
})
# Commit Changes
conn.commit()
# Close Connection
conn.close()
#Clear The Text Boxes
c_name.delete(0, END)
c_type.delete(0, END)
c_race.delete(0, END)
c_class.delete(0, END)
c_color.delete(0, END)
c_manacost.delete(0, END)
c_power.delete(0, END)
c_toughness.delete(0, END)
c_oracle.delete(0, END)
c_deck.delete(0, END)
c_deck_quantity.delete(0, END)
# Create Query Function
def query():
# Create a database or connect to one
conn = sqlite3.connect('card_catalog.db')
# Create cursor
c = conn.cursor()
# Query the Database
c.execute("SELECT *, oid FROM catalog")
show_cards = c.fetchall()
#print(show_cards)
# Loop Thru Results
print_cards = ''
print_cards_id = ''
print_cards_name = ''
for card in show_cards:
# Format the query output
print_cards_id += str(card[11]) + "\n"
query_label = Label(root, text=print_cards_id)
query_label.grid(row=16, column=0)
print_cards_name += str(card[0]) + "\n"
query_label2 = Label(root, text=print_cards_name)
query_label2.grid(row=16, column=1)
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Create Close Window Functions
def close_list():
list_cards_w.destroy()
def close_add():
add_card_w.destroy()
def close_delete():
delete_w.destroy()
def close_edit():
editor.destroy()
def close_decks():
deck_w.destroy()
# Create a title for the Root Window
root_title_label = Label(root, text="MTG Card Catalog", font=('Arial', 25))
root_title_label.grid(row=0, column=0, columnspan=2)
# Create an Add Card Window Button
submit_btn = Button(root, text="Add Card", command=add_card)
submit_btn.grid(row=2, column=0, pady=10, padx=10, ipadx=50)
# Create Delete Window Button
delete_btn = Button(root, text="Delete Card", command=delete_window)
delete_btn.grid(row=2, column=1, pady=10, padx=10, ipadx=50)
# Create a List Cards Window Button
query_btn = Button(root, text="List Cards", command=list_cards)
query_btn.grid(row=1, column=0, columnspan=2, pady=5, padx=10, ipadx=130)
# Create a Button to Edit Cards
edit_btn = Button(root, text="Edit Card", command=edit)
edit_btn.grid(row=3, column=0, pady=10, padx=10, ipadx=50)
# Create a Button to Open a Decks Window
deck_btn = Button(root, text="Decks", command=deck_window)
deck_btn.grid(row=3, column=1, pady=10, padx=10, ipadx=66)
# Create Button to Close Application
quit_btn = Button(root, text="Quit", command=root.quit)
quit_btn.grid(row=4, column=0, columnspan=2, pady=5, padx=10, ipadx=130)
# Commit Changes
conn.commit()
# Close Connection
conn.close()
root.mainloop()
|
5e642907559df3eaa54ab33ffbb9a5ab13c9f377 | aditya-doshatti/Leetcode | /mirror_reflection_858.py | 1,030 | 3.5 | 4 | '''
858. Mirror Reflection
Medium
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.
Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)
Example 1:
Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.
https://leetcode.com/problems/mirror-reflection/
'''
class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
for i in range(1, min(p,q)+1):
if((p % i == 0) and (q % i == 0)):
gcd = i
p = (p/gcd) % 2
q = (q/gcd) % 2
if p and q:
return 1
elif p:
return 0
else:
return 2
|
67c9197ffc40da53d9daafffd93e5487bb539fa8 | MatthewFoulk/cuttle | /src/Cuttle.py | 33,116 | 3.609375 | 4 |
import sys
import random
import pygame
from CardGame import *
from Gui import *
class Player():
def __init__(self):
self.hand = []
self.pointsCards = []
self.permCards = []
self.jacks = {} # Dictionary with card keys that have list of jack cards attached to them
self.score = 0
self.handVisible = False # 8's make opp hand visible
self.pointsNeededToWin = 21
self.queenProtection = False # Queens protect against two's and jacks
self.selectedCard = None
self.turnFinished = False
# True if in the middle of playing one of these cards
self.playingTwo = False
self.playingThree = False
self.playingSeven = False
self.playingJack = False
self.scuttling = False
def getNumCardsInJacks(self):
return len(self.jacks)
def getNumCardsInHand(self):
return len(self.hand)
def getNumCardsInPointsCards(self):
return len(self.pointsCards)
def getNumCardsInPermCards(self):
return len(self.permCards)
def removeCardFromHand(self, card):
self.hand.remove(card)
def removeCardFromPointsCards(self, card):
self.pointsCards.remove(card)
def removeCardFromPermCards(self, card):
self.permCards.remove(card)
def removeCardFromJacks(self, card):
self.jacks.pop(card)
def removeJackFromJacks(self, card):
self.jacks[card].pop(0)
def addCardToHand(self, card):
self.hand.append(card)
def addCardToPermCards(self, card):
self.permCards.append(card)
def addCardToPointsCards(self, card):
self.pointsCards.append(card)
def playPointsCard(self):
self.addCardToPointsCards(self.selectedCard)
self.removeCardFromHand(self.selectedCard)
self.turnFinished = True
def drawCard(self, deck):
self.hand.append(deck.drawCardAt(0))
def playAce(self, otherPlayer, discardPile):
"""
Discard all points cards and attached jacks
"""
for card in self.pointsCards:
self.discardCard(discardPile, card)
for card in otherPlayer.pointsCards:
otherPlayer.discardCard(discardPile, card)
for card in self.jacks.keys():
for jack in self.jacks[card]:
self.discardCard(discardPile, jack)
for card in otherPlayer.jacks.keys():
for jack in otherPlayer.jacks[card]:
otherPlayer.discardCard(discardPile, jack)
# Remove all cards from points
self.pointsCards = []
otherPlayer.pointsCards = []
self.jacks = {}
otherPlayer.jacks = {}
def playNormalTwo(self, otherPlayer, card, discardPile, currPlayer=False, isJack=False):
"""
Use a two to remove a permanent effect card
"""
self.discardCard(discardPile, self.selectedCard)
self.removeCardFromHand(self.selectedCard)
# Card being removed from otherPlayer
if not currPlayer:
# Card being removed is a jack
if isJack:
# Discard the jack
otherPlayer.discardCard(discardPile, otherPlayer.jacks[card][0])
otherPlayer.removeJackFromJacks(card) # Remove the jack from other's jacks
# Add the jacks to the curr player if any remaining
if (len(otherPlayer.jacks[card]) > 0):
self.jacks[card] = otherPlayer.jacks[card]
# Remove from other's points and add to curr
otherPlayer.removeCardFromPointsCards(card)
self.addCardToPointsCards(card)
# Remove card from other's jacks
otherPlayer.removeCardFromJacks(card)
# Remove Non jack perm card
else:
# Discard the cadr being 'twoed'
otherPlayer.discardCard(discardPile, card)
otherPlayer.removeCardFromPermCards(card)
# If 8, reset curr player's hand visibility
if card.value == 8:
self.handVisible = False
# If king, reset other player's points needed to win
elif card.value == Card.NAME_TO_VALUE["King"]:
otherPlayer.playKing()
# If queen, reset other player's queen protection
elif card.value == Card.NAME_TO_VALUE["Queen"]:
otherPlayer.queenProtection = False
# Card being removed is from current player (whoops why would they do that...)
else:
# Card being removed is a jack
if isJack:
# Discard the jack
self.discardCard(discardPile, self.jacks[card][0])
self.removeJackFromJacks(card)
# Add the card to the other player's jacks if any jacks remain
if (len(self.jacks[card]) > 0):
otherPlayer.jacks[card] = self.jacks[card]
# Remove the card from curr points and add to others
self.removeCardFromPointsCards(card)
otherPlayer.addCardToPointsCards(card)
self.removeCardFromJacks(card) # Remove card from your own jacks
# Remove Non jack perm card
else:
# Discard the card being 'twoed'
self.discardCard(discardPile, card)
self.removeCardFromPermCards(card)
# If 8, reset other player's hand visibility
if card.value == 8:
otherPlayer.handVisible = False
# If king, Reset curr points needed to win
elif card.value == Card.NAME_TO_VALUE["King"]:
self.playKing()
# if queen, removed current's own protection
elif card.value == Card.NAME_TO_VALUE["Queen"]:
self.queenProtection = False
self.turnFinished = True
def playThree(self, card, discardPile):
"""
Add a card from the discard to the hand
"""
# Discard three and remove from hand
self.discardCard(discardPile, self.selectedCard)
self.removeCardFromHand(self.selectedCard)
# Remove card from discard pile and add to hand
self.removeCardFromDiscard(discardPile, card)
self.addCardToHand(card)
self.playingThree = False
self.turnFinished = True
def playFour(self, otherPlayer, discardPile):
"""
Randomly discard two cards from opponents hand
"""
# One card remaining, so can only remove one
if otherPlayer.getNumCardsInHand() == 1:
cardToRemove = otherPlayer.hand[0]
otherPlayer.discardCard(discardPile, cardToRemove)
otherPlayer.removeCardFromHand(otherPlayer.hand[0])
# Randomly discard two cards from opponent
else:
numCardsInHand = otherPlayer.getNumCardsInHand()
firstCardToRemove = otherPlayer.hand[random.randint(0, numCardsInHand - 1)]
secondCardToRemove = otherPlayer.hand[random.randint(0, numCardsInHand - 1)]
# If second card choice is the same as the first
# Choose again until its a different card
while (secondCardToRemove == firstCardToRemove):
secondCardToRemove = otherPlayer.hand[random.randint(0, numCardsInHand - 1)]
otherPlayer.discardCard(discardPile, firstCardToRemove)
otherPlayer.removeCardFromHand(firstCardToRemove)
otherPlayer.discardCard(discardPile, secondCardToRemove)
otherPlayer.removeCardFromHand(secondCardToRemove)
def playFive(self, deck, handLimit):
"""
Draw two cards, or one if hand is currently one less than max
"""
self.drawCard(deck)
if (handLimit > self.getNumCardsInHand()):
self.drawCard(deck)
def playSix(self, otherPlayer, discardPile):
"""
Discard all permanent effect cards (jacks included)
"""
for card in self.permCards:
self.discardCard(discardPile, card)
for card in self.jacks.keys():
self.discardCard(discardPile, card)
# Return card to original player
if len(self.jacks[card]) % 2 != 0:
self.removeCardFromPointsCards(card)
otherPlayer.addCardToPointsCards(card)
for card in otherPlayer.permCards:
otherPlayer.discardCard(discardPile, card)
for card in otherPlayer.jacks.keys():
otherPlayer.discardCard(discardPile, card)
# Return card to original player
if len(otherPlayer.jacks[card]) % 2 != 0:
otherPlayer.removeCardFromPointsCards(card)
self.addCardToPointsCards(card)
# Reset perm effects
self.queenProtection = False
self.pointsNeededToWin = 21
self.handVisible = False
otherPlayer.queenProtection = False
otherPlayer.pointsNeededToWin = 21
otherPlayer.handVisible = False
self.permCards = []
self.jacks = {}
otherPlayer.permCards = []
otherPlayer.jacks = {}
def playSeven(self, otherPlayer, deck, discardPile):
self.drawCard(deck)
self.selectedCard = self.hand[self.getNumCardsInHand() - 1] # Get the newest card
# Continue to Draw cards until one is drawn that can be played
while(self.selectedCard.value == Card.NAME_TO_VALUE["Jack"] and
(otherPlayer.getNumCardsInPointsCards() + self.getNumCardsInPointsCards() == 0)):
self.drawCard(deck)
self.selectedCard = self.hand[self.getNumCardsInHand() - 1] # Get the newest card
self.playingSeven = True
def playOneOffCard(self, otherPlayer, deck, discardPile, handLimit):
# If no more actions needed (e.g. for a 2,3, or 7), then finish playing turn
# Must go before rest of logic because 7 changes selected card
if (self.selectedCard.value != 2 and self.selectedCard.value != 3):
self.discardCard(discardPile, self.selectedCard)
self.removeCardFromHand(self.selectedCard)
# Finish turn if not playing 7
if (self.selectedCard.value != 7):
self.turnFinished = True
if self.selectedCard.value == Card.NAME_TO_VALUE["Ace"]:
self.playAce(otherPlayer, discardPile)
elif self.selectedCard.value == 2:
self.playingTwo = True
elif self.selectedCard.value == 3:
self.playingThree = True
elif self.selectedCard.value == 4:
self.playFour(otherPlayer, discardPile)
elif self.selectedCard.value == 5:
self.playFive(deck, handLimit)
elif self.selectedCard.value == 6:
self.playSix(otherPlayer, discardPile)
elif self.selectedCard.value == 7:
self.playSeven(otherPlayer, deck, discardPile)
def playPermCard(self, otherPlayer):
if self.selectedCard.value == Card.NAME_TO_VALUE["Jack"]:
self.playingJack = True
else:
self.addCardToPermCards(self.selectedCard)
self.removeCardFromHand(self.selectedCard)
if self.selectedCard.value == 8:
otherPlayer.handVisible = True
elif self.selectedCard.value == Card.NAME_TO_VALUE["Queen"]:
self.queenProtection = True
elif self.selectedCard.value == Card.NAME_TO_VALUE["King"]:
self.playKing()
self.turnFinished = True
def playJack(self, otherPlayer, card):
# Jacked opponent, switch the card over
if card in otherPlayer.pointsCards:
otherPlayer.removeCardFromPointsCards(card)
self.addCardToPointsCards(card)
if card in otherPlayer.jacks.keys():
self.jacks[card] = otherPlayer.jacks[card]
self.jacks[card].append(self.selectedCard)
otherPlayer.removeCardFromJacks(card)
else:
self.jacks[card] = [self.selectedCard]
# Jacked yourself (whoops! That sucks...)
else:
self.removeCardFromPointsCards(card)
otherPlayer.addCardToPointsCards(card)
if card in self.jacks.keys():
otherPlayer.jacks[card] = self.jacks[card]
otherPlayer.jacks[card].append(self.selectedCard)
self.removeCardFromJacks(card)
else:
otherPlayer.jacks[card] = [self.selectedCard]
self.removeCardFromHand(self.selectedCard)
self.turnFinished = True
def playKing(self):
kingCount = 0
for card in self.permCards:
if card.value == Card.NAME_TO_VALUE["King"]:
kingCount += 1
if kingCount == 1:
self.pointsNeededToWin = 14
elif kingCount == 2:
self.pointsNeededToWin = 10
elif kingCount == 3:
self.pointsNeededToWin = 7
else:
self.pointsNeededToWin = 5
def scuttle(self, otherPlayer, card, discardPile):
# If jacks attached remove
for testCard in otherPlayer.jacks.keys():
if testCard == card:
otherPlayer.removeCardFromJacks(card)
break
self.discardCard(discardPile, self.selectedCard)
self.removeCardFromHand(self.selectedCard)
otherPlayer.discardCard(discardPile, card)
otherPlayer.removeCardFromPointsCards(card)
self.turnFinished = True
def discardCard(self, discardPile, card):
discardPile.append(card)
def removeCardFromDiscard(self, discardPile, card):
"""
Removes given card from the discard pile
"""
discardPile.remove(card)
def isTwoInHand(self):
"""
Returns true if there is a two in players hand, else false
"""
for card in self.hand:
if card.value == 2:
return True
return False
def discardTwo(self, discardPile):
"""
Discards the lowest value two from hand
"""
lowestTwo = self.hand[0]
for card in self.hand:
if card.value == 2:
if card < lowestTwo:
lowestTwo = card
self.discardCard(discardPile, lowestTwo)
self.removeCardFromHand(lowestTwo)
def clearCurrAction(self):
self.playingSeven = False
self.playingJack = False
self.playingTwo = False
self.scuttling = False
def updateScore(self):
self.score = 0
for card in self.pointsCards:
self.score += card.value
class Cuttle():
TIME_BETWEEN_TURNS = 2 * 600 # Seconds * Time in milliseconds
HAND_LIMIT = 8 # Max limit on number of cards in hand
def __init__(self, playerGoingFirst, dealer):
"""
Initialize the game board
"""
self.currPlayer = playerGoingFirst
self.otherPlayer = dealer
self.deck = Deck()
self.winner = None
self.imageBackOfCardInHand = None
self.imageBackOfCardOnBoard = None
self.promptOtherPointsCards = False
self.promptCurrPointsCards = False
self.promptOtherPermCards = False
self.promptCurrPermCards = False
self.cancelButton = False
self.cancelButtonObj = None
self.pointsButtonObj = None
self.permButtonObj = None
self.oneOffButtonObj = None
self.scuttleButtonObj = None
self.discardPile = [] # list of cards that have been discarded
self.showMaxDiscard = 5
self.discardBackButtonObj = None
self.discardNextButtonObj = None
self.switchingTurns = False # True if in the middle of switcing turns
self.startWaitTime = 0 # Time when waiting for turn switch started
self.waitTime = 0 # Amount of time since begun switching turns
self.askTwo = False # True if two needs to be asked
self.twoPlayer = None # Which player would be playing two
self.twoYesButton = None
self.twoNoButton = None
self.twoAsked = False # True if two has been asked, False if it hasn't
def switchPlayerTurn(self):
"""
Switches the current player and the other player
"""
temp = self.currPlayer
self.currPlayer = self.otherPlayer
self.otherPlayer = temp
def getLastDiscarded(self):
return self.discardPile[len(self.discardPile) - 1]
def getNumCardsInDiscard(self):
return len(self.discardPile)
def dealStartingHands(self):
"""
Deals 6 cards to the dealer and 5 cards to the non-dealer.
"""
hands = self.deck.deal(2, 5)
hands[1].append(self.deck.drawCardAt(0)) # Add the extra card to the dealer's hand [[dealers hand], [playerGoingFirst]]
self.currPlayer.hand = hands[0]
self.otherPlayer.hand = hands[1]
def clearSecondaryPrompts(self):
self.promptOtherPointsCards = False
self.promptCurrPointsCards = False
self.promptOtherPermCards = False
self.promptCurrPermCards = False
self.cancelButtonObj = None
self.cancelButton = False
def clearPrimaryPrompts(self):
self.pointsButtonObj = None
self.permButtonObj = None
self.oneOffButtonObj = None
self.scuttleButtonObj = None
def checkWinner(self):
if self.currPlayer.score >= self.currPlayer.pointsNeededToWin:
self.winner = self.currPlayer
elif self.otherPlayer.score >= self.otherPlayer.pointsNeededToWin:
self.winner = self.otherPlayer
def promptJackPlaying(self):
"""
Hint to the current player where they can play their Jack
"""
# Can be played on opponent points cards
if (self.otherPlayer.getNumCardsInPointsCards() > 0 and
not self.otherPlayer.queenProtection):
self.promptOtherPointsCards = True
# Can be played on yourself
if (self.currPlayer.getNumCardsInPointsCards() > 0 and
not self.currPlayer.queenProtection):
self.promptCurrPointsCards = True
# Turn on the cancel button
self.cancelButton = True
def promptTwoPlaying(self):
"""
Hint to the current player where they can play their Two
"""
# Prompt opponent's perm area if they have an perm cards in it
if self.otherPlayer.getNumCardsInPermCards() > 0:
self.promptOtherPermCards = True
# Prompt opp points area if opp has any jacks in their points area
# and no queen protection
if len(self.otherPlayer.jacks) > 0 and not self.otherPlayer.queenProtection:
self.promptOtherPointsCards = True
# Prompt curr player's perm area if they have perm cards in it
if self.currPlayer.getNumCardsInPermCards() > 0:
self.promptCurrPermCards = True
# Prompt curr player's points area if they have any jacks
# and no queen protection
if len(self.currPlayer.jacks) > 0 and not self.currPlayer.queenProtection:
self.promptCurrPointsCards = True
# Turn on back button
self.cancelButton = True
def play(player0, player1):
# Initialize game window
pygame.init()
screen = getScreen()
# Create a new game
game = Cuttle(player0, player1)
# Load card images
loadCardImages(game)
# Shuffle the starting deck
game.deck.shuffle()
# Deal starting hands
game.dealStartingHands()
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Nothing can be done besides quiting while waiting for turn to end
# or the game is already over
elif game.switchingTurns or game.winner is not None:
continue
elif event.type == pygame.MOUSEBUTTONUP:
# Set the x, y position of the click
clickX, clickY = event.pos
# Determine if anything relevant was clicked
deckClicked = checkDeckClicked(game, clickX, clickY)
cancelButtonClicked = checkCancelButtonClicked(game, clickX, clickY)
otherPointsCardClicked = checkOtherPointsClicked(game, clickX, clickY)
otherPermCardClicked = checkOtherPermClicked(game, clickX, clickY)
otherJackCardClicked = checkOtherJackClicked(game, clickX, clickY)
currPointsCardClicked = checkCurrPointsClicked(game, clickX, clickY)
currPermCardClicked = checkCurrPermClicked(game, clickX, clickY)
currJackCardClicked = checkCurrJackClicked(game, clickX, clickY)
permButtonClicked = checkPermButtonClicked(game, clickX, clickY)
pointsButtonClicked = checkPointsButtonClicked(game, clickX, clickY)
oneOffButtonClicked = checkOneOffButtonClicked(game, clickX, clickY)
scuttleButtonClicked = checkScuttleButtonClicked(game, clickX, clickY)
cardInHandClicked = checkCardInHandClicked(game, clickX, clickY)
twoYesClicked = checkTwoYesButtonClicked(game, clickX, clickY)
twoNoClicked = checkTwoNoButtonClicked(game, clickX, clickY)
if game.askTwo:
if twoYesClicked:
if game.twoPlayer == game.otherPlayer:
twoInHand = game.otherPlayer.isTwoInHand()
if twoInHand:
# Discard two and switching player being asked about two
game.otherPlayer.discardTwo(game.discardPile)
game.twoPlayer = game.currPlayer
elif game.twoPlayer == game.currPlayer:
twoInHand = game.currPlayer.isTwoInHand()
if twoInHand:
game.currPlayer.discardTwo(game.discardPile)
game.twoPlayer = game.otherPlayer
elif twoNoClicked:
if game.twoPlayer == game.currPlayer:
# end their turn without completing action
game.askTwo = False
game.askedTwo = True
game.currPlayer.turnFinished = True
else:
game.askTwo = False
game.twoAsked = True # This will finish curr players one-off
# Reset two things
game.twoPlayer = None
game.askTwo = False
game.twoYesButton = None
game.twoNoButton = None
# Currently in the middle of playing a three, you can NOT go back once you start
elif game.currPlayer.playingThree:
cardInDiscardClicked = checkCardInDiscardClicked(game, clickX, clickY)
discardBackButtonClicked = checkDiscardBackButtonClicked(game, clickX, clickY)
discardNextButtonClicked = checkDiscardNextButtonClicked(game, clickX, clickY)
if cardInDiscardClicked:
game.currPlayer.playThree(cardInDiscardClicked, game.discardPile)
game.showMaxDiscard = 5
elif discardBackButtonClicked:
game.showMaxDiscard -= 5
elif discardNextButtonClicked:
game.showMaxDiscard += 5
# Clicked on cancel button, so cancel usage selection
elif cancelButtonClicked:
game.clearSecondaryPrompts()
game.currPlayer.clearCurrAction()
# Clicked on deck to draw a card
elif (deckClicked and not game.currPlayer.playingSeven
and (game.currPlayer.getNumCardsInHand() < game.HAND_LIMIT)):
game.currPlayer.drawCard(game.deck)
game.currPlayer.turnFinished = True
game.currPlayer.clearCurrAction()
game.clearPrimaryPrompts()
game.clearSecondaryPrompts()
# Change selected card
elif (cardInHandClicked is not None and
not game.currPlayer.playingSeven):
# Deselect cards
if cardInHandClicked == game.currPlayer.selectedCard:
game.currPlayer.selectedCard = None
# Select card
else:
game.currPlayer.selectedCard = cardInHandClicked
game.currPlayer.clearCurrAction()
game.clearSecondaryPrompts()
# In the process of playing a two
elif game.currPlayer.playingTwo:
# If perm card (jacks included) is clicked, play two
# (unless queen protect, then must be a queen clicked)
if (otherPermCardClicked is not None
and (not game.otherPlayer.queenProtection or
otherPermCardClicked.value == Card.NAME_TO_VALUE["Queen"])):
game.currPlayer.playNormalTwo(game.otherPlayer,
otherPermCardClicked, game.discardPile)
game.clearSecondaryPrompts()
elif otherJackCardClicked is not None and not game.otherPlayer.queenProtection:
game.currPlayer.playNormalTwo(game.otherPlayer,
otherJackCardClicked, game.discardPile,isJack=True)
game.clearSecondaryPrompts()
elif (currPermCardClicked is not None
and (not game.currPlayer.queenProtection or
currPermCardClicked.value == Card.NAME_TO_VALUE["Queen"])):
game.currPlayer.playNormalTwo(game.otherPlayer,
currPermCardClicked, game.discardPile, currPlayer=True)
game.clearSecondaryPrompts()
elif (currJackCardClicked is not None and not game.currPlayer.queenProtection):
game.currPlayer.playNormalTwo(game.otherPlayer,
currJackCardClicked, game.discardPile, currPlayer=True,
isJack=True)
game.clearSecondaryPrompts()
# Currently in the process of playing a Jack
elif game.currPlayer.playingJack:
# If any point card is clicked and no queen protection,
# finish playing the jack
if (otherPointsCardClicked is not None and
not game.otherPlayer.queenProtection):
game.currPlayer.playJack(game.otherPlayer, otherPointsCardClicked)
game.clearSecondaryPrompts()
elif (currPointsCardClicked is not None and
not game.currPlayer.queenProtection):
game.currPlayer.playJack(game.otherPlayer, currPointsCardClicked)
game.clearSecondaryPrompts()
# In the process of scuttling
elif game.currPlayer.scuttling:
# If any opponent point card is clicked, scuttle
if otherPointsCardClicked is not None:
game.currPlayer.scuttle(game.otherPlayer,
otherPointsCardClicked, game.discardPile)
game.clearSecondaryPrompts()
# Play the selected card as a permanent effect
elif permButtonClicked:
# If Jack then turn on prompts for playing jack
if game.currPlayer.selectedCard.value == Card.NAME_TO_VALUE["Jack"]:
game.promptJackPlaying()
game.currPlayer.playPermCard(game.otherPlayer)
game.clearPrimaryPrompts()
# Play the selected card for points
elif pointsButtonClicked:
game.currPlayer.playPointsCard()
game.clearPrimaryPrompts()
# Play the selected card as a one-off effect
# or if all possible twos have been played or asked to play
# and denied
elif oneOffButtonClicked or game.twoAsked:
# If two is finished asking, then complete one off
if game.twoAsked:
if game.currPlayer.selectedCard.value == 2:
game.promptTwoPlaying()
game.currPlayer.playOneOffCard(game.otherPlayer, game.deck,
game.discardPile, game.HAND_LIMIT)
game.clearPrimaryPrompts()
game.askTwo = False
game.twoAsked = False
# Prompt two before completing one-off
else:
game.twoPlayer = game.otherPlayer # First person to ask about two
game.askTwo = True
# Play the selected card as a scuttle
elif scuttleButtonClicked:
game.currPlayer.scuttling = True
game.promptOtherPointsCards = True
game.cancelButton = True
game.clearPrimaryPrompts()
# Clear screen and set background color
screen.fill(GREEN)
# Draw points and perm indicator words
drawBoardIndicators(screen)
# Prepare to switch players if turn is ending
if game.currPlayer.turnFinished:
game.currPlayer.selectedCard = None # Reset for next turn
game.clearPrimaryPrompts() # Reset for next turn
game.clearSecondaryPrompts() # Reset for next turn
# Draw the deck and card count if cards left
if game.deck.getNumCards() > 0:
# Draw deck image
drawDeckImage(game, screen)
# Draw number of cards in deck
drawNumCardsInDeck(game, screen)
# Draw players' scores
game.currPlayer.updateScore()
game.otherPlayer.updateScore()
drawPlayersScore(game, screen)
# Draw top card in discard pile, if any have been discarded
numCardsInDiscard = game.getNumCardsInDiscard()
if numCardsInDiscard > 0:
if not game.currPlayer.playingThree:
drawDiscardPile(game, screen)
else:
game.clearPrimaryPrompts()
drawCardsInDiscard(game, screen)
drawDiscardButtons(game, screen)
# Draw players' hands
drawPlayersHands(game, screen)
# Prompt for card usage if selected and not playing three
if (game.currPlayer.selectedCard is not None
and not game.currPlayer.playingThree):
promptCardUsage(game, screen)
# Draw players' points cards
drawPointsCards(game, screen)
# Draw players' permanent effect cards
drawPermCards(game, screen)
# Draw players' jacks
drawJacks(game, screen)
# Display two question if needed
if game.askTwo:
drawTwoResponsePrompt(game, screen, game.twoPlayer)
if game.winner is not None:
if game.winner == game.currPlayer:
drawWinner(game, screen)
elif game.switchingTurns:
drawSwitchingTurns(game, screen)
game.waitTime = pygame.time.get_ticks() - game.startWaitTime
if game.waitTime > game.TIME_BETWEEN_TURNS:
game.switchingTurns = False
game.switchPlayerTurn()
elif game.currPlayer.turnFinished:
game.switchingTurns = True
game.startWaitTime = pygame.time.get_ticks()
game.currPlayer.turnFinished = False # Reset for next turn
game.currPlayer.clearCurrAction()
game.checkWinner()
pygame.display.flip() |
0e505b7299569c18b5bc6fd94055f50f79a8e43f | dgonzalez/goeardownloader | /goearget | 657 | 3.78125 | 4 | #!/usr/bin/python
import urllib2
import sys
urlpattern = """http://www.goear.com/tracker758.php?f=%s"""
def get_download_url(code):
return (urlpattern) % code
def parse_song(url):
backendurl = get_download_url(url.split("/")[4])
return (url.split("/")[5] + ".mp3", urllib2.urlopen(backendurl).read().split('"')[5])
def download(url):
"""
Downloads the song of the url.
"""
filename, songurl = parse_song(url)
urllib2.urlopen(songurl).read()
with open(filename, "w") as file:
file.write(urllib2.urlopen(songurl).read())
if __name__ == "__main__":
if len(sys.argv) == 2:
download(sys.argv[1])
else:
print "usage: goearget <songurl>" |
156cb6ce82fd6dd07f16b991a51e7e0e7f5f3d9a | weltonvaz/Zumbis | /exercicio01_welton03.py | 516 | 3.96875 | 4 | # encoding:utf8
#
# Curso: Python para Zumbies - exercício 3
#
# Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário.
# Calcule o total em segundos.
#
import os
os.system("clear") # Limpando a tela
dias = int(input("Digite a quantidade de dia(s): "))
horas = int(input("Digite a quantidade de hora(s) : "))
segundos = int(input("Digite a quantidade de segundo(s) : "))
total = ((dias * 86400) + (horas * 1440) + segundos)
print ("Calcule o total em segundos é de ", total)
|
31a08e17c900a055bc6390d3d7802ddc1b688427 | Anton-K-NN/Python-prakticum-Stepic | /n число Фибоначчи.py | 309 | 3.921875 | 4 | '''
Числа Фибоначчи
Напишите функцию fib(n), возвращающую n-е число Фибоначчи.
'''
x=int(input())
def fib(n):
fibon=[0,1,1]
for i in range(2, n+1):
fibon.insert(i,(fibon[i-1] + fibon[i-2]))
return fibon[n]
print(fib(x)) |
8d2a83c0863c65de535e04118bebcd5c57cf5cba | subodhss23/python_small_problems | /easy_probelms/is_there_upward_trend.py | 362 | 3.828125 | 4 | # Create a function that determines if there is an upward trend.
def upward_trend(lst):
for i in lst:
if type(i) == str:
return 'Strings not permitted!'
return lst == sorted(lst)
print(upward_trend([1, 2, 3, 4]))
print(upward_trend([1, 2, 6, 5, 7, 8]))
print(upward_trend([1, 2, 3, "4"]))
# print(upward_trend([1, 2, 3, 6, 7])) |
5793d10091f4a93c547f79e2250ce77d813ed666 | chenshanghao/Interview_preparation | /Leetcode分类/4.Tree/Leetcode_112_Path Sum/my_solution_dfs.py | 836 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if not root:
return False
return self.dfs(root, sum, 0)
def dfs(self, node, sum, sumVal):
sumVal = sumVal + node.val
if not node.left and not node.right:
return sumVal == sum
leftPathSum, rightPathSum = False, False
if node.left:
leftPathSum = self.dfs(node.left, sum, sumVal)
if node.right:
rightPathSum = self.dfs(node.right, sum, sumVal)
return leftPathSum or rightPathSum
|
9b849ce1d2bc57e5605bc44b4eaf1904deb6937b | Trieu210/TrieuTienDuc-C4T8 | /HW-session10/minihackp3.py | 600 | 4.09375 | 4 | price = {
'HP': 600,
'DELL': 650,
'MACBOOK': 12000,
'ASUS': 400,
'ACER': 350,
'TOSHIBA': 600,
'FUJISU': 900,
'ALIENWARE': 1000,
}
computers ={
'HP':20,
'DELL':50,
'MACBOOK':12,
'ASUS':30,
'TOSHIBA':15,
'FUJITSU':15,
}
print(price['ASUS'])
user = input("Enter a computer brand ").upper()
if user in computers:
print(price[user])
print('number of computers left:')
print(computers[user])
quantity = int(input("How many computers u want to buy"))
print(price[user]*quantity)
else:
print('Sr its not available')
|
59ab6745974ce2877a34357121eed0000fc375f0 | JiaqiLuciaLu/LeetCode | /may11.py | 1,185 | 3.5625 | 4 | def reverse(x: int) -> int:
if x >= 2**31-1 or x <= -2**31: return 0
if x >= 0 :
temp = str(x)
temp = temp[::-1]
else:
x = -x
temp = str(x)
temp = temp[::-1]
temp = '-' + temp
if int(temp) >= 2**31-1 or int(temp) <= -2**31: return 0
else: return int(temp)
def myAtoi(self, str: str) -> int:
if len(str) == 0:
return 0
i = 0
while i < len(str) and str[i] ==' ':
i += 1
str_new = str[i:]
if len(str_new) == 0:
return 0
first = str_new[0]
if first not in '0123456789+-':
return 0
else:
x = ''
j = 0
while j < len(str_new) and ((str_new[j] in '0123456789') or (j == 0 and (first== '+' or first=='-' ))):
x += str_new[j]
j += 1
if x == '+' or x == '-':
return 0
x = int(x)
if x >= 2**31-1 : return 2147483647
elif x <= -2**31: return -2147483648
else: return x
def isPalindrome(self, x: int) -> bool:
return (str(x) == str(x)[::-1])
|
d25a431e2fc20f4ad76e724b5e7b1127fb8900ed | markymauro13/Learning-Python | /Python_Tutorial_Files/Variables.py | 181 | 3.734375 | 4 | name = "Mark";
age = 18;
isMale = True;
print("There was once a man named " + name);
print(name + " was a loser and could not do algorithms")
print("Mark is " + str(age))
|
4e144c5bcd359e8d8e21cca331adc1e884e8a6da | MasterKali06/Hackerrank | /Problems/medium/Implementation/encryption.py | 765 | 3.9375 | 4 | '''
https://www.hackerrank.com/challenges/encryption/problem
'''
from collections import defaultdict
import math
s = "if man was meant to stay on the ground god would have given us roots"
def encryption(s):
s = s.replace(" ", "")
l = math.sqrt(len(s))
r = math.floor(l)
c = math.ceil(l)
dic = defaultdict(str)
for i in range(0, len(s), c):
sub = s[i:i+c]
# adding sub to dictionary
for j in range(len(sub)):
dic[j] += sub[j]
d = list(dic.values())
print(" ".join(d))
#encryption(s)
# :)))))))))))
def enc_cool(s):
sm = s.replace(" ", "")
r = math.floor(math.sqrt(len(sm)))
c = math.ceil(math.sqrt(len(sm)))
for i in range(c):
print(sm[i::c], end=" ")
enc_cool(s) |
1bc2e54fe3d46c61f1892a0390fa6b54cca1ff96 | huqinwei/python_demo | /fundation/sleep.py | 256 | 3.859375 | 4 | from time import sleep
from time import time
t = time()
duration = 5
print("the time is ",t)
print("sleep , wakeup in ",duration,"seconds")
sleep(duration)
print("waked!")
t_new = time()
print("what's the time? ~is ",t_new)
sleep(1)
sleep(2)
#help(sleep)
|
852d0b7c3beea183413fa7bf18b0fc7b14366df2 | biosvos/algorithm | /프로그래머스/타겟 넘버/main.py | 395 | 3.609375 | 4 | def sol(arr, target, total):
arr = list(arr)
if not arr:
if total == target:
return 1
return 0
item = arr.pop()
return sol(arr, target, total + item) + sol(arr, target, total - item)
def solution(numbers, target):
return sol(numbers, target, 0)
def main():
assert solution([1, 1, 1, 1, 1], 3) == 5
if __name__ == '__main__':
main()
|
5ebabdd962b1762c57dbfd09a23ebc559733d1a5 | washingtoncandeia/PyCrashCourse | /09_Classes/upgradeBattery.py | 3,421 | 4.09375 | 4 | ##-------------------------------
# Cap.9 - Classes
# Python Crash Course
# Autor: Washington Candeia
##-------------------------------
# Faça você mesmo, p.241
# 9.9 - Privileges
class Car():
"""Uma tentativa simples de representar um carro."""
def __init__(self, make, model, year):
"""Inicializa os atributos que descrevem o carro."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
self.gas_tank = 0
def get_descriptive_name(self):
"""Descreve o carro de forma elegante."""
# Poderia-se usar a função print, mas optei por retornar
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name
def read_odometer(self):
"""Informa sobre a quilometragem do carro"""
print("Este carro tem " + str(self.odometer_reading) + "km")
def update_odometer(self, km):
"""Cria método para fazer update da quilometragem."""
if km >= self.odometer_reading:
self.odometer_reading = km
else:
print('\n\tVocê não pode baixar a quilometragem do seu carro!')
def increment_odometer(self, kmters):
"""Incrementa o valor da quilometragem do carro."""
self.odometer_reading += kmters
print('\nA quilometragem passou a ser: ' + str(self.odometer_reading))
def fill_gas_tank(self, fill):
"""Enche o tanque do carro com o que você informou."""
self.gas_tank += fill
print('Seu carro tem ' + str(self.gas_tank) + 'L no tanque.')
class Battery():
"""Cria uma classe que contém as informações acerca da bateria do carro."""
def __init__(self, battery_size=70):
"""Inicializa os atributos da bateria."""
self.battery_size = battery_size
def describe_battery(self):
"""Informa como está a situação da bateria."""
print('Este carro tem uma bateria de ' + str(self.battery_size) + '-kWh.')
def get_range(self):
"""Exibe uma frase sobre a distância que o carro consegue percorrer com essa bateria."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = 'Este carro pode andar, aproximadamente, ' + str(range)
message += ' quilômetros sem abastecer.'
print(message)
def upgrade_battery(self):
"""Método verifica a capacidade da bateria e define-a para 85 se o valor for diferente."""
if self.battery_size != 85:
self.battery_size = 85
else:
print('\tA capacidade da bateria é 85-kWh.')
class ElectricCar(Car):
"""Cria uma classe que representa um carro elétrico."""
def __init__(self, make, model, year):
super().__init__(make, model, year) # Utiliza atributos da classe Pai.
self.battery = Battery() # Instância Battery como atributo.
def fill_gas_tank(self, fill):
"""Carros elétricos não têm tanques de gasolina."""
print('Carros elétricos não têm tanques de gasolina.')
# Instancia carro_eletrico
carro_eletrico = ElectricCar('atom', 'lsd', 2048)
carro_eletrico.battery.describe_battery()
carro_eletrico.fill_gas_tank(100)
carro_eletrico.battery.get_range()
# Usando novo método para fazer upgrade:
carro_eletrico.battery.upgrade_battery()
carro_eletrico.battery.get_range() |
0bf1bb12c0705aab61572bfa4336f902431adf4d | datalyo-dc-m1/tp-python-alecordix | /tp2/monkey.py | 466 | 3.53125 | 4 | class Monkey:
def __init__(self, name, banane):
self.name = name
self.banane = banane
def mange(self):
print('Un singé nommé', self.name, 'mange une banane de couleur', self.banane.color)
class Banane:
def __init__(self, color):
self.color = color
banane_verte = Banane('verte')
banane_jaune = Banane('jaune')
Pierre = Monkey("Pierre", banane_jaune)
Marie = Monkey("Marie", banane_verte)
Pierre.mange()
Marie.mange() |
3936be92ee2e02c872276be42d2fb95606ec2f21 | vijayjag-repo/LeetCode | /Python/LC_Maximum_Score_From_Performing_Multiplication_Operations.py | 889 | 3.59375 | 4 | # DP hard problem
# For better understanding, check this - https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/2156486/Greedy-Failed-From-Level-Zero-or-Beginner-Friendly-or-Fully-Explained-or-Python-or-C
from functools import lru_cache
class Solution:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
@lru_cache(2000)
def df(i, left):
if i == m:
return 0
val = multipliers[i]
# Easy to derive if you take an example
right = n - 1 - (i - left)
# Left, right products
left_product = val * nums[left] + df(i + 1, left + 1)
right_product = val * nums[right] + df(i + 1, left)
return max(left_product, right_product)
n = len(nums)
m = len(multipliers)
return df(0,0)
|
b2492076a5725826772799249b8e15acb9a118ad | bachelor10/recurrent-octo-sniffle | /online_recog/rpd_test.py | 1,537 | 3.625 | 4 | import numpy as np
import math
#https://github.com/fhirschmann/rdp/blob/master/rdp/__init__.py
"""
pldist is a function directly copied from link above, to calculate the perpendicular distance.
"""
def pldist(point, start, end):
"""
Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end: numpy array
"""
if np.all(np.equal(start, end)):
return np.linalg.norm(point - start)
return np.divide(
np.abs(np.linalg.norm(np.cross(end - start, start - point))),
np.linalg.norm(end - start))
"""
rdp_fixed_num is a rewritten version of rdp taken from github link in top of the file.
This version does not depend on a epsilon, however removes the points least affecting the
strokes' structure, until a fixed limit is reached. Its purpose is to normalize all traces
to a fixed length.
"""
def rdp_fixed_num(M, fixed_num, dist=pldist):
min_distance = math.inf
index = -1
indices = np.ones(len(M), dtype=bool)
for i in range(0, len(M) - 2):
d = dist(M[i + 1], M[i], M[i + 2])
if d < min_distance:
index = i + 1
min_distance = d
indices[index] = False
if len(M) - 1 <= fixed_num:
return M[indices]
else:
return rdp_fixed_num(M[indices], fixed_num)
|
4e390c5ea09ecf1aac21291807794eb07064540b | smrsassa/Studying-python | /curso/PY3/listas/lista2/ex4.py | 710 | 3.8125 | 4 | #exercicio87
matriz = [[0, 0, 0,], [1, 1, 1,], [2, 2, 2,]]
somapares = 0
somaterceira = 0
for c in range(0, 3):
for c2 in range(0,3):
valor = int(input(f'preencha a celula [{c, c2}] da matriz: '))
if valor %2 == 0:
somapares += valor
if c == 2:
somaterceira += valor
if c == 1:
if valor > matriz[1][c2]:
maxsegunda = valor
matriz[c][c2] = valor
print ('-='*50)
print (matriz[0])
print (matriz[1])
print (matriz[2])
print ('-='*50)
print (f'A soma dos valores pares digitados = {somapares}')
print (f'A soma dos valores na terceira coluna = {somaterceira}')
print (f'O maior valor da segunda coluna = {maxsegunda}') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.