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 |
|---|---|---|---|---|---|---|
1132636348439e8793a1a29ce127f3e90d2a3ccd | GGXH/coding | /arrays_string/isunique/sol1.py | 457 | 3.546875 | 4 |
def isunique(a):
marker = 0
bl = ord('a')
for item in a:
b = 1 << (ord(item) - bl)
if marker & b > 0:
return False
else:
marker |= b
return True
if __name__ == "__main__":
test_str = ['aaaaa', 'abcdea', 'abcdefg']
test_sol = [False, False, True]
for i in xrange(len(test_str)):
sol = isunique(test_str[i])
if sol == test_sol[i]:
print test_str[i] + " passes " + str(sol)
else:
print test_str[i] + " no pass " + str(sol) |
80887e088562aaae8918717a335cab51da8ea691 | elenirotsides/CS-115 | /HW-Code/hw4.py | 1,589 | 3.796875 | 4 | from cs115 import *
'''
Created on March 8, 2021
@author: Eleni Rotsides
Pledge: I pledge my honor that I have abided by the Stevens Honor System
CS115 - HW 4
'''
def addPasc(numList):
'''Helper function for pascal_row that creates a new list of sums of
adjacent terms in the original list.'''
if numList == [numList[0]]:
return []
return [numList[0] + numList[1]] + addPasc(numList[1:])
def pascal_row(num):
'''Returns a list of elements found in a certain row of Pascal’s Triangle.
Takes an integer num as input (represents the row's number), and it is
assumed that the input will always be non-negative.'''
if num == 0:
return [1]
else:
return [1] + addPasc(pascal_row(num - 1)) + [1]
def pascal_triangle(num):
'''Takes as input a single integer num and returns a list of lists
containing the values of all the rows up to and including row n.'''
return map(pascal_row, range(num + 1))
def test_pascal_row():
'''Test pascal_row, returns nothing if all tests pass'''
assert pascal_row(0) == [1]
assert pascal_row(1) == [1,1]
assert pascal_row(5) == [1, 5, 10, 10, 5, 1]
assert pascal_row(4) == [1, 4, 6, 4, 1]
def test_pascal_triangle():
'''Test pascal_triangle, returns nothing if all tests pass'''
assert pascal_triangle(0) == [[1]]
assert pascal_triangle(1) == [[1], [1, 1]]
assert pascal_triangle(5) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
assert pascal_triangle(4) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
|
fa1a74b276669888d2690bf8c00deeae1eb63b48 | pentakotalokesh/Python-Lab | /median.py | 190 | 3.75 | 4 | list=[55,23,45,12,3,5,7,20]
list.sort()
length=len(list)
if length%2==0:
index=length//2
print("Median is ",list[index])
else:
index=length//2
print("Median is ",list[index]) |
a88ee5844a61627d7c43725f3d03e7984c568cda | Postmea/CP3-TANADAT-THANYAJAROENKANKA | /WidgetEx.py | 337 | 3.9375 | 4 | from tkinter import *
def sayHelloWorld():
print("Hello world")
def sayNo():
print("Bye Bye")
mainWindow = Tk()
button = Button(mainWindow,text = "Click me",command = sayHelloWorld)
button.place(x = 20, y = 10)
button2 = Button(mainWindow,text = "Click me2",command = sayNo)
button2.place(x = 120, y = 10)
mainWindow.mainloop() |
ba091c1a6d2618478241461ac84ca3223dddf073 | kw78999/MyStudy | /Python/Py_ex1/list7.py | 111 | 3.5 | 4 | import random
lotto = set()
cnt2 = 0
for i in range(6):
lotto.add(random.randint(1,45)
print(lotto) |
3471d719cb3cc1fdbc625696d01c5812b1165433 | ngarnsworthy/Pizza_Game | /OLD VERINS/capt5testingnnogame.py | 396 | 3.859375 | 4 | class Monster(object):
eats = 'food'
def __init__(self,name):
self.name = name
def speak(self):
print(self.name + ' speaks')
def eat(self, meal):
if meal == self.eats:
print('yum')
else:
print('belch')
#my_monster = Monster('nick')
#my_monster.speak()
#my_monster.eat('food')
class FrankenBurger(Monster):
eats = 'ham'
|
e0d59577dbb6db62b3d9d2f7d300d295d20f3ed4 | andrewschultz/stale-tales-slate | /utils/sts.py | 4,312 | 3.78125 | 4 | # sts.py: this is a can-opener sort of application
# it gives a hash of any word according to STS
# it can also reverse lookup any word from any integer, starting with E as the biggest number and working its way down
# so that it doesn't go through too many possibilities
#
# this partially replaces hv.pl and extends it, but it doesn't have functions like "detect hash in file" ... yet
#
import mytools as mt
import sys
import re
import math
from collections import defaultdict
word_hash = defaultdict(list)
write_to_file = False
nudge_out_file = "c:/writing/dict/hv.txt"
sts_hash = {
"a" : 2187818,
"b" : 18418905,
"c" : 19005585,
"d" : 21029089,
"e" : 127806109,
"f" : 26514896,
"g" : 32599702,
"h" : 37282299,
"i" : 44992846,
"j" : 48960525,
"k" : 52933178,
"l" : 53813839,
"m" : 64075153,
"n" : 68907508,
"o" : 74352577,
"p" : 81465959,
"q" : 84405617,
"r" : 85323803,
"s" : 96273966,
"t" : 103110018,
"u" : 105105807,
"v" : 107164820,
"w" : 107934773,
"x" : 112768081,
"y" : 122359252,
"z" : 122969618 }
rev_word = sorted(sts_hash, key=sts_hash.get, reverse = True)
def usage():
print("Entering a number allows hash reverse-lookup. That is the only option so far.")
sys.exit()
def letters_only(my_word):
return re.sub("[^a-z]", "", my_word.lower())
def ana_alf(my_word):
return ''.join(sorted(list(my_word)))
def roi_poss(my_word, count_duplicates = False, full_factorial = False):
count = defaultdict(int)
my_word = letters_only(my_word)
vowels = sum([my_word.count(x) for x in 'aeiou'])
ys = my_word.count('y')
consonants = sum([my_word.count(x) for x in 'bcdfghjklmnpqrstvwxz'])
for x in my_word:
count[x] += 1
if full_factorial:
ret_val = math.factorial(len(my_word))
for x in count:
if count[x] > 1:
ret_val //= math.factorial(count[x])
return ret_val
ret_val = math.factorial(vowels)*math.factorial(ys)*math.factorial(consonants)
if not count_duplicates:
for x in count:
if count[x] >= 2:
ret_val //= math.factorial(count[x])
return ret_val
def word_hash_match(my_word):
temp = 0
for q in my_word.lower():
if q in sts_hash:
temp += sts_hash[q]
return temp
got_one = False
def word_by_libe(hash_to_see):
with open("c:/writing/dict/brit-1word.txt") as file:
for line in file:
if word_hash_match(line.lower().strip()) == hash_to_see:
print("(DICT) Got a match!", hash_to_see, "matches", line.strip())
return
print("(DICT) No dictionary matches for", hash_to_see)
def get_word_hash():
global word_hash
with open(mt.words_file) as file:
for (line_count, line) in enumerate (file, 1):
ll = line.lower().strip()
alf = ''.join(sorted(ll))
word_hash[alf].append(ll)
def get_anagrams(cur_word):
if not len(word_hash):
get_word_hash()
if cur_word not in word_hash:
print(cur_word, "not in", word_hash)
else:
print(cur_word, ",".join(word_hash[cur_word]))
def pick_reverse_word(hash_to_see, max_letters = 8, cur_word = ""):
if len(cur_word) > max_letters: return
global got_one
if got_one: return
if hash_to_see == 0:
cur_word = ''.join(sorted(cur_word))
print("GOT ONE!", cur_word, word_hash_match(cur_word))
get_anagrams(cur_word)
got_one = True
return
for x in rev_word:
if sts_hash[x] <= hash_to_see:
pick_reverse_word(hash_to_see - sts_hash[x], max_letters, cur_word + x)
if cur_word == "" and not got_one:
print("Nothing found for", hash_to_see)
return
cmd_count = 1
while cmd_count < len(sys.argv):
arg = sys.argv[cmd_count]
if arg.isdigit():
pick_reverse_word(int(arg))
elif arg == 'f':
write_to_file = True
elif len(arg) > 3:
for x in arg.split(","):
print(x, word_hash_match(x))
if write_to_file:
f = open(nudge_out_file, "a")
this_line = '"{}"\t{}\t--\t--\t"some text"\n'.format(x,word_hash_match(x))
f.write(this_line)
f.close()
else:
usage()
cmd_count += 1
|
3294dafc3a0e9ca20287bcaa17c7d92ef7cffdf1 | CuriosityGym/Mentees | /Shiv Kampani/Shiv's Projects in python bubble sort.py | 764 | 4.3125 | 4 |
print("How many values do you have?")
def sortList(reverse=True):
unorderedlist=[1,300,50,20,8,60]
listlength=len(unorderedlist)
for i in range(0,listlength):
print(unorderedlist)
for i in range(0,listlength-1):
if(reverse):
if(unorderedlist[i]>unorderedlist[i+1]):
a=unorderedlist[i+1]
unorderedlist[i+1]=unorderedlist[i]
unorderedlist[i]=a
if(not reverse):
if(unorderedlist[i]<unorderedlist[i+1]):
a=unorderedlist[i+1]
unorderedlist[i+1]=unorderedlist[i]
unorderedlist[i]=a
sortList(False)
|
ce3377195ba713503857447c3d50ed5d3f9a4ca8 | JuanCamiloSendoya/Ejercicios-pseint | /PYTHON TUTORIAL FOR BEGINNERS/Arithmetic Operators.py | 267 | 4 | 4 | #sum
print(10 + 3)
#subtraction
print(10 - 3)
#division with decimals
print(10 / 3)
#division without decimals
print(10 // 3)
#module
print(10 % 3)
#exponentiation
print(10 ** 3)
#assignment operator
x = 10
x = x + 3
#x += 3
#x -= 3
#x *= 3
print(x) |
3e20f915c6563b784806d61042fceb9f5278cb76 | StudyForCoding/BEAKJOON | /05_Practice1/Step02/yj.py | 176 | 3.734375 | 4 | burger = []
drink = []
for i in range(3):
a = int(input())
burger.append(a)
for i in range(2):
b = int(input())
drink.append(b)
print(min(burger)+min(drink)-50) |
f119ddf41e12eb5d292ec07ae0663ee8e8b1c35d | minwuh0811/DIT025-Applied-Mathematical-Thinking | /module 5/control_PowervsOutsideT.py | 1,812 | 3.78125 | 4 | import matplotlib.pyplot as plt
# in minutes
deltaT= 1 # do not change!
temp= 5 # actual room temperature
desiredTemp=17 # desired room temperature
outsideTemp= -5 # temperature outside of room
# for heater fan
PowerSet=[0+i*60 for i in range(60)]
outsideTemps=[-5+i*0.4 for i in range(60)]
outSideMin=[]
maxPowerMins=[]
accError=0
for outsideTemp in outsideTemps:
timeSet=[]
tempReach=[]
List=[]
for maxPower in PowerSet:
time=0;
temp= 5;
timeList = []
tempList = []
desiredTempList = []
for i in range(60):
# you can change the controller and the maxPower of the heater
# heater allows change once a minute to any value within 0 <= power <= maxPower
# simple thermostat control - try to replace with something better!
if temp < desiredTemp:
power = maxPower
else:
timeSet.append(time)
tempReach.append(maxPower)
power = 0
time = time + deltaT # time always increased with deltaT
# effect of outside temperature and heater
tempChange = 0.11 * (outsideTemp-temp) + 0.0009 * power
temp = temp + tempChange * deltaT
# THIS IS JUST TO PUT THE MOST RECENT VALUES IN THE LISTS
timeList.append(time)
tempList.append(temp)
desiredTempList.append(desiredTemp)
List.append([timeList,tempList,desiredTempList])
if (timeSet!=[]):
outSideMin.append(outsideTemp)
maxPowerMin=min(tempReach)
maxPowerMins.append(maxPowerMin)
plt.figure(1)
plt.title ("Minimum power needed vs Outside temperature")
plt.plot(outSideMin,maxPowerMins)
plt.show()
|
ee62cd36639868554bcb3e28ccc6d700d0635b60 | smantavya/pyprogs | /character frequeny.py | 92 | 3.625 | 4 | a = input('enter your word = ')
b = input('character to be counted = ')
print(a.count(b))
|
0644e7ae10a554e85e1650e74ffc4c36fd71eb6b | mocmeo/algorithms | /subsets.py | 312 | 3.625 | 4 | def subsets(nums):
arr = [[]]
for num in nums:
temp = []
for cur in arr:
x = cur + [num]
temp.append(x)
arr += temp
return arr
print(subsets([1,2,2]))
# n = 3
# nth_bit = 1 << n
# for i in range(2**n):
# # generate bitmask, from 0..00 to 1..11
# bitmask = bin(i | nth_bit)[3:]
# print(bitmask) |
aff3898c67ec7ca7f1de66701d80f696b69b20da | peterrowland/D07 | /HW07_ch10_ex06.py | 957 | 3.984375 | 4 |
#!/usr/bin/env python3
# <filename>
# I want to be able to call is_sorted from main w/ various lists and get
# returned True or False.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
##############################################################################
# Imports
# copy
# Body
def is_sorted(in_list):
# Try/except list sorting
try:
sorted(in_list)
except:
print('not sortable')
else:
if sorted(in_list) != in_list:
return False
#TODO: check reverse sorting
# elif sorted(in_list, reverse=True) != in_list:
# return False
else:
return True
# if list == list.sort()
# return true
# also check if reverse sort is true
# else false
##############################################################################
def main():
pass
if __name__ == '__main__':
main()
|
8b676aba7d210a3034cde0243812cc9a33416df1 | dw2008/coding365 | /201905/0502.py | 625 | 4.09375 | 4 | #Finish half of this tutorial https://hourofpython.trinket.io/a-visual-introduction-to-python#/welcome/an-hour-of-code
#Write your own code below
import turtle
turt = turtle.Turtle()
turt.penup()
def line(words, horiz_pos = -50):
x,y = turt.pos()
turt.goto(max(horiz_pos, -190), y)
turt.write(words)
x,y = turt.pos()
turt.goto(x, y - 25)
def by(author):
x,y = turt.pos()
turt.goto(x + 70, max( -190, y -30))
turt.write(author)
x,y = turt.pos()
turt.goto(0, y)
turt.goto(-50, 0)
line("Dang cilantro sucks")
line("I mean it's not that bad really")
line("I has bad grammers")
by("Daniel Wu") |
1cea70f033e2499ab3d6c3bc49d0e9c2659b769b | rockerarjun/python-notes | /Examples of program/subtraction.py | 228 | 3.5625 | 4 | """
map(), filter(), reduce() and lambda
"""
from functools import reduce
a = [4,5,8,9,7]
b = [14,15,13,16,19]
c =[-4,-5,-3,2,-6]
print(list(map(lambda x,y:y-x, a,b)))##subtraction
print(list(map(lambda x,y,z:y-x+z, a,b,c)))##
|
2af332963968f79db488a3b8cc12b64eaa133e38 | atulanandnitt/questionsBank | /sorting/mergeSort_practice.py | 1,026 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 12:50:10 2018
@author: atanand
"""
#practice merge sort
def mergeSort(arr):
if len(arr)>1:
midpoint=len(arr)//2
lefthalf=arr[:midpoint]
righthalf=arr[midpoint:]
mergeSort(lefthalf)
mergeSort(righthalf)
i,j,k=0,0,0
print("lefthalf : ",lefthalf,"righthalf : ",righthalf,"arr : ",arr)
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i]>righthalf[j]:
arr[k]=righthalf[j]
j +=1
else:
arr[k]=lefthalf[i]
i+=1
k+=1
while i<len(lefthalf):
arr[k]=lefthalf[i]
i +=1
k +=1
while j <len(righthalf):
arr[k]=righthalf[j]
j +=1
k +=1
print ("arr : ",arr)
return arr
arr=[4,5,3,6,2,7,1,8,9]
mergeSort(arr) |
f70c50415c51ce383e53ffe6e950b8173cf0e752 | Len-Jon/Machine-Learning-Python | /ex6/gaussianKernel.py | 424 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
% Instructions: Fill in this function to return the similarity between x1
% and x2 computed using a Gaussian kernel with bandwidth
% sigma
%
:Time: 2020/8/1 16:01
:Author: lenjon
"""
import numpy as np
def gaussianKernel(x1, x2, sigma):
sim = 0
pass
# sim = np.exp(-(np.sum((x1 - x2) ** 2) / (2 * (sigma ** 2))))
return sim
|
554190169268e535cae960addba33606daa00504 | zhentoufei/LeetCode | /Python/剑指offer/37.两个链表的第一个公共结点.py | 1,632 | 3.53125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Mr.Finger'
__date__ = '2017/10/5 20:21'
__site__ = ''
__software__ = 'PyCharm'
__file__ = '37. 两个链表的第一个公共结点.py'
'''
方法1:利用堆栈的思想
首先,可以发现,如果过这两个链表有公共点,那么从公共节点到最后可定不会再分开了,
好了,我们就把这两个列表塞入堆栈中,然后分别pop出去
方法2:
就是下面的方法了,更加高效
[1]先比较出长短,找到之间的长度差
[2]让长的那个链表先走长度差这么多步数
[3]然后依次比较两个链表的节点
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def findeFirstCommonNode(self, p_head_1, p_head_2):
length_1 = self.getListLength(p_head_1)
length_2 = self.getListLength(p_head_2)
length_diff = abs(length_1-length_2)
if length_1 > length_2:
p_head_long = length_1
p_head_short = length_2
else:
p_head_long = length_2
p_head_short = length_1
for i in range(length_diff):
p_head_long = p_head_long.next
while p_head_long != None and p_head_short != None and p_head_long != p_head_short:
p_head_long = p_head_long.next
p_head_short = p_head_short.next
p_1st_common = p_head_long
return p_1st_common
def getListLength(self, p_head):
length = 0
while p_head != None:
p_head = p_head.next
length += 1
return length
if __name__ == '__main__':
pass |
edcc24b23181f52003cb8d14035ab5132bfba751 | mfouda/SPOT_OT | /test.py | 2,770 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 17 12:34:45 2020
@author: qspinat
"""
import numpy as np
import time
from assignment import *
from plot_assignment import *
#%%################################################################
rng = np.random.default_rng()
n = 30
alpha = 0.75
m = int(alpha*n)
X = np.sort(np.random.uniform(10,size=int(m)))
Y = np.sort(np.random.uniform(10,size=int(n)))
#%%################## true optimal assignement ##############
# start0 = time.time()
# print(0, "starting optimal assigment brut force")
# a_bf = brut_force(X, Y)
# end0 = time.time()
# print(end0-start0, "optimal assigment fisnished")
# print("total time :", end0-start0)
# print("cost :",cost(X,Y,a_bf))
# print()
#######################
start1 = time.time()
print(0, "starting optimal assigment")
t = nn_assignment(X, Y)
end1 = time.time()
print(end1-start1, "optimal assigment fisnished")
print("total time :", end1-start1)
print("cost :",cost(X,Y,t))
print()
#print(t)
#plot_assignment(X,Y,t)#,'t')
#%%
start2 = time.time()
print(time.time()-start1, "starting injective optimal assigment")
a = quad_assignment_preprocessed(X,Y)
end2 = time.time()
print(end2-start1, "injective optimal assigment finished")
print("total time :", end2-start2)
print("cost :",cost(X,Y,a))
print()
#print(a)
#plot_assignment(X,Y,a)#,'a')
#%%
start3 = time.time()
print(time.time()-start1, "starting second injective optimal assigment")
a_bis = quad_assignment(X,Y)
end3 = time.time()
print(end3-start1, "second injective optimal assigment finished")
print("total time :", end3-start3)
print("cost :",cost(X,Y,a_bis))
print()
#
start4 = time.time()
print(time.time()-start4, "starting third injective optimal assigment with subproblem decomposition")
a_ter = assignment(X,Y)
end4 = time.time()
print(end4-start4, "third injective optimal assigment finished")
print("total time :", end4-start4)
print("cost :",cost(X,Y,a_ter))
print()
#
# start5 = time.time()
# print(time.time()-start5, "starting fourth injective optimal assigment with subproblem decomposition")
# a_quad = assignment_bis(X,Y)
# end5 = time.time()
# print(end5-start5, "fourth injective optimal assigment finished")
# print("total time :", end5-start5)
# print("cost :",cost(X,Y,a_quad))
# print()
#plot_assignment(X,Y,t,'t')
#plot_assignment(X,Y,a,'a')
#plot_assignment(X,Y,a_bis,'a_bis')
#plot_assignment(X,Y,a_ter,'a_ter')
#%%################## test assignment decomposition #####################
start6 = time.time()
print(time.time()-start6, "starting subproblem decomposition")
A = assignment_decomp(X, Y)
end6 = time.time()
print(end6-start6, "subproblem decomposition finished")
print("total time :", end6-start6)
plot_assignment_decomp(X,Y,A)
|
fdf792e9eff5984211c3b4d177f7b9f75436a174 | AliShahram/Breakthrough | /transition.py | 12,605 | 3.984375 | 4 | # Define the transition function
# Modified from 'turn functionality commit'
import traceback
import sys
class Board(object):
def __init__(self, list2d, cursor_at='O'):
"""Initializes the board with whose turn. Default is `O`"""
self.board = list2d
self.playerO = 'O'
self.playerX = 'X'
self.cursor_at = cursor_at
self.game_over = False
def is_game_over(self):
return self.game_over
def get_turn(self):
return self.cursor_at
def get_current_state(self):
return self.board
def is_valid(self, src, dst):
"""Checking to see if it's possible to move from src to dst.
Position is indicated by a tuple of the form (row, column).
NB: It works only when the `O` player moves UP and `X` moves
down"""
try:
(x,y) = src
(a,b) = dst
srcSym = self.get_sym(src)
dstSym = self.get_sym(dst)
# CP1(CheckPoint1): Invalid Index, negative and outside of list
if None in [srcSym, dstSym]:
# print("Out of bound error, both negative and larger than size")
return False
# CP2: source /= destination, same row movement not permitted either
if x == a:
# print("Error: src=dst")
return False
# CP3: Wrong Move Direction
# For player `O`, the valid dest direction is upwards
if srcSym == self.playerO:
if x == (a + 1):
pass
else:
# print("The direction is not upward")
return False
# For `X` the valid dest direction is downwards
if srcSym == self.playerX:
if x == (a - 1):
pass
else:
# print("The direction is not downward")
return False
# CP4: Movement of more than one unit
# The jump cannot be more than one unit forward or diagonal
col_diff = abs(y - b)
if col_diff > 1 or col_diff < 0:
return False
# CP5: Occupied by the same player
# A move can be made when the dst is either `.` or enemy
if dstSym == srcSym:
return False
else:
return True
except IndexError as e:
# print ("out of the board {0} {1}".format(dst, e))
return False
def display_state(self):
"""Prints out the state passed to this function on the terminal."""
print("\n######################################################\n")
for row in self.board:
for column in row:
print(column, end=' ')
print("\n")
print("######################################################\n")
return
def get_sym(self, position):
"""Returns the symbol/character at position passed.
Returns None if it's neither `O` nor `X`"""
try:
(x, y) = position
# Negative indices DOES NOT raise indexError in Python
# Board contains only positive (x,y) values.
for i in position:
if i < 0:
return None
sym = self.board[x][y].upper()
if sym == self.playerO:
return 'O' # or self.playerO
elif sym == self.playerX:
return 'X'
elif sym == '.':
return '.'
else:
return None
except IndexError:
return None
def get_direction(self, posit):
"""To get upwards or downwards direction for a given position"""
try:
sym = self.get_sym(posit)
direction = None
if sym == 'O':
direction = 'U'
elif sym == 'X':
direction = 'D'
else:
direction = None
return direction
except Exception:
return None
def get_positions(self, player):
"""Returns all the position occupied by a certain player"""
try:
if player not in [self.playerX, self.playerO]:
# print("Incorrect marker passed for player's symbol.")
raise ValueError
traceback.print_stack(file=sys.stdout)
positions_found = []
for x, row in enumerate(self.board):
for y, column in enumerate(row):
if column == player:
positions_found.append((x,y))
return positions_found
except Exception as e:
print("Exception occurred: ", e)
traceback.print_stack(file=sys.stdout)
def all_moves(self, player):
"""Returns a data structure full of possible moves by a player"""
all_positions = self.get_positions(player)
movement_dict = {}
for position in all_positions:
# A single source
(x,y) = position
# Is this moving upwards or downwards
flow = self.get_direction(position)
# All the moves for this position in a list
moves_for_this_position = self.get_moves(position)
for i, move in enumerate(moves_for_this_position):
(x1, y1) = move
if flow == 'U':
if y1 == y + 1: # to the right
# Replacing the destination with letter
moves_for_this_position[i] = 'R'
elif y1 == y - 1: # to the left
# Replacing the destination with letter
moves_for_this_position[i] = 'L'
elif y1 == y: # to forward
# Replacing the destination with letter
moves_for_this_position[i] = 'F'
else:
print("Somethig wrong in the get_moves function")
elif flow == 'D':
if y1 == y - 1: # to the right
# Replacing the destination with letter
moves_for_this_position[i] = 'R'
elif y1 == y + 1: # to the left
# Replacing the destination with letter
moves_for_this_position[i] = 'L'
elif y1 == y: # to forward
# Replacing the destination with letter
moves_for_this_position[i] = 'F'
else:
print("Sth wrong in the get_moves function")
else:
print("Direction is neither up nor down. Invalid")
movement_dict[position] = moves_for_this_position
return movement_dict
def get_moves(self, posit):
"""Returns a list of valid moves for the position passed"""
try:
(x,y) = posit
direction = self.get_direction(posit)
all_moves = []
valid_moves = []
if direction == 'U':
# direction upwards, (x-1, y-1): diagonal left,
# (x-1, y): forward, (x-1, y+1): diagonal right
all_moves = [(x-1, y-1), (x-1, y), (x-1,y+1)]
elif direction == 'D':
# direction upwards, (x+1, y-1): diagonal left,
# (x+1, y): forward, (x+1, y+1): diagonal right
all_moves = [(x+1, y-1), (x+1, y), (x+1,y+1)]
elif direction == '.':
pass
else:
# last elif and this else can be combined
pass
# Filtering the valid moves
for move in all_moves:
if self.is_valid(posit, move) == True:
valid_moves.append(move)
else:
pass
return valid_moves
except TypeError:
print("Invalid position, TypeError raised.")
return []
def terminal_state(self):
"""Check if current state is a terminal one."""
# Need to change the variable names to make things more consistent
player1 = False
player2 = False
p1list = []
p2list = []
for row in self.board:
for element in row:
#First case, when one of the players pieces is all out
if element is self.playerX:
p1list.append(element)
if element is self.playerO:
p2list.append(element)
#Second case, when one of the pieces move to the last row
for element in self.board[-1]:
if element == "X":
player1 = True
for element in self.board[0]:
if element == "O":
player2 = True
#Print the result for both cases
if player1 is True:
# print("First case, when one of the players pieces is all out")
#print("Game Over. Player X won")
self.game_over = True
return self.playerX
if player2 is True:
# print("First case, when one of the players pieces is all out")
#print("Game Over. Player O won")
self.game_over = True
return self.playerO
if len(p1list) == 0:
# print ("Second case, when one of the pieces move to the last row")
#print("Game Over. Player O won")
self.game_over = True
return self.playerO
if len(p2list) == 0:
# print ("Second case, when one of the pieces move to the last row")
#print("Game Over. Player X won")
self.game_over = True
return self.playerX
# None of the winning conditions returned True
return None
def switch_turn(self):
if self.cursor_at == self.playerO:
self.cursor_at = self.playerX
elif self.cursor_at == self.playerX:
self.cursor_at = self.playerO
else:
raise Exception
return self.cursor_at
def move(self, posit, turn):
"""Move to the direction =['R','L','F'] asked to from position passed"""
try:
# Check if it's current players turn
if self.cursor_at != self.get_sym(posit):
# print("Move not allowed. {0}'s turn now".format(self.cursor_at))
return False
# Identify the destination
(x, y) = posit
# Initialize the destination tuple
a = 99999999
b = 99999999
flow = self.get_direction(posit)
# Figuring out the dest X (=a) value
if flow == 'U':
a = x - 1
# Figuring out the dest Y (=b) value
if turn == 'R':
b = y + 1
elif turn == 'L':
b = y - 1
elif turn == 'F':
b = y
else:
print ("Invalid move direction")
return False
elif flow == 'D':
a = x + 1
if turn == 'R':
b = y - 1
elif turn == 'L':
b = y + 1
elif turn == 'F':
b = y
else:
print ("Invalid move direction")
return False
else:
# When get_direction == None, return Failure
return False
# validate move
dest = (a,b)
if self.is_valid(posit, dest) != True:
return False
# Move the current player to the dest, assign `.` at empty spot
self.board[a][b] = self.board[x][y]
self.board[x][y] = '.'
# Flip the turn to the other player
# print("{0} just played.".format(self.cursor_at))
self.switch_turn()
# print("Next is {0}'s turn.".format(self.cursor_at))
return True
except Exception as e:
# Anything goes wrong
print("Exception occured: ", e)
return False
|
07b0bc40c5b6c9dba60509d3a70a1357298a1f98 | Aimeelynnramirez/getting_started_with_python | /hello.py | 198 | 3.703125 | 4 | print("hello there everybody this is a new file for python and see it is simple as abc")
a,b,c= 'kristine', 'mila' , 'gilbert'
print("Name is:", a)
print("Name b is:", b)
print ("Name c is:", c)
|
e074e8f80d4c548737920df77b87af406bd49730 | marianohtl/LogicaComPython | /Cousera/exe036.py | 736 | 3.75 | 4 | #Fórmula de Bhaskara
import math
def delta (a,b,c):
return b**2 - 4 * a * c
def imprime_raizes(a,b,c):
d = delta(a,b,c)
if d == 0:
raiz1 = (-b + math.sqrt(d)/(2*a))
print('A única raiz é: {}'.format(raiz1))
else:
if d < 0:
print('Esta equação não possui raizes reais.')
else:
raiz1 = (-b + math.sqrt(d) / (2 * a))
raiz2 = (-b - math.sqrt(d) / (2 * a))
print('A primeira raiz é: {}'.format(raiz1))
print('A segunda raiz é: {}'.format(raiz2))
def main():
a = float(input('Digite o valor de a: '))
b = float(input('Digite o valor de b: '))
c = float(input('Digite o valor de c: '))
imprime_raizes(a,b,c)
main()
|
2642ca5e82be734ef9753cee61d54dffc0d2e76e | avikabra/idtech-python-tensorflow | /IDTECH - 2018/Wednesday - Splicing.py | 404 | 3.765625 | 4 | times = int(input("How many items would you like to add to the list"))
userList = []
for i in range (0, times):
userInput = int(input("Add a number"))
userList.append(userInput)
oneList = int(times/2)
A = []
B = []
if times%2==0:
A = userList[:oneList]
B = userList[oneList:]
else:
A = userList[:oneList+1]
B = userList[oneList:]
print("A is " + str(A))
print("B is " + str(B)) |
06994ddbedf62e2d2d8d49199a17881bf03a0d3c | Aholloway20/MyRepo | /Save.py | 124 | 3.671875 | 4 | with open("saved.txt", "a") as file:
file.write("I've added another line with append!\n")
file.write("New Line!\n")
|
a3663adc04a2db1edd3b1714b8ee2b6fa6989665 | lingtianwan/Leetcode2 | /Algorithm/10_RegularExpressionMatching.py | 2,373 | 4.125 | 4 | # Implement regular expression matching with support for '.' and '*'.
#
# '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
#
# The matching should cover the entire input string (not partial).
#
# The function prototype should be:
# bool isMatch(const char *s, const char *p)
#
# Some examples:
# isMatch("aa","a") → false
# isMatch("aa","aa") → true
# isMatch("aaa","aa") → false
# isMatch("aa", "a*") → true
# isMatch("aa", ".*") → true
# isMatch("ab", ".*") → true
# isMatch("aab", "c*a*b") → true
# Show Company Tags
# Show Tags
# Show Similar Problems
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
return self.search(s, p, 0, 0)
def search(self, s, p, idxs, idxp):
lens = len(s)
lenp = len(p)
if idxp == lenp:
return idxs == lens
if idxp == lenp - 1:
return (idxs == lens - 1) and self.match(s, p, idxs, idxp)
if p[idxp + 1] != '*':
if idxs < lens and self.match(s, p, idxs, idxp):
return self.search(s, p, idxs + 1, idxp + 1)
else:
return False
if self.search(s, p, idxs, idxp + 2):
return True
for i in range(idxs, lens):
if not self.match(s, p, i, idxp):
return False
if self.search(s, p, i + 1, idxp + 2):
return True
return False
def match(self, s, p, idxs, idxp):
return s[idxs] == p[idxp] or p[idxp] == '.'
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
dp = [[False for i in range(len(p)+1)] for j in range(len(s)+1)]
dp[0][0] = True
for i in range(len(p) + 1):
if i >= 2 and p[i-1] == '*':
dp[0][i] = dp[0][i - 2]
for i in range(1, len(s) + 1):
for j in range(1, len(p) + 1):
if p[j - 1] == '*':
dp[i][j] = dp[i][j - 2]
if s[i - 1] == p[j - 2] or p[j - 2] == '.':
dp[i][j] |= dp[i - 1][j]
elif p[j - 1] == '.' or s[i - 1] == p[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
return dp[-1][-1]
|
eddf8d802d8905c1ff8958c6d57253eb8e65f33b | abrodin/cours_Python | /creation_drawman/task_problem2.py | 588 | 3.546875 | 4 | from drawman import *
from time import sleep
drawman_scale(30)
coordinate_grid_axis()
def f(x):
return x**2 - 9
a = 0
b = 10
x = a
to_point(x,f(x))
pen_down()
while x<=b:
to_point(x,f(x))
x += 0.1
pen_up()
assert f(a)*f(b) < 0 #Функция должна быть знакопеременной на отрезке
while (b-a)/2 > 0.0000001:
c = (a+b)/2
if f(c)*f(a) < 0:
b = c #a,b = a,c
elif f(c) * f(a) > 0:
a = c #a,b = c,b
else:
a,b = c
print('корень: ',(a+b)/2, '+-',(b-a)/2)
sleep(5) |
46ca98c351c293c6798cb7a40c34e8daa35786eb | ceberous/osxSettings | /standardDeviation | 830 | 3.875 | 4 | #!/usr/bin/env python3
import math
import numpy
total_items = int( input( "Total Number of Items = " ) )
data_points = []
for i in range( 1 , total_items + 1 ):
data_points.append( float( input( f"Item: {i} = " ) ) )
sum = 0
for i , dp in enumerate( data_points ):
sum += dp
average = ( sum / total_items )
print( f"Average = {average}" )
numpy_average = numpy.mean( data_points )
print( f"Numpy Average = {numpy_average}" )
sum_of_squared_deviation = 0
for i in range( len( data_points ) ):
sum_of_squared_deviation += ( data_points[i] - average )**2
standard_deviation = ( ( sum_of_squared_deviation ) / len( data_points ) )**0.5
print( f"Standard Deviation = {standard_deviation}" )
numpy_standard_deviation = numpy.std( numpy.array( data_points ) )
print( f"Numpy Standard Deviation = {numpy_standard_deviation}" )
|
2132db4ed1d3f7d508654259f45d88c8c1130913 | Maxtasy/adventofcode2017 | /day14-2.py | 2,134 | 3.53125 | 4 | #https://adventofcode.com/2017/day/14
def part2(input_file):
def create_knot_hash(hash_input, suffix = [17, 31, 73, 47, 23]):
sequence = []
for c in hash_input:
sequence.append(ord(c))
sequence += suffix
pos = 0
skip = 0
sparse = list(range(256))
for i in range(64):
for length in sequence:
for i in range(length // 2):
temp = sparse[(pos + i) % 256]
sparse[(pos + i) % 256] = sparse[(pos + length - 1 - i) % 256]
sparse[(pos + length - 1 - i) % 256] = temp
pos = (pos + length + skip) % 256
skip += 1
dense = []
index = 0
for _ in range(16):
xor = 0
for i in range(16):
xor ^= sparse[index + i]
dense.append(xor)
index += 16
knot_hash = ""
for element in dense:
h = hex(element)
if len(h) < 4:
hex_value = "0"+h[-1]
else:
hex_value = h[-2:]
knot_hash += hex_value
return knot_hash
def convert_to_binary_string(knot_hash):
binary_string = ""
for c in knot_hash:
binary_part = f'{int(c, 16):0004b}'
binary_string += binary_part
return binary_string
def dfs(start):
stack = [start]
while stack:
(x, y) = stack.pop()
for dx, dy in DELTAS:
candidate = x+dx, y+dy
if candidate in maze:
stack.append(candidate)
maze.remove(candidate)
with open(input_file, "r") as f:
prefix = f.read()
hash_inputs = []
for i in range(128):
hash_inputs.append(prefix + "-" + str(i))
knot_hashes = []
for hash_input in hash_inputs:
knot_hashes.append(create_knot_hash(hash_input))
binary_strings = []
for knot_hash in knot_hashes:
binary_strings.append(convert_to_binary_string(knot_hash))
maze = set()
for i in range(128):
for j in range(128):
if binary_strings[i][j] == "1":
used_bit = (i, j)
maze.add(used_bit)
DELTAS = ((1, 0), (-1, 0), (0, 1), (0, -1))
regions = 0
while maze:
dfs(maze.pop())
regions += 1
return regions
def main():
input_file = "day14-input.txt"
print(part2(input_file))
if __name__ == "__main__":
main() |
b196145d01bfa27a7b0dd535be19c5a67c8e774b | cgwu/objc | /Python/Function.py | 520 | 3.828125 | 4 | #!/usr/bin/env python3
'''
Python 包含4种函数:
全局函数,局部函数,Lambda, 方法
'''
s = lambda x: '' if x == 1 else 's'
count = 1
print("{0} file{1} processed".format(count, s(count)))
count = 2
print("{0} file{1} processed".format(count, s(count)))
elements = [(2,12,'Mg'), (1,11,'Na'), (2, 4,"Be")]
elements.sort()
print(elements)
#elements.sort(key = lambda e: (e[1], e[2]))
elements.sort(key = lambda e: e[1:3])
print(elements)
elements.sort(key = lambda e: (e[2].lower(), e[1]))
print(elements)
|
2a1d95e9bbdaa95bdbc69b9a756ce3d13a17b251 | zion0624/practice | /while.py | 382 | 3.875 | 4 | while False:
print('hello world')
print("______________")
i=0
while i<3:
print('zion')
i=i+1
print("______________")
a=0
while a<5:
print('number'+str(a*4)) # str_숫자를 문자화 하여 계산 (int는 문자를 정수화 하여 계산)
a=a+1
print("______________")
b=0
while b<9:
if b != 4: # a!=b _ a와 b 가 다를떄 True
print(b)
b=b+1
|
11e8110396375190a3254b142e2495b68b3ced1e | younusesherif/IBMLabs | /hcf.py | 229 | 3.65625 | 4 | def hcf(x,y):
if(x>y):
small=y
else:
small=x
for i in range(1,small+1):
if(x%i==0) and (y%i==0):
print(i)
hcf = i
return hcf
x=10
y=5
print(hcf(x,y)) |
1379e85f0d3ce764d3c3638521709376db7bb594 | bruggerl/gdp-height | /src/constants.py | 285 | 3.8125 | 4 | from enum import Enum
class Sex(Enum):
"""
This enumeration is used to differentiate between the two sexes.
"""
MALE = 0
FEMALE = 1
COUNTRY = 'Country'
COUNTRY_CODE = 'Country code'
AVG_HEIGHT = 'Mean height of 19-year-olds in cm'
GDP = 'GDP per capita in USD'
|
0ed86a7920e1c2603320c77b1c2eb3bba4c509a8 | snnsch/FHW_ADD_SS2020_Weninger | /B_variable_operations.py | 615 | 3.96875 | 4 | # PLEASE NOTE: This snippet is about basic arithmetic and variable operations
### AUFGABE: Wie funktionieren Variablenzuweisungen und Operationen mit Variablen?
# ONE Arithmetic operations with numbers
a = 10
b = 2
c = 12.7
#print(a + b)
#print(a - c)
#print(a * b)
#print(a / c)
# TWO Same artihmetic operations possible with type "string"?
c = "Hello"
d = "Anna"
#print(c + d) # vs print(c,d)
#print(c - d)
#print(c * d)
#print(c / d)
# THREE "Mixing" numerical and textual data?
number = 12.4
text = "random text"
#print(number + text)
#print(number,text)
# FOUR Advanced Maths
e = 3
f = 9
#print(a % b)
|
096fbdc1daf89e021c802016c6ca32d3d65987c8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/77/usersdata/234/43849/submittedfiles/exercicio24.py | 250 | 3.875 | 4 | # -*- coding: utf-8 -*-
import math
a=int(input('digite o valor de a:'))
b=int(input('digite o valor de b:'))
if a<b:
menor=a
else:
menor=b
for i in range(1, menor+ 1,1):
if a% i ==0 and b% i==0:
mdc=i
print(mdc)
|
1ef41f5c2c4e5a0965d720ff9e600aad4a0cba52 | Sindroc/coding_problems | /rotate_left.py | 641 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 09:47:38 2021
@author: sindy
"""
def left_rotate(original_matrix):
length = len(original_matrix)
left_rotate = [None]*length
for row in range(length): # initialize the rotate matrix
left_rotate[row] = [None] * length # with None values
for row in range(length):
for col in range(length): # fill the matrix
left_rotate[row][col] = original_matrix[col][length - row - 1]
return left_rotate
original_matrix = [[1,2,3], [4,5,6], [7,8,9]]
left_rotate(original_matrix)
|
0ab985812f15c0e8535f135639c4dc551326dcdf | mluis98/AprendiendoPython | /practica/condiciones_ejercicios2.py | 233 | 3.953125 | 4 | equipo = raw_input("ingrese nombre de un equipo")
print "el nombre ingresado es:" + equipo
if equipo == "madrid":
print "es del madrid"
elif equipo == "barcelona":
print "es del barcelona"
else:
print "ni del madrid y barcelona" |
3d4c5c08c9d10217581260655a327a13428b4691 | Kdk22/PythonLearning | /PythonApplication3/name_mangling.py | 2,481 | 3.796875 | 4 | class Myclass:
def mypublicmethod(self):
print('Public Method')
def __myprivatemethod(self):
print('Private Method')
obj = Myclass()
obj.mypublicmethod()
# obj.__myprivatemethod() # try to run this
print(dir(obj))
obj._Myclass__myprivatemethod()
class Foo:
def __init__(self):
self.__baz =42
def foo(self):
print(self.__baz)
class Bar(Foo):
def __init__(self):
super().__init__()
self.__baz = 21
def bar(self):
print(self.__baz)
x = Bar()
x.foo()
x.bar()
print(x.__dict__)
'''
# THis code is from python documentation but I don't understood
so below is the simiar code to this from stack
class Mapping:
def __init__(self, iterable):
self.items_list =[]
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update
class MappingSubclass(Mapping):
def update(self, keys, values):
for item in zip(keys, values):
self.items_list.append(item)
'''
# ref : https://stackoverflow.com/questions/1162234/what-is-the-benefit-of-private-name-mangling-in-python
class Parent:
def __init__(self):
self.__help('will take child to school')
def help(self, activities):
print('parent', activities)
__help = help #private copy of orginal help() method
class Child(Parent):
#new signature for help() and does not break __init__()
def help(self, activities, days):
self.activities = activities
self.days = days
print('Child will do ', self.activities, self.days)
print('list parents & child responsibiliteis')
c = Child()
c.help('laundry', 'Saturdays')
#ref : https://stackoverflow.com/questions/38606804/private-variables-and-class-local-references?rq=1
class Foo:
__attr = 5
attr= 6
print(__attr) #prints 5
#exec('print(__attr)') #raises NameError
exec('print(attr)') #prints 6
exec('print(_Foo__attr)') #prints 5
#compare above two exec() methods
'''
Notice that code passed to exec,
eval() or execfile() does not consider
the classname of the invoking class to
be the current class;
'''
print(Foo.attr)
#print(Foo.__attr) #raises AttributeError
#print(_Foo__attr) #error
c = Foo()
print(c._Foo__attr) #prints 5
'''Outside of class private varibles or dunders variables
can be called through object._Classname__attributename |
ea85b4dd79a68ac9eae8d5309a95dcb499860b69 | ZanataMahatma/Python-Exercicios | /Repetições em Python (while)/ex060.py | 878 | 4.28125 | 4 | '''Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial. Exemplo:
5! = 5 x 4 x 3 x 2 x 1 = 120'''
#correção
'''from math import factorial
n = int(input('Digite um numero para calcular seu FATORIAL:'))
f = factorial(n)
print('O fatorial de {} é {}.'.format(n,f))'''
n = int(input('Digite um numero para calcular seu FATORIAL:'))
c = n
f = 1
print('Calculando {}! = '.format(n), end='')
while c > 0:
print('{}'.format(c), end='')
print('x' if c > 1 else '=', end='')
f = f * c
c = c - 1
print('{}'.format(f))
#minha resposta
'''r = 'S'
fat4 = 0
while r == 'S':
n1 = int(input('Digite um numero: '))
fat = n1 * 4
fat2 = fat * 3
fat3 = fat2 * 2
fat4 = fat3 * 1
print('{}x4x3x2x1={}'.format(n1,fat4))
r = str(input('Quer Calcular outro numero fatorial? [S/N]')).upper()
print('Fim')''' |
305d62d8edf9b550bed50a9e76aad08a86f1ff7e | tylerharter/caraza-harter-com | /tyler/cs301/spring19/materials/code/lec-06/sec3/add.py | 112 | 3.859375 | 4 | x = input("give me an number: ")
y = input("give me another number: ")
x = float(x)
y = float(y)
print(x + y)
|
8ce2019057d4772ef5b1bc79c8677119bf88b1c3 | vonnenaut/coursera_python | /4 of 7 -- Principles of Computing 2/wk4 -- modeling/solve_interior_tile.py | 3,296 | 3.828125 | 4 | def solve_interior_tile(self, target_row, target_col):
"""
Place correct tile at target position
Updates puzzle and returns a move string
"""
# test assrtion that target_row > 1 and target_col > 0
assert target_row > 1
assert target_col > 0
# find the current position of the tile that should appear at this position in a solved puzzle
clone = self.clone()
clone.update_target_tile(target_row, target_col)
move_string = ""
temp_string = ''
clone.get_zero_pos()
ttile_row = clone.get_target_tile()[0]
ttile_col = clone.get_target_tile()[1]
zero_row = clone.get_zero_pos()[0]
zero_col = clone.get_zero_pos()[1]
if target_col == ttile_col:
col_multi = 1
else:
col_multi = abs(target_col - ttile_col)
if target_row == ttile_row:
row_multi = 1
else:
row_multi = abs(target_row - ttile_row)
# Base case
if ttile_row == target_row and ttile_col == target_col:
return ''
# Recursive case
# case 1: target tile is in same col (above zero tile)
if ttile_col == zero_col:
if row_multi == 1:
temp_string += 'uld'
elif ttile_row < zero_row and zero_col < clone.get_width() - 1:
temp_string += 'u' * col_multi + 'r' + 'd' * col_multi + 'lurd'
elif ttile_row < zero_row and zero_col == clone.get_width() - 1:
temp_string += 'u' * row_multi + 'l' + 'dd' + 'ruld'
# case 2: target tile is in same row (to left or right of zero tile)
elif ttile_row == zero_row:
if col_multi == 1 and ttile_row == target_row:
temp_string += 'l'
elif ttile_col < zero_col and zero_row < target_row:
temp_string += 'l' * col_multi + 'd' + 'r' * col_multi + 'uld'
elif ttile_col < zero_col and zero_row == target_row:
temp_string += 'l' * col_multi + 'u' + 'r' * col_multi + 'dl'
elif ttile_col > zero_col and zero_row < target_row and target_col == ttile_col:
temp_string += 'druld'*abs(ttile_row - target_row)
elif zero_row > 0:
temp_string += 'rulld'
else:
temp_string += 'rdlulddruld'
# case 3: neither (1) same col nor (2) same row
else:
print clone.__str__()
if ttile_row > zero_row:
temp_string += 'd' * abs(ttile_row - zero_row)
elif ttile_row < zero_row:
temp_string += 'u' * abs(ttile_row - zero_row)
elif ttile_row == zero_row and zero_col < self.get_width():
temp_string += 'druld'
# update move string, puzzle, zero position and target tile position
move_string += temp_string
clone.update_puzzle(temp_string)
clone.get_zero_pos()
clone.update_target_tile(target_row, target_col)
move_string += clone.solve_interior_tile(target_row, target_col)
# update the puzzle and return the entire move string
self.update_puzzle(move_string)
return move_string |
5150f5bfd485a47cede8b121502f490c75821ae8 | karrollinaaa/kody | /py i cpp/warunek.py | 431 | 3.671875 | 4 | def main(args):
a = int(input('Podaj pierwszą liczbę: '))
b = int(input('Podaj drugą liczbę: '))
c = int(input('Podaj trzecią liczbę: '))
if a > b and a > c:
print('Największa liczba: ', a)
elif b > a and b > c:
print('Największa liczba: ', b)
else:
print('Największa liczba: ', c)
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))
|
c9fe5f98e69a709b071a76c362f980639af9d41d | OlaBer/Python | /Ex20_zadanie.py | 155 | 3.671875 | 4 | my_lst = [1,2,3,4,5]
def sum_lst(_lst):
_sum = 0
for el in _lst:
_sum = _sum + el
return _sum
print(sum_lst(my_lst))
|
2d3e5e6a6ba632419b01f95da9ce99a49f1500b4 | x77686d/pytester | /test_seq.py | 146 | 3.546875 | 4 | def main():
start = int(input())
end = int(input())
step = int(input())
for i in range(start,end,step):
print(i)
main()
|
b7bfb63780329c649d2ae786797127793694d9c1 | FarzanaEva/Data-Structure-and-Algorithm-Practice | /InterviewBit Problems/Backtracking/permutations.py | 1,087 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-07-17 04:21:14
# @Author : Farzana Eva
# @Version : 1.0.0
"""
PROBLEM STATEMENT:
Given a collection of numbers, return all possible permutations.
Example:
[1,2,3] will have the following permutations:
[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]
NOTE
No two entries in the permutation sequence should be the same.
For the purpose of this problem, assume that all the numbers in the collection are unique.
Warning : DO NOT USE LIBRARY FUNCTION FOR GENERATING PERMUTATIONS.
Example : next_permutations in C++ / itertools.permutations in python.
If you do, we will disqualify your submission retroactively and give you penalty points.
"""
class Solution:
# @param A : list of integers
# @return a list of list of integers
def permute(self, A):
if len(A) == 1: return [A]
permute_list = []
for i in range(len(A)):
left_nums = self.permute(A[:i]+A[i+1:])
for num in left_nums:
permute_list.append([A[i]]+num)
return permute_list
|
3d78565d407b4b37c843d12fa156126afbf4ea7d | ProjectEDGE/Python3 | /[002] Chapter - Flow Control/[+]_Chapter_[01]_Value_Boolean/[002]_Example.py | 574 | 4.03125 | 4 |
nombre1 = "Esteban" # Variable nombre1 con un valor asignado.
nombre2 = "Moises" # Variable nombre2 con un valor asignado.
print("El Nombre1 y Nombre2 son Iguales : ", nombre1 == nombre2)
print("Los Nombres No son iguales : ", nombre1 != nombre2)
print("El Nombre1 es Menos que Nombre2 : ", nombre1 < nombre2)
print("El Nombre1 es Mayor que Nombre2 : ", nombre1 > nombre2)
print("El Nombre1 es Menor o Igual que Nombre2 : ", nombre1 <= nombre2)
print("El Nombre1 es Mayor o Igual que Nombre2 : ", nombre1 >= nombre2)
|
f953efdf175971e336b6f4b40f017b1f95dbaca7 | dannymulligan/Project_Euler.net | /Prob_107/prob_107.py | 9,728 | 3.578125 | 4 | #!/usr/bin/python
#
# Project Euler.net Problem 107
#
# Determining the most efficient way to connect the network.
#
# The following undirected network consists of seven vertices and
# twelve edges with a total weight of 243.
#
# 20
# B --------- E
# / \ / \
# 16/ 17\ /18 \11
# / \ / \
# A -------- D -------- G
# \ 21 / \ 23 /
# 12\ /28 \19 /27
# \ / \ /
# C --------- F
# 31
#
# The same network can be represented by the matrix below.
# A B C D E F G
# A - 16 12 21 - - -
# B 16 - - 17 20 - -
# C 12 - - 28 - 31 -
# D 21 17 28 - 18 19 23
# E - 20 - 18 - - 11
# F - - 31 19 - - 27
# G - - - 23 11 27 -
#
# However, it is possible to optimise the network by removing some
# edges and still ensure that all points on the network remain
# connected. The network which achieves the maximum saving is shown
# below. It has a weight of 93, representing a saving of 243 - 93 =
# 150 from the original network.
#
#
# B E
# / \ / \
# 16/ 17\ /18 \11
# / \ / \
# A D G
# \ \
# 12\ \19
# \ \
# C F
#
# Using network.txt (right click and 'Save Link/Target As...'), a 6K
# text file containing a network with forty vertices, and given in
# matrix form, find the maximum saving which can be achieved by
# removing redundant edges whilst ensuring that the network remains
# connected.
#
# Solved:
# ? problems solved
# Position #??? on level ?
import mini_network
weights = mini_network.weights
#import network
#weights = network.weights
########################################
# Gather info on the starting point
nsize = len(weights)
print "Network size =", nsize
starting_vertices = 0
starting_weight = 0
for i in range(nsize):
for j in range(i,nsize):
if (weights[i][j] != 0):
starting_vertices += 1
starting_weight += weights[i][j]
print "There are {} vertices, weighing {}".format(starting_vertices, starting_weight)
########################################
def print_network():
# Analyze the matrix
nvertices = 0
nweight = 0
for i in range(nsize):
for j in range(i,nsize):
if (weights[i][j] != 0):
nvertices += 1
nweight += weights[i][j]
# Print the matrix
print "The current connection matrix is..."
print " {:2} ".format(' '),
for i in range(nsize):
print " {:2} ".format(i),
print
for i in range(nsize):
print " {:2} ".format(i),
for j in range(nsize):
if (j == i):
print " . ",
elif (weights[i][j] == 0):
print " - ",
else:
print "{:3} ".format(weights[i][j]),
print
print "There are {} vertices, which is {:.1f}% of the starting number of vertices of {}".format(nvertices, 100.0*nvertices/starting_vertices, starting_vertices)
print "The weight is {}, which is {:.1f}% of the starting weight of {}".format(nweight, 100.0*nweight/starting_weight, starting_weight)
print "----"
########################################
def find_loop(start_node, max_length):
dist = [[-1]*nsize for _ in range(nsize)]
for i in range(nsize):
dist[i][i] = 0
print "dist = "
for dd in dist:
print " {}".format(dd)
for d in range(max_length):
for n in range(nsize):
print "Searching for nodes that are {} step(s) from {}".format(d+1, n)
for i in range(nsize):
if (dist[n][i] == d):
for j in range(nsize):
if (j == i):
continue
print " weight[{}][{}] = {}, dist[{}][{}] = {}".format(i, j, weights[i][j], n, j, dist[n][j])
if (weights[i][j] != 0):
if (dist[n][j] == -1):
dist[n][j] = d+1
print "node {} is {} from node {} because weight[{}][{}] = {}".format(j, d+1, n, i, j, weights[i][j])
elif ((d + 1 + dist[n][j]) >= 3):
print "Found a loop of distance {}, start_node = {}".format((d + 1 + dist[n][j]), n)
print " dist[{}] = {}".format(n, dist[n])
print " intermediate nodes = {} & {}, weights[{}][{}] = {}".format(i, j, i, j, weights[i][j])
loop = [i, j]
print "starting to build loop, loop = {}".format(loop)
print "dist[{}] = {}".format(n, dist[n])
# Backtrack to the start of the loop
print "range({}, 0, -1) = {}".format((dist[n][i]-1), range(dist[n][i]-1, 0, -1))
for dist_b in range(dist[n][i]-1, 0, -1):
for b in range(nsize):
if (dist[n][b] == dist_b):
if (weights[loop[0]][b] != 0):
loop.insert(0, b)
break
print "done backtracking, loop = {}".format(loop)
# The loop starts with n
loop.insert(0, n)
print "added start, loop = {}".format(loop)
# Forward to the end of the loop
for dist_f in range(dist[n][j]-1, 0, -1):
for b in range(nsize):
if (dist[n][b] == dist_f):
if (weights[loop[-1]][b] != 0):
loop.append(b)
break
print "done forward tracking, loop = {}".format(loop)
return loop
print "dist = "
for dd in dist:
print " {}".format(dd)
return []
########################################
def disconnect_loop(loop):
best_weight = 0
best_start = 0
best_end = 0
for i in range(len(loop)):
start = loop[i-1]
end = loop[i]
if (start > end):
start, end = end, start
weight = weights[start][end]
assert (weight != 0), "{} is not a loop, vertex {}-{} has a weight of 0".format(loop, start, end)
if (weight > best_weight):
best_weight = weight
best_start = start
best_end = end
print "Disconnecting {}-{} (weight = {})".format(best_start, best_end, best_weight)
weights[best_start][best_end] = 0
weights[best_end][best_start] = 0
return
########################################
# Report some statistics on the network before we begin
print_network()
########################################
# Count the number of vertices
nvertices = 0
nweight = 0
for i in range(nsize):
for j in range(i,nsize):
if (weights[i][j] != 0):
nvertices += 1
nweight += weights[i][j]
########################################
# Main loop
progress = True
while(progress):
progress = False
# Count the number of connections for each node
nconnections = [0] * nsize
for i in range(nsize):
for j in range(i,nsize):
if (weights[i][j] != 0):
nconnections[i] += 1
nconnections[j] += 1
# Try to break a loop of length 3, 4, 5, etc
for loop_length in range(3,nsize):
for start_node in range(nsize):
if (nconnections[start_node] > 1):
loop = find_loop(start_node=start_node, max_length=loop_length)
if (len(loop) > 0):
progress = True
print "Found {}, a loop of length {}".format(loop, loop_length)
disconnect_loop(loop)
break
if (progress):
break
print_network()
print "No further progress can be made, this is the final network"
nweight = 0
for i in range(nsize):
for j in range(i,nsize):
if (weights[i][j] != 0):
nweight += weights[i][j]
print "Answer = {}".format(nweight)
## Code to test disconnect_loop using the example problem
#print "\ndisconnect_loop([0, 1, 3])"
#disconnect_loop([0, 1, 3])
#print_network()
#
#print "\ndisconnect_loop([1, 3, 4])"
#disconnect_loop([1, 3, 4])
#print_network()
#
#print "\ndisconnect_loop([2, 3, 5])"
#disconnect_loop([2, 3, 5])
#print_network()
#
#print "\ndisconnect_loop([3, 4, 6])"
#disconnect_loop([3, 4, 6])
#print_network()
#
#print "\ndisconnect_loop([0, 1, 3, 2])"
#disconnect_loop([0, 1, 3, 2])
#print_network()
#
#print "\ndisconnect_loop([3, 4, 6, 5])"
#disconnect_loop([3, 4, 6, 5])
#print_network()
|
fc45e9359b9a6e8444d256785d9c11e656c1daab | arunh/python-by-example-150-challenges | /challenges1-11/challenage-004.py | 186 | 4.0625 | 4 | number_1 = int(input('Calculate two numbers \n please, enter 1st. number : '))
number_2 = int(input('please, enter 2st. number : '))
print('the result is {0}'.format(number_1+number_2))
|
0302bc1531e1ae19b905e958b71c1772ee9e0f05 | messizqin/ConvexHull | /GrahamScan.py | 1,525 | 3.671875 | 4 | # Author: Rodolfo Ferro
# Mail: ferro@cimat.mx
# Script: Compute the Convex Hull of a set of points using the Graham Scan
import sys
import numpy as np
import matplotlib.pyplot as plt
# Function to know if we have a CCW turn
def RightTurn(p1, p2, p3):
if (p3[1]-p1[1])*(p2[0]-p1[0]) >= (p2[1]-p1[1])*(p3[0]-p1[0]):
return False
return True
# Main algorithm:
def GrahamScan(P):
P.sort() # Sort the set of points
L_upper = [P[0], P[1]] # Initialize upper part
# Compute the upper part of the hull
for i in range(2,len(P)):
L_upper.append(P[i])
while len(L_upper) > 2 and not RightTurn(L_upper[-1],L_upper[-2],L_upper[-3]):
del L_upper[-2]
L_lower = [P[-1], P[-2]] # Initialize the lower part
# Compute the lower part of the hull
for i in range(len(P)-3,-1,-1):
L_lower.append(P[i])
while len(L_lower) > 2 and not RightTurn(L_lower[-1],L_lower[-2],L_lower[-3]):
del L_lower[-2]
del L_lower[0]
del L_lower[-1]
L = L_upper + L_lower # Build the full hull
return np.array(L)
def main():
try:
N = int(sys.argv[1])
except:
N = int(input("Introduce N: "))
# By default we build a random set of N points with coordinates in [0,300)x[0,300):
P = [(np.random.randint(0,300),np.random.randint(0,300)) for i in range(N)]
L = GrahamScan(P)
P = np.array(P)
# Plot the computed Convex Hull:
plt.figure()
plt.plot(L[:,0],L[:,1], 'b-', picker=5)
plt.plot([L[-1,0],L[0,0]],[L[-1,1],L[0,1]], 'b-', picker=5)
plt.plot(P[:,0],P[:,1],".r")
plt.axis('off')
plt.show()
if __name__ == '__main__':
main()
|
78d1084a4dcf796b06973f9f66fc737a51737b20 | tahabroachwala/hangman | /ExternalGuessingGame.py | 1,109 | 4.28125 | 4 | # The Guess Game
# secret number between 1 and 100
import random
randomNumber = random.randrange(1, 100) # changed from 10 to 100
#print randomNumber #check if it's working
# rules
print('Hello and welcome to the guess game !')
print('The number is between 1 and 100')
guesses = set() # your set of guesses
guessed = False
tries = 0 # no need add 1 to the tries here
while guessed == False:
userInput = int(input("Please enter your guess: "))
if userInput not in guesses: # if it's not in our set
tries += 1 # increase the tries
guesses.add(userInput) # add it to our set
if userInput == randomNumber:
guessed = True
tries = str(tries)
print("Congratulations ! You win after " + tries + " tries ! ")
elif userInput > 100 or userInput < 1:
print("The guess range is between 1 and 100, please try again")
elif userInput > randomNumber:
print("Your guess is too large")
elif userInput < randomNumber:
print("Your guess is too small")
print("End of the game, please play again")
|
1d8f9b3b3a6b37880e236f15d44d3f118f95d2e7 | CodeInDna/Data_Scientist_With_Python | /06_Introduction_to_Data_Visualization_with_Python/01_Customizing_Plots.py | 14,463 | 4.3125 | 4 | # The axes() command
# Syntax: axes([x_yo, y_lo, width, height]) # All expressed in Figure Units
# By Figure Units, it means numbers between 0 and 1
# The subplot() command
# Syntax: subplot(nrows, ncols, nsubplot)
# Subplot Ordering:
# Row-wise from top-left
# Indexed from 1
import numpy as np
import matplotlib.pyplot as plt
# Multiple plots on single axis
# It is time now to put together some of what you have learned and combine line plots on a common set of axes. The data set here comes from records of undergraduate degrees awarded to women in a variety of fields from 1970 to 2011. You can compare trends in degrees most easily by viewing two curves on the same set of axes.
# Here, three NumPy arrays have been pre-loaded for you: year (enumerating years from 1970 to 2011 inclusive), physical_sciences (representing the percentage of Physical Sciences degrees awarded to women each in corresponding year), and computer_science (representing the percentage of Computer Science degrees awarded to women in each corresponding year).
# You will issue two plt.plot() commands to draw line plots of different colors on the same set of axes. Here, year represents the x-axis, while physical_sciences and computer_science are the y-axes.
year = np.array([1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980,
1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,
1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011])
physical_sciences = np.array([13.8, 14.9, 14.8, 16.5, 18.2, 19.1, 20. , 21.3, 22.5, 23.7, 24.6,
25.7, 27.3, 27.6, 28. , 27.5, 28.4, 30.4, 29.7, 31.3, 31.6, 32.6,
32.6, 33.6, 34.8, 35.9, 37.3, 38.3, 39.7, 40.2, 41. , 42.2, 41.1,
41.7, 42.1, 41.6, 40.8, 40.7, 40.7, 40.7, 40.2, 40.1])
computer_science = np.array([13.6, 13.6, 14.9, 16.4, 18.9, 19.8, 23.9, 25.7, 28.1, 30.2, 32.5,
34.8, 36.3, 37.1, 36.8, 35.7, 34.7, 32.4, 30.8, 29.9, 29.4, 28.7,
28.2, 28.5, 28.5, 27.5, 27.1, 26.8, 27. , 28.1, 27.7, 27.6, 27. ,
25.1, 22.2, 20.6, 18.6, 17.6, 17.8, 18.1, 17.6, 18.2])
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
# Plot in red the % of degrees awarded to women in Computer Science
plt.plot(year, computer_science, color='red')
# Display the plot
plt.show()
# It looks like, for the last 25 years or so, more women have been awarded undergraduate degrees in the Physical Sciences than in Computer Science.
# Using axes()
# Rather than overlaying line plots on common axes, you may prefer to plot different line plots on distinct axes. The command plt.axes() is one way to do this (but it requires specifying coordinates relative to the size of the figure).
# Here, you have the same three arrays year, physical_sciences, and computer_science representing percentages of degrees awarded to women over a range of years. You will use plt.axes() to create separate sets of axes in which you will draw each line plot.
# In calling plt.axes([xlo, ylo, width, height]), a set of axes is created and made active with lower corner at coordinates (xlo, ylo) of the specified width and height. Note that these coordinates can be passed to plt.axes() in the form of a list or a tuple.
# The coordinates and lengths are values between 0 and 1 representing lengths relative to the dimensions of the figure. After issuing a plt.axes() command, plots generated are put in that set of axes.
# Create plot axes for the first line plot
plt.axes([0.05, 0.05, 0.425, 0.9])
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
# Create plot axes for the second line plot
plt.axes([0.525, 0.05, 0.425, 0.9])
# Plot in red the % of degrees awarded to women in Computer Science
plt.plot(year, computer_science, color='red')
# Display the plot
plt.show()
# As you can see, not only are there now two separate plots with their own axes, but the axes for each plot are slightly different.
# Using subplot() (1)
# The command plt.axes() requires a lot of effort to use well because the coordinates of the axes need to be set manually. A better alternative is to use plt.subplot() to determine the layout automatically.
# In this exercise, you will continue working with the same arrays from the previous exercises: year, physical_sciences, and computer_science. Rather than using plt.axes() to explicitly lay out the axes, you will use plt.subplot(m, n, k) to make the subplot grid of dimensions m by n and to make the kth subplot active (subplots are numbered starting from 1 row-wise from the top left corner of the subplot grid).
# Create a figure with 1x2 subplot and make the left subplot active
plt.subplot(1,2,1)
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
plt.title('Physical Sciences')
# Make the right subplot active in the current 1x2 subplot grid
plt.subplot(1,2,2)
# Plot in red the % of degrees awarded to women in Computer Science
plt.plot(year, computer_science, color='red')
plt.title('Computer Science')
# Use plt.tight_layout() to improve the spacing between subplots
plt.tight_layout()
plt.show()
# Using subplot() (2)
# Now you have some familiarity with plt.subplot(), you can use it to plot more plots in larger grids of subplots of the same figure.
# Here, you will make a 2×2 grid of subplots and plot the percentage of degrees awarded to women in Physical Sciences (using physical_sciences), in Computer Science (using computer_science), in Health Professions (using health), and in Education (using education).
health = np.array([77.1, 75.5, 76.9, 77.4, 77.9, 78.9, 79.2, 80.5, 81.9, 82.3, 83.5,
84.1, 84.4, 84.6, 85.1, 85.3, 85.7, 85.5, 85.2, 84.6, 83.9, 83.5,
83. , 82.4, 81.8, 81.5, 81.3, 81.9, 82.1, 83.5, 83.5, 85.1, 85.8,
86.5, 86.5, 86. , 85.9, 85.4, 85.2, 85.1, 85. , 84.8])
education = np.array([74.53532758, 74.14920369, 73.55451996, 73.50181443, 73.33681143,
72.80185448, 72.16652471, 72.45639481, 73.19282134, 73.82114234,
74.98103152, 75.84512345, 75.84364914, 75.95060123, 75.86911601,
75.92343971, 76.14301516, 76.96309168, 77.62766177, 78.11191872,
78.86685859, 78.99124597, 78.43518191, 77.26731199, 75.81493264,
75.12525621, 75.03519921, 75.1637013 , 75.48616027, 75.83816206,
76.69214284, 77.37522931, 78.64424394, 78.54494815, 78.65074774,
79.06712173, 78.68630551, 78.72141311, 79.19632674, 79.5329087 ,
79.61862451, 79.43281184])
# Create a figure with 2x2 subplot layout and make the top left subplot active
plt.subplot(2,2,1)
# Plot in blue the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
plt.title('Physical Sciences')
# Make the top right subplot active in the current 2x2 subplot grid
plt.subplot(2,2,2)
# Plot in red the % of degrees awarded to women in Computer Science
plt.plot(year, computer_science, color='red')
plt.title('Computer Science')
# Make the bottom left subplot active in the current 2x2 subplot grid
plt.subplot(2,2,3)
# Plot in green the % of degrees awarded to women in Health Professions
plt.plot(year, health, color='green')
plt.title('Health Professions')
# Make the bottom right subplot active in the current 2x2 subplot grid
plt.subplot(2,2,4)
# Plot in yellow the % of degrees awarded to women in Education
plt.plot(year, education, color='yellow')
plt.title('Education')
# Improve the spacing between subplots and display them
plt.tight_layout()
plt.show()
# Controlling axis extents
# axis([xmin,xmax,ymin,ymax]) sets axis extents
# Control over individual axis extents
# xlim([xmin,xmax])
# ylim([ymin,ymax])
# Can use tuples, lists for extents
# e.g, lim((-2,3)) works
# Using xlim(), ylim()
# In this exercise, you will work with the matplotlib.pyplot interface to quickly set the x- and y-limits of your plots.
# You will now create the same figure as in the previous exercise using plt.plot(), this time setting the axis extents using plt.xlim() and plt.ylim(). These commands allow you to either zoom or expand the plot or to set the axis ranges to include important values (such as the origin).
# In this exercise, as before, the percentage of women graduates in Computer Science and in the Physical Sciences are held in the variables computer_science and physical_sciences respectively over year.
# After creating the plot, you will use plt.savefig() to export the image produced to a file.
# Plot the % of degrees awarded to women in Computer Science and the Physical Sciences
plt.plot(year,computer_science, color='red')
plt.plot(year, physical_sciences, color='blue')
# Add the axis labels
plt.xlabel('Year')
plt.ylabel('Degrees awarded to women (%)')
# Set the x-axis range
plt.xlim([1990,2010])
# Set the y-axis range
plt.ylim([0,50])
# Add a title and display the plot
plt.title('Degrees awarded to women (1990-2010)\nComputer Science (red)\nPhysical Sciences (blue)')
plt.show()
# Save the image as 'xlim_and_ylim.png'
plt.savefig('xlim_and_ylim.png')
# This plot effectively captures the difference in trends between 1990 and 2010.
# Using axis()
# Using plt.xlim() and plt.ylim() are useful for setting the axis limits individually. In this exercise, you will see how you can pass a 4-tuple to plt.axis() to set limits for both axes at once. For example, plt.axis((1980,1990,0,75)) would set the extent of the x-axis to the period between 1980 and 1990, and would set the y-axis extent from 0 to 75% degrees award.
# Once again, the percentage of women graduates in Computer Science and in the Physical Sciences are held in the variables computer_science and physical_sciences where each value was measured at the corresponding year held in the year variable.
# Plot in blue the % of degrees awarded to women in Computer Science
plt.plot(year,computer_science, color='blue')
# Plot in red the % of degrees awarded to women in the Physical Sciences
plt.plot(year, physical_sciences,color='red')
# Set the x-axis and y-axis limits
plt.axis((1990,2010,0,50))
# Show the figure
plt.show()
# Save the figure as 'axis_limits.png'
plt.savefig('axis_limits.png')
# Legends
# Provide labels for overlaid points and curves
# Using legend()
# Legends are useful for distinguishing between multiple datasets displayed on common axes. The relevant data are created using specific line colors or markers in various plot commands. Using the keyword argument label in the plotting function associates a string to use in a legend.
# For example, here, you will plot enrollment of women in the Physical Sciences and in Computer Science over time. You can label each curve by passing a label argument to the plotting call, and request a legend using plt.legend(). Specifying the keyword argument loc determines where the legend will be placed.
# Specify the label 'Computer Science'
plt.plot(year, computer_science, color='red', label='Computer Science')
# Specify the label 'Physical Sciences'
plt.plot(year, physical_sciences, color='blue', label='Physical Sciences')
# Add a legend at the lower center
plt.legend(loc='lower center')
# Add axis labels and title
plt.xlabel('Year')
plt.ylabel('Enrollment (%)')
plt.title('Undergraduate enrollment of women')
plt.show()
# Using annotate()
# It is often useful to annotate a simple plot to provide context. This makes the plot more readable and can highlight specific aspects of the data. Annotations like text and arrows can be used to emphasize specific observations.
# Here, you will once again plot enrollment of women in the Physical Sciences and Computer Science over time. The legend is set up as before. Additionally, you will mark the inflection point when enrollment of women in Computer Science reached a peak and started declining using plt.annotate().
# To enable an arrow, set arrowprops=dict(facecolor='black'). The arrow will point to the location given by xy and the text will appear at the location given by xytext.
# Computer Science enrollment and the years of enrollment have been preloaded for you as the arrays computer_science and year, respectively.
# Compute the maximum enrollment of women in Computer Science: cs_max
cs_max = computer_science.max()
# Calculate the year in which there was maximum enrollment of women in Computer Science: yr_max
yr_max = year[computer_science.argmax()]
# Plot with legend as before
plt.plot(year, computer_science, color='red', label='Computer Science')
plt.plot(year, physical_sciences, color='blue', label='Physical Sciences')
plt.legend(loc='lower right')
# Add a black arrow annotation
plt.annotate('Maximum', xy=(yr_max, cs_max), xytext=(yr_max+5, cs_max+5), arrowprops=dict(facecolor='black'))
# Add axis labels and title
plt.xlabel('Year')
plt.ylabel('Enrollment (%)')
plt.title('Undergraduate enrollment of women')
plt.show()
# Annotations are extremely useful to help make more complicated plots easier to understand.
# Modifying styles
# Matplotlib comes with a number of different stylesheets to customize the overall look of different plots. To activate a particular stylesheet you can simply call plt.style.use() with the name of the style sheet you want. To list all the available style sheets you can execute: print(plt.style.available)
# Import matplotlib.pyplot
import matplotlib.pyplot as plt
# Set the style to 'ggplot'
plt.style.use('ggplot')
# Create a figure with 2x2 subplot layout
plt.subplot(2, 2, 1)
# Plot the enrollment % of women in the Physical Sciences
plt.plot(year, physical_sciences, color='blue')
plt.title('Physical Sciences')
# Plot the enrollment % of women in Computer Science
plt.subplot(2, 2, 2)
plt.plot(year, computer_science, color='red')
plt.title('Computer Science')
# Add annotation
cs_max = computer_science.max()
yr_max = year[computer_science.argmax()]
plt.annotate('Maximum', xy=(yr_max, cs_max), xytext=(yr_max-1, cs_max-10), arrowprops=dict(facecolor='black'))
# Plot the enrollmment % of women in Health professions
plt.subplot(2, 2, 3)
plt.plot(year, health, color='green')
plt.title('Health Professions')
# Plot the enrollment % of women in Education
plt.subplot(2, 2, 4)
plt.plot(year, education, color='yellow')
plt.title('Education')
# Improve spacing between subplots and display them
plt.tight_layout()
plt.show() |
35d68446f3381fd3b992b17f2f24c83ed42efc37 | jasonzhouu/abroadWatcher | /recursionFile.py | 647 | 4.1875 | 4 | """
function: 遍历目录,返回目录结构的 list
"""
import os
def scanpath(filepath, suffix):
file_list = []
print("开始扫描【{0}】".format(filepath))
if not os.path.isdir(filepath):
print("【{0}】不是目录".format(filepath))
exit(-1)
for filename in os.listdir(filepath):
if os.path.isdir(filepath + "/" + filename):
file_list.extend(scanpath(filepath + "/" + filename, suffix))
elif filename.endswith(suffix):
sub_filename = filepath + '/' + filename
file_list.append(sub_filename)
print(sub_filename)
return file_list
|
84e76b0b8e68562146cbf249b987a926021284c7 | anup5889/PythonWork | /find.py | 499 | 3.578125 | 4 | #!/usr/bin/env python
import sys
import re
import os
#get the start directory
start= sys.argv[1]
#Get the patterns from the command line arguments
pattern=sys.argv[2]
#convert them to regular expressions
expr=re.compile(pattern)
#traverse the directories for all the files
for root, dirs, files in os.walk(start):
for fname in files:
if fname in files:
if expr.match(fname):
print os.path.join(root, fname)
#print root+"/"+fname
#if a file matches the pattern, print its name
|
16595566b67e412a5e3cf6db639b48d890614631 | abhisheks-12/hackerrank-python | /08_finding_percentage.py | 372 | 3.78125 | 4 | n = int(input("Enter the num: "))
my_score = {}
for i in range(n):
name , *line = input("Name: ").split()
# print(name)
# print(line)
score = list(map(float,line))
my_score[name] = score
query_name = input("enter the: ")
a = my_score[query_name]
sum = 0
for i in a:
sum = sum +i
b = sum/3
print(format(b,".2f"))
|
63fae238b252465120d0a48e6230b1115ce01eeb | HoeYeon/Algorithm | /Python_Algorithm/Baek/11772.py | 128 | 3.703125 | 4 | result = 0
for i in range(int(input())):
num = input()
a,b = int(num[:-1]),int(num[-1])
result += a**b
print(result) |
9b832339975f2532bac9e001bcdb31d38fede4c3 | mmmdip/LinearEquationSolver | /linearEqationSolver.py | 1,844 | 3.734375 | 4 | def takeInput():
firstEqu = input( "Enter 1st equation: ")
secondEqu = input( "Enter 2nd equation: ")
return [ firstEqu, secondEqu ]
def extractCoef( equation ):
str = equation.split( '+' )
a = float( str[ 0 ].split( 'x' )[ 0 ] )
b = float( str[ 1 ].split( 'y' )[ 0 ] )
c = float( str[ 1 ].split( '=' )[ 1 ] )
return [ a, b, c ]
def calculateDeterminant( coef1, coef2 ):
determinant = coef1[ 0 ] * coef2[ 1 ] - coef2[ 0 ] * coef1[ 1 ]
return determinant
def calculateX( det, coef1, coef2 ):
dx = coef1[ 2 ] * coef2[ 1 ] - coef2[ 2 ] * coef1[ 1 ]
return dx / det
def calculateY( det, coef1, coef2 ):
dy = coef1[ 0 ] * coef2[ 2 ] - coef2[ 0 ] * coef1[ 2 ]
return dy / det
def plotSolution( solX, solY, coef1, coef2 ):
import matplotlib
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
x1 = list( range( -2 * 5, 2 * 5 + 1 ))
y1 = []
for x in x1:
y1.append(( coef1[ 2 ] - coef1[ 0 ] * x ) / coef1[ 1 ] )
ax.plot( x1, y1, color = "g", label = "Line 1" )
x2 = list( range( -2 * 5, 2 * 5 + 1 ))
y2 = []
for x in x2:
y2.append(( coef2[ 2 ] - coef2[ 0 ] * x ) / coef2[ 1 ] )
ax.plot( x2, y2, color = "b", label = "Line 2" )
plt.title( "Solving systems of equations" )
solution = [ solX, solY ]
circle = plt.Circle( solution, radius = 0.25 , color = 'r' )
ax.add_artist( circle )
ax.legend()
plt.show()
def main():
#equList = takeInput()
equList = [ '1x + -1y = 0', '1x + 1y = 1' ]
coef1 = extractCoef( equList[ 0 ])
coef2 = extractCoef( equList[ 1 ])
d = calculateDeterminant( coef1, coef2 )
print( d )
x = calculateX( d, coef1, coef2 )
y = calculateY( d, coef1, coef2 )
print( "Solution: X= ", x, "Y= ", y )
plotSolution( x, y, coef1, coef2 )
main()
|
7a396c5e5b2459177d9f66a736c1954546e7d3da | felileivas/caja-fuerte | /cajafuerte.py | 1,136 | 3.578125 | 4 | from random import randrange
intentos = 7
vidas = 2
bomba_1 = randrange(0, 9)
bomba_2 = randrange(0, 9)
casillas = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if bomba_1 == bomba_2:
bomba_2 = randrange(0, 9)
array = []
for i in range(9):
array.append(0)
array[bomba_1] = 'bomba'
array[bomba_2] = 'bomba'
# print(array)
print('-' * 60)
print(casillas)
for element in array:
print('-' * 60)
x = int(input('Selecciona la casilla: ')) - 1
while x > 8 or x < 0:
print('Casilla no valida')
x = int(input('Selecciona la casilla: ')) - 1
while casillas[x] == 'X':
print('Casilla ya seleccionada, pida otra')
x = int(input('Selecciona la casilla: ')) - 1
casillas[x] = 'X'
intentos = intentos - 1
if array[x] == 'bomba':
array[x] = 1
vidas = vidas - 1
intentos = intentos + 1
print('Te salio una bomba')
if array[x] == 0:
array[x] = 1
if vidas == 0:
print('Perdiste')
break
if intentos == 0:
print('Ganaste!!!!')
break
print('-' * 60)
print('Cantidad de vidas: ', vidas)
print(casillas) |
f2063b1344a2d7cdc5370787fea4313c581b6a6f | leizhi90/python | /base_python/day10/work.py | 2,814 | 4.21875 | 4 | # -*- conding:utf-8 -*-
# 编写三个类,矩形与正方形两个类,求周长与面积。分别使用不继承与继承两种方式,并总结出继承的优势。
class Rectangle:
def __init__(self,length,high):
self.length=length
self.high=high
def perimeter(self):
return 2*(self.length + self.high)
def area(self):
return self.length*self.high
class Square:
def __init__(self,length):
self.length=length
def perimeter(self):
return 3*self.length
def area(self):
return self.length*self.length
class Squares(Rectangle):
def __init__(self,length):
self.length=length
super().__init__(length,length)
r=Rectangle(3,4)
print(r.perimeter())
print(r.area())
ss=Squares(5)
print(ss.perimeter())
print(ss.area())
# 编写一个分页显示类,构造器传入记录总数。可以设置每页记录数与页码,
# 能够返回当前页显示的记录区间。如果页码不正确,则将页码恢复成1,并显示错误提示信息。每页记录数与页码使用property实现。
class Paging:
def __init__(self,total):
self.total=total
self.__every_page=10
self.__now_page=1
@property
def every_page(self):
return self.__every_page
@every_page.setter
def every_page(self,p):
self.__every_page=p
@every_page.deleter
def every_page(self):
del self.__every_page
@property
def now_page(self):
return self.__now_page
@now_page.setter
def now_page(self,p):
self.now_page=p
# 编写电脑类,提供一个方法,能够与移动设备(U盘,MP3,移动硬盘)进行读写交互。如果参数类型不是移动设备的类型,则打印错误信息。MP3除了读与写之外,还额外具有一个播放音乐的功能。
class Movie:
def read(self):
print('read fun')
class Computer:
def __init__(self,m):
self.move=m
def judge(self):
if isinstance(self.move,Movie):
pass
else:
print('is not movie type!')
class U(Movie):
pass
class MP3(Movie):
def music(self):
print('music on.......')
class Disk(Movie):
pass
# 编写如下的继承结构,类C继承(A,B),类D继承(B,A),类E继承(C,D)或者(D,C),会出现什么情况?
class A:
pass
class B:
pass
class C(A,B):
pass
class D(B,A):
pass
# class E(C,D):
# pass
# 实现矩阵的转置。(zip)
li=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
#print ([[i for i in enumerate(item) ] for item in li])
print(*li)
print (list(map(list,zip(*li))))
age=[1,2]
name=['a','b']
print(li)
print(list(zip(name,age)))
# 使用sorted函数实现reverse的功能。但是顺序不改变。
li=[3,1,5,9]
def ord(i):
pass
print(sorted(li,reverse=True))
print(li)
print(*li) |
2c3e73d7351bca34aee3094bb6804e00f51c7992 | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/vjha21/Day12/question2.py | 593 | 4.125 | 4 | """Count number of substrings that start and end with 1
if there is no such combination print 0
"""
def generate_substrings(string):
sub_strings = [
string[i:j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)
]
return sub_strings
def count_substrings(sub_string):
count = 0
for element in sub_string:
if element[0] == "1" and element[-1] == "1":
count += 1
return count
if __name__ == "__main__":
string = "1111"
print(generate_substrings(string))
print(count_substrings(generate_substrings(string))) |
f0a8058d796caeafb8973a552fc997b759af1e71 | djanshuman/Code-Docs | /Python/PracticeQuestion/best_Internet_Browser.py | 2,809 | 3.9375 | 4 | '''In the race for the best Internet browser, there's now a new contender for it, this browser is called the: "The Semantic Mind-Reader!" After its promo on the world wide web, everyone's been desperately waiting for the browser to be released. And why shouldn't they be curious about it, after all, it's the new project of our very own genius "Little Jhool!" He's worked very hard for this browser, and to add new mind reading features to it.
Apart from the various security powers it possesses, it's called the mind-reader for a reason. Here's why:
You don't need to type 'www.' to open a website anymore.
Though, you still need to type '.com' to open a website.
The browser predicts ALL THE VOWELS in the name of the website. (Not '.com', though. Again!)
Obviously, this means you can type the name of a website faster and save some time.
Now to convince users that his browser will indeed save A LOT of time for users to open a particular website, Little Jhool has asked you to prepare a report on the same.
Input format:
The first line contains tc, the number of test cases.
The second line contains the name of websites, as a string.
Output format:
You have to print the ratio of characters you would have typed in Jhool's browser, to your normal browser.
Constraints:
1 <= tc <= 100
1 <= Length of the website <= 200
NOTE: You do NOT need to print the output in its lowest format. You should print in its original fraction format.
The names of all the websites will be in small case only.
Every string will start from *www. and end with *.com, so well!**
SAMPLE INPUT
2
www.google.com
www.hackerearth.com
SAMPLE OUTPUT
7/14
11/19
Explanation
Consider the first case:
In Jhool's browser, you'll only have to type: ggl.com (7 characters) while in a normal browser, you'll have to type www.google.com, which is 14 characters.'''
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
count=int(input())
x=0
while(x<count):
x+=1
name=input()
list1=name.split('.')
str1=''
for i in list1:
if i.lower() in ('www','com'):
continue
else:
for j in i:
if j not in ('a','e','i','o','u'):
str1+=j
print(str(len(str1+'.'+list1[-1]))+'/'+str(len(name)))
'''Result
RESULT: Sample Test Cases Passed
Time (sec)
0.108773
Memory (KiB)
64
Language
Python 3
Input
2
www.google.com
www.hackerearth.com
Your Code's Output
7/14
11/19
Expected Correct Output
7/14
11/19
Compilation Log
Compiled successfully.
Execution Log
No execution log!
'''
|
1e31ab1ec50441f83a53d1a207a2008027fd2756 | joshianshul2/Python | /leapyr.py | 204 | 4.03125 | 4 | a=int(input("Enter a year for checking leap or not "))
if a%400==0 :
print("Leap Year ")
elif a%100==0:
print("Non Leap Year")
elif a%4==0 :
print("Leap Year ")
else:
print("Non Leap Year ")
|
1cbe6a0e2329454fd10cf19a8db784f0edac6422 | boyuan618/cp2019 | /Template_functions/binarysearchrecursive.py | 527 | 3.984375 | 4 | def binarySearch(arr, left, right, target):
print("Running in process")
if right >= 1:
size = len(arr)
mid = int(size/2) + 1
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binarySearch(arr, left, mid-1, target)
else:
return binarySearch(arr, mid+1, right, target)
else:
return -1
arr = [1, 234, 433, 4565, 7565]
print(binarySearch(arr, 0, len(arr)-1, 4565)) |
c5bb8afd38bc2daf5b152d8963c144948d20a33c | anshuljdhingra/Machine-Learning | /Deep-Learning/CNN.py | 2,199 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 29 22:01:44 2017
@author: adhingra
"""
# Convolution Neural Network
# importing keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# initlaising the CNN
classifier = Sequential()
# adding convoluton layer
classifier.add(Convolution2D(32,(3,3), input_shape = (64,64,3), activation= 'relu'))
# adding max pooling layer
classifier.add(MaxPooling2D(pool_size= (2,2) ))
# adding a second convolutional and pooling layer
classifier.add(Convolution2D(32,(3,3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2)))
# flatttening the pooled feature maps
classifier.add(Flatten())
# adding fully connected layer
classifier.add(Dense(output_dim = 128, activation= 'relu'))
# adding output layer
classifier.add(Dense(units= 1, activation= 'sigmoid'))
# compiling the CNN
classifier.compile(optimizer= 'adam', loss= 'binary_crossentropy', metrics= ['accuracy'])
# fitting the CNN model to the dataset
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory('dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory('dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
classifier.fit_generator(training_set,
steps_per_epoch=8000,
epochs=20,
validation_data=test_set,
nb_val_samples=2000)
|
4e5cc2fdbcaa14965fc666db6e94734646623f1b | Blyznyuk/HomeWork3 | /ex3.py | 556 | 3.515625 | 4 | a = 0
while a < 11:
print(a)
a += 1
b = 20
while b > 0:
print(b, end=' ')
b -= 1
s = []
c = 20
print(sep='\n')
while c > 0:
s.append(c)
c -= 1
print(s)
while True:
d = int(input("Введите четное число: "))
if d % 2 != 0 :
print("Введено нечетное число. Повторите ввод")
else:
e = 0
while d//2:
e += 1
if (d//2) % 2 == 0:
d = d//2
else:
break
print(e)
break
|
dc21fdbefa1264fd67aecf4514bd8ae241e5c0e6 | henrizhang/password-checker | /pwchecker.py | 891 | 3.734375 | 4 | def meetsThreshold(p):
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "1234567890"
return True in [x in lower for x in p] and True in [x in upper for x in p] and True in [x in digits for x in p]
def strength(p):
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "1234567890"
other = ".?!&#,;:-_*"
stregnth=0
hasLower=0
hasUpper=0
hasSpecial=0
hasDigit=0
if len([x in lower for x in p])>0:
hasLower=1
if len([x in upper for x in p])>0:
hasUpper=1
if len([x in other for x in p])>0:
hasSpecial=1
if len([x in digits for x in p])>0:
hasDigit=1
return (hasLower+hasUpper+hasSpecial+hasDigit)*len(p)
print meetsThreshold("skrrrt")
print meetsThreshold("skrtS1")
print strength("skrtS1")
print strength("skr!.?t1212312S1") |
67e8f04bd54cbeb03cd7d9531a89f92bb657d09b | MeetLuck/works | /console/cursestutorial/hello4.1.py | 1,063 | 3.5 | 4 | import curses, time
''' more text animation
>>> stdscr = curses.initscr()
>>> dims = stdscr.getmaxyx() 'return a tuple (height,width) of the window'
row = 0,1,2,...,24 -> max_height = dims[0]-1, max_width = dims[1]-1
col = 0,1,2,...,79
>>> stdscr.addstr(row,col,'text',curse.A_REVERSE)
>>> stdscr.nodelay(1) 'If yes is 1, getch() will be non-blocking.'
'''
stdscr = curses.initscr()
stdscr.nodelay(1)
dims = stdscr.getmaxyx()
#dims = stdscr.getmaxyx()
#height = dims[0]-1, width = dims[1]-1
height,width = dims[0]-1, dims[1]-1
text = 'Hello World!'
row,col = 0,0
horizontal,vertical = +1,+1 # + : go down, right - : go up, left
q = -1
while q < 0:
stdscr.clear()
stdscr.addstr(row,col,text)
stdscr.refresh()
row += vertical
col += horizontal
# row += 1
# col += 1
if row == height:
vertical = -1
elif row == 0:
vertical = +1
if col == width-len(text):
horizontal = -1
elif col == 0:
horizontal = +1
q = stdscr.getch()
time.sleep(0.05)
stdscr.getch()
curses.endwin()
|
6caee82f49a700de88febd16a1e7137a350584fc | philg09/Microsoft-Learn | /python-if-elif-else/python-if/exercise2.py | 439 | 3.921875 | 4 | first_number = 5
second_number = 0
true_value = True
false_value = False
if first_number > 1 and first_number < 10:
print('The value is between 1 and 10.')
if first_number > 1 or second_number > 1:
print('At least one value is greater than 1')
print(not true_value)
print(not false_value)
if not first_number > 1 and second_number < 10:
print('Both values pass the test')
else:
print('Both values do NOT pass the test') |
994b03cb0848e9eaea729e278d132bafa235c288 | NathalieRaob/OOP | /bankAccount.py | 2,535 | 3.9375 | 4 | class BankAccount:
def __init__(self,int_rate, balance, b_type):
self.int_rate = int_rate
self.balance = balance
self.type = b_type
def deposit(self, amount):
#increases the account balance by the given amount
self.balance += amount
return self
def withdraw(self, amount):
#decreases the account balance by the given amount if there are sufficient funds
#if there is not enough money, print a message "insufficient funds: Charging a $5 fee" and deduct $5
if self.balance > amount:
self.balance -= amount
else:
self.balance -= 5
print("Insufficient funds: Charging a $5 fee")
return self
def display_account_info(self):
print(f"Current balance in {self.type}: ${self.balance}")
return self
def yield_interest(self):
#increases the account balance by the current balance * the interest rate(as long as the balance is positive)
if self.balance > 0:
self.balance = self.balance + self.balance * self.int_rate
return self
# first_account = BankAccount()
# first_account.deposit(100).deposit(100).deposit(100).withdraw(200).yield_interest().display_account_info()
# second_account = BankAccount()
# second_account.deposit(40000).deposit(800).withdraw(500).withdraw(400).withdraw(300).withdraw(900).yield_interest().display_account_info()
#SOLUTION
# class BankAccount:
# def __init__(self, int_rate=0, balance=0):
# self.int_rate = int_rate
# self.balance = balance
# def deposit(self, amount):
# self.balance += amount
# return self
# def withdraw(self, amount):
# if self.balance >= amount:
# self.balance -= amount
# else:
# self.balance -= 5
# print("Insufficient Funds: Charging a $5 fee")
# return self
# def display_account_info(self):
# print(f"Balance: ${self.balance}")
# return self
# def yield_interest(self):
# if self.balance > 0:
# self.balance = self.balance + self.balance * self.int_rate
# print(f"Rate:{self.int_rate}")
# return self
# ba1 = BankAccount(balance=100)
# ba2 = BankAccount(.01, 500)
# ba1.deposit(500).deposit(3000).deposit(700).withdraw(600).yield_interest().display_account_info()
# ba2.deposit(100).deposit(100).withdraw(100).withdraw(50).withdraw(50).withdraw(50).yield_interest().display_account_info() |
0fb2f32b080cc03055bb1d6dc9e386497e310e19 | rinkanrohitjena/python_training | /esecond_exer.py | 235 | 4 | 4 |
sentence = input("enter your string >>")
letter = input("enter your letteer>>")
count = 0
countlist = [x for x in sentence]
for x in countlist:
if x == letter:
count = count+1
print("the number of time appeared ", count)
|
61fca39e364cc3693c8616220f25075984a6c1e9 | hongwei1/LearnPython | /CarptourDe/test.py | 139 | 3.671875 | 4 | def hasNumbers(inputString): return any(char.isdigit() for char in inputString)
print(hasNumbers("hognog"))
print(hasNumbers("hognog 32")) |
0b0e6b1602d50a76a9ce0e04ffd7404913b96ae0 | ferrin22/CTCI | /1-7.py | 870 | 3.71875 | 4 | #If an element in an MxN matrix is zero, its entire column and row get set to zero
#Loop to find 0's in matrix, store them. For corresponding rows, cols, loop to insert 0's
# O(mn) complexity, O(n) space(worst case all 0's)
def zero(matx, M, N):
table = []
for x in range(0, M):
for y in range(0, N):
if matx[x][y] == 0:
table.append((x,y))
for pair in table:
for i in range(0, N):
matx[pair[0]][i] = 0
for j in range(0, M):
matx[j][pair[1]] = 0
return matx
mtx = [[0 for x in range(2)] for y in range(2)]
mtx[0][0] = 1
mtx[0][1] = 0
mtx[1][0] = 3
mtx[1][1] = 4
print mtx
print zero(mtx, 2, 2)
big = [[0 for x in range(3)] for y in range(4)]
big[0][0] = 1
big[0][1] = 2
big[0][2] = 3
big[1][0] = 4
big[1][1] = 5
big[1][2] = 6
big[2][0] = 0
big[2][1] = 8
big[2][2] = 9
big[3][0] = 0
big[3][1] = 10
big[3][2] = 11
print big
print zero(big, 4, 3) |
d41edacfe448d7904a3edd42c0289891d9e01f96 | Sarthak-Singhania/Work | /Class 12/infix to postfix.py | 851 | 3.6875 | 4 | infix='(a+b)*(c+('
l=[x for x in infix]
precedence={'**':3,'*':2,'/':2,'%':2,'+':1,'-':1}
brackets=['(',')']
operation=[]
postfix=''
for i in l:
if i in precedence or i in brackets:
if len(operation)==0:
operation.append(i)
print(operation)
elif i=='(':
operation.append(i)
print(operation)
elif precedence[i]>precedence[operation[-1]] or operation[-1]=='(':
operation.append(i)
print(operation)
elif precedence[i]<=precedence[operation[-1]]:
postfix+=operation.pop()
operation.append(i)
print(operation)
elif i==')':
if operation[-1]!='(':
postfix+=operation.pop()
else:
postfix+=i
for _ in range(len(operation)):
postfix+=operation.pop()
print(postfix)
|
39768bddc0ab7883cf171afa960d9e0d7ae24858 | naglepuff/SudokuSolver | /SudokuGameTests.py | 2,554 | 3.90625 | 4 | """
This is a script to test some of the methods in the SudokuGame class.
Important things to test are is_valid and is_complete.
"""
from SudokuGame import SudokuGame
"""
Helper function to make test cases easy to construct.
"""
def make_grid(val = 0):
return [[val] * 9] * 9
"""
Test the is_valid function of the Sudoku game class.
"""
def test_is_valid(messages):
# case 1: test two values in same row
testGrid = make_grid()
testGrid[0][0] = 5
testGrid[0][5] = 5
game = SudokuGame("", testGrid)
if game.is_valid():
messages = messages + [["is_valid: two equal values in the same row should be invalid."]]
# case 2: test two values in same column
testGrid = make_grid()
testGrid[0][0] = 5
testGrid[5][0] = 5
game = SudokuGame("", testGrid)
if game.is_valid():
messages = messages + [["is_valid: two equal values in the same row should be invalid."]]
# case 3: two values in same subgrid
# here we test multiple subgrids to make sure our index calculations are correct
testGrid = make_grid()
testGrid[3][3] = 5
testGrid[4][4] = 5
game1 = SudokuGame("", testGrid)
game1Valid = game1.is_valid()
testGrid[3][3] = 0
testGrid[4][4] = 0
testGrid[7][7] = 5
testGrid[8][8] = 5
game2 = SudokuGame("", testGrid)
game2Valid = game2.is_valid()
if game1Valid or game2Valid:
messages = messages + ["is_valid: two equal values in the same subgrid should be invalid."]
"""
Test the is_complete function of the Sudoku game class.
"""
def test_is_complete(messages):
# case 1: empty grid
testGrid = make_grid()
game = SudokuGame("", testGrid)
if game.is_complete():
messages = messages + ["is_complete: an empty sudoku grid is not complete"]
# case 2: full grid
testGrid = make_grid(5)
game = SudokuGame("", testGrid)
if not game.is_complete():
messages = messages + ["is_complete: an complete sudoku grid is not incomplete"]
# case 3: single empty square
testGrid = make_grid(5)
testGrid[8][8] = 0
game = SudokuGame("", testGrid)
if game.is_complete():
messages = messages + ["is_complete: a sudoku grid with an empty cell is not complete"]
"""
Run the tests, keep track of error messages in a list.
"""
def main():
errors = []
test_is_valid(errors)
test_is_complete(errors)
if len(errors) == 0:
print("All tests passed.")
else:
for error in errors:
print(error)
if __name__ == "__main__":
main() |
3ce38c93c09a374476569434f1ce8929096da740 | a-shah8/LeetCode | /Medium/threeSum.py | 929 | 3.5 | 4 | ## Two pointer approach
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = []
nums.sort()
for i in range(len(nums)):
if i != 0 and nums[i] == nums[i-1]: continue
lo, hi = i+1, len(nums)-1
while lo<hi:
total = nums[i] + nums[lo] + nums[hi]
if total == 0:
result.append([nums[i], nums[lo], nums[hi]])
while lo<hi and nums[lo]==nums[lo+1]:
lo += 1
while lo<hi and nums[hi]==nums[hi-1]:
hi -= 1
lo += 1
hi -= 1
elif total < 0:
lo += 1
else:
hi -= 1
return result
|
8856bbc6efc707314ad269829ffa44af9e49a13f | aryabiju37/Python-mini-Proects | /oop/animals.py | 569 | 4.21875 | 4 | class Animal:
cool = True
def __init__(self,name,species):
self.name = name
self.species = species
def make_sound(self,sound):
print(f"this animal makes {sound}")
class Cat(Animal):
def __init__(self,name,species,breed,toy):
# self.name = name
# self.species = species ---code repetition
#Animal.__init__(self,name,species) -- same thing accomplished by super
super().__init__(name,species="Cat")
self.breed = breed
self.toy = toy
blue = Cat("Blue","Persian","Laser light") |
6708e15744d7c18e3d167d40ddb202afb7705460 | ekjellman/interview_practice | /epi/10_12.py | 1,660 | 4.28125 | 4 | ###
# Problem
###
# Make a linked list from the leaves of a binary tree. The leaves
# should appear in left-to-right order
###
# Work
###
# Questions:
# Size of the tree, use cases, etc
# What are we looking at for the return type here? A linked list
# where the values are tree nodes? (Assume yes)
from linked_list import ListNode
def leaves_list(node):
head = ListNode(0)
ll_helper(node, head)
return head.next_node
def ll_helper(node, tail):
if not node.left and not node.right:
new_node = ListNode(node)
tail.next_node = new_node
return new_node
else:
if node.left:
tail = ll_helper(node.left, tail)
if node.right:
tail = ll_helper(node.right, tail)
return tail
# Test:
from binary_tree import BinaryTree
a = BinaryTree("A")
b = BinaryTree("B")
c = BinaryTree("C")
d = BinaryTree("D")
e = BinaryTree("E")
f = BinaryTree("F")
g = BinaryTree("G")
h = BinaryTree("H")
i = BinaryTree("I")
a.left = b
a.right = c
b.left = d
b.right = e
e.left = h
c.left = f
c.right = g
g.right = i
ll = leaves_list(a)
current = ll
while current:
print current.value.value
current = current.next_node
# Time:
###
# Mistakes / Bugs / Misses
###
# I need to think about what an actual, useful LinkedList data
# structure looks like when I'm doing these problems. For example,
# here I had to have the helper return the tail, because I
# was dealing with the structure I created for linked list problems.
# But in reality, and in an interview, a problem like this that
# is focusing in the binary tree won't care if I use a real
# linked list implementation like collections.deque. So do that.
# TODO: make a card, somehow?
|
217feda61232d035767a36cb015feadb6803da15 | nsachs/ch00-Variables-nsachs | /Notes3.py | 4,245 | 4.34375 | 4 | # --------- February 23 --------
#Insertion Sort
#iterate through the list starting at 1 through the end of list
# we are splitting our list into two parts, sorted items on the left, unsorted on the right.
#1 We iterate to the next number to sort
#2 we store the value and pos
#3 we compare val to val of pos to the immediate left.
#4 If it is bigger, we found the place for this item. If it is smaller, we swap out the scanning position with the one to its immediate left and move
#the scan position down one to check the next item. This repeats until we find the place it belongs.
#5 Then we put the original value in that place, and start over with the next pos.
#import random
'''
my_list = []
for i in range(5000000):
my_list.append(random.randrange(100000))
for pos in range(1,len(my_list)):
key_pos = pos
scan_pos = key_pos - 1
key_val = my_list[key_pos]
while my_list[scan_pos] > key_val and key_pos >= 0:
my_list[scan_pos + 1] = my_list[scan_pos]
scan_pos -= 1
my_list[scan_pos + 1] = key_val
print(my_list)
import turtle
my_turtle = turtle.Turtle()
my_turtle.isvisible()
my_screen = turtle.Screen()
#Draw Here
my_turtle.fillcolor("red")
my_turtle.begin_fill()
my_turtle.goto(200, 0)
my_turtle.goto(200, 200)
my_turtle.goto(0, 200)
my_turtle.goto(0,0)
my_screen.bgcolor("blue")
my_turtle.end_fill()
my_turtle.width(10)
my_turtle.up()
my_turtle.goto(-100, -100)
my_turtle.down()
my_turtle.setheading(135)
my_turtle.forward(100)
#my_turtle.begin_fill()
curl = 0.1
heading = 0
for i in range(50):
my_turtle.setheading(heading)
curl += 0.1
heading += curl
my_turtle.forward(5)
#my_turtle.end_fill()
my_screen.exitonclick()
'''
#EXCEPTIONS (use me sparingly please)
#Exception = condition that resuls in abnormal program flow
#Exception handling = what we actively do to for exceptions
#Catch = code that handles abnormal conditions
#Throw/raise = adnormal conditions THROW or RAISE Exceptions
#Unhandled exceptions = Thrown, but not caught. Program killers
#Common exception handling we might do:
#Divide by zeri error (ZeroDivisionError)
'''
x = 0
y = 2
try:
print(y/x)
except:
print("Invalid Operation")
#Conversion Error (ValueError)
done = False
while not done:
try:
user_input = int(input("Enter a valid number: "))
done = True
except:
print("Number entered was not valid.")
#File opening (IOError, FileNotFoundError)
try:
file = open("AliceInWonderland.txt")
except:
print("Couldn't open files")
#Use the built in error types
try:
my_file = open("myfile.txt")
int("Hello")
print(1/0)
except FileNotFoundError:
print("File not found")
except ZeroDivisionError:
print("You cannot divide by zero")
except ValueError:
print("Invalid integer conversion")
except:
print("Unknown Error")
#Exception object (grabbing the caight exception object)
try:
print(1/0)
except ZeroDivisionError as e:
print(e)
'''
#RECURSION NOTES
#functions can call functions
def f():
g()
print("f")
def g():
print("g")
f()
#functions can call themselves
def hello():
print("Hello")
#hello()
hello()
#control the level of recursion (depth)
def controlled(level, end_level):
print("Recursion level", level)
if level < end_level:
controlled(level + 1, end_level)
controlled(4,20)
#make a function to calculate a factorial
def factorial(n):
total = 1
for i in range(2, n +1):
total *= i
return total
print(factorial(10))
def recursive_factorial(n):
if(n == 1):
return n
else:
return n * recursive_factorial(n-1)
print(recursive_factorial(10))
#Zombie Apocalypse Problem
def zombie_apocalypse(zombies, humans, attacks_per_day, defense_rate, day, end_day):
print("DAY: ", day)
print("Humans = ", humans)
print("Zombies = ", zombies)
new_zombies = zombies + zombies * attacks_per_day * (1-defense_rate) - zombies * attacks_per_day * defense_rate
humans = humans - new_zombies
day += 1
if humans > 0 and zombies > 0 and day < end_day:
zombie_apocalypse(new_zombies, humans, attacks_per_day, defense_rate, day, end_day)
zombie_apocalypse(100, 6e9, 1, 0.1, 0, 100)
|
0cc430d7621bfaae1f6b6a655566642dd758c4bf | grecoe/teals | /4_advanced/modules/userinput.py | 2,085 | 4 | 4 | '''
This file allows you to hide all of the implementation details of asking
a user for input for your program. It will verify that the correct data is
returned.
Externally, we want to expose the getUserInput().
'''
'''
__parseInt
Parameters
userInput : Input string from user
error : Error to display if not a int
Returns:
Int if non error, None otherwise
'''
def __parseInt(userInput, error):
returnVal = None
try:
returnVal = int(userInput)
except Exception as ex:
returnVal = None
print(error)
return returnVal
'''
__parseFloat
Parameters
userInput : Input string from user
error : Error to display if not a float
Returns:
Float if non error, None otherwise
'''
def __parseFloat(userInput, error):
returnVal = None
try:
returnVal = float(userInput)
except Exception as ex:
returnVal = None
print(error)
return returnVal
'''
getUserInput:
Parameters:
prompt : Prompt to show to the user
error: Error to show to the user if expected type not input.
classInfo: Class info of type to collect
retries: Number of times to allow user to get it right.
Returns:
Expected value type if retries isn't exceeded
'''
def getUserInput(prompt, retries, error, classInfo):
userValue = None
className = classInfo.__name__
currentRetries = 0
while True:
currentRetries += 1
userInput = input(prompt)
if className == 'int':
userValue = __parseInt(userInput, error)
elif className == 'float':
userValue = __parseFloat(userInput, error)
else:
userValue = userInput
# If we have a value, get out
if userValue is not None:
break
# If we've exhausted our retries, get out.
if currentRetries >= retries:
print("You have exhausted your attempts to enter a ", className)
break
return userValue
|
18577e36bc47368728bab4ba6cbe54d3598912b5 | Ray-SunR/leetcode | /148. Sort List/solution.py | 924 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
d = {}
s = head
v = set()
while s:
if s.val not in d:
d[s.val] = []
t = s.next
d[s.val].append(s)
v.add(s.val)
s.next = None
s = t
v = sorted(v)
head = None
prev = None
# print(d)
for key in v:
if not head:
head = d[key][0]
else:
prev.next = d[key][0]
i = 1
n = d[key][0]
while i < len(d[key]):
n.next = d[key][i]
n = d[key][i]
i += 1
prev = n
return head
|
63853be5a0e797c922c292b4abe5821af7169425 | aniketshelke123/hello-world.io | /cp_sp.py | 242 | 3.90625 | 4 | cp=int(input("enter the cost price\n"))
sp=int(input("enter the selling price\n"))
if(cp>sp):
print("loss ")
loss=cp-sp
print("loss is",loss)
else:
print("profit")
profit=sp-cp
print("profit is ",profit)
|
be00bccbb319e25de5685b8907a3abce2f051cea | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/4bd1396def954a5c94ed894b29305582.py | 1,178 | 3.84375 | 4 | from datetime import date, timedelta
def meetup_day(year, month, weekday, flags):
meetup_date = date(year, month, 1)
weekdays = dict(zip('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(), range(7)))
if flags.endswith("teenth"):
teens_start = 11
teens_end = 20
meetup_date += timedelta(days = teens_start)
while meetup_date < meetup_date + timedelta(days = teens_end):
meetup_date += timedelta(days=1)
if meetup_date.weekday() == weekdays.get(weekday):
break
elif flags == "last":
meetup_date += timedelta(days=31)
while meetup_date < meetup_date + timedelta(days=23):
meetup_date -= timedelta(days=1)
if meetup_date.weekday() == weekdays.get(weekday):
break
else:
week = int(flags[0])
meetup_date += timedelta(days=week*(7)-1))
while meetup_date < meetup_date + timedelta(days=8):
meetup_date += timedelta(days=1)
if meetup_date.weekday() == weekdays.get(weekday):
break
meetup_date -= timedelta(days=7)
return meetup_date
|
3547fec299d60ba4f8310f2cbb7b72167d72da0d | linhkent/nguyenkhuonglinh-fundamental-c4e25 | /Homework/homework3/exercise.py | 4,737 | 4.125 | 4 | def ex1(turtle):
# Turtle excercises
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
choice = input('''What shape do you want to draw:
1. Polygons
2. Flags
''')
# turtle.reset()
turtle.speed(10)
while choice not in ("1","2"):
choice = input("Invalid input. Please enter (1) or (2): ")
if choice == "1":
for i in range(5):
turtle.color(colors[i])
for j in range (i+3):
turtle.left(360/(i+3))
turtle.forward(100)
else:
turtle.penup()
for i in range(5):
turtle.color(colors[i])
turtle.begin_fill()
for j in range(2):
turtle.forward(50)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.end_fill()
turtle.setposition(50*i+50,0)
return()
def ex2():
# Manage clothes shop
items = ['T-Shirt', 'Sweater']
chx = input('''What do you want:
1. Add new cloth (C)
2. Update new cloth (U)
3. Delete one cloth (D)
4. Exit (E)
''')
print ("Our shop have: ", items)
while chx not in ('C', 'U', 'D', 'E','c','u','d','e'):
chx = input("Invalid input. Please re-enter (C, U, D, E): ")
while chx not in ('E', 'e'):
if chx in ('C', 'c'):
items.append(input("Enter name of new cloth: "))
elif chx in ('U', 'u'):
p = int(input("Select cloth's position you want to update: "))
items[p-1] = input("New items: ")
else:
p = int(input("Select cloth's position you want to delete: "))
del items[p-1]
print ("Our shop have: ", items)
chx = input("Any thing else?(C, U, D, E):")
while chx not in ('C', 'U', 'D', 'E','c','u','d','e'):
chx = input("Invalid input. Please re-enter (C, U, D, E): ")
print ("Goodbye!")
return()
def ex3():
# Shear the sheep
flock = []
nm = input("Enter your name: ")
n = int(input("Enter number of sheep the flock: "))
for i in range(n):
print ("Size of the sheep",i+1,":")
flock.append(int(input()))
print ("-----------------------------------------")
m = int(input("How many month do you want to work? "))
print ("My name is",nm,". And here is my flock: ")
print (flock)
print ("-----------------------------------------")
print ("Month 0:")
print ("--------")
print ("Now my biggest sheep has size", max(flock), ". Let's shear it")
print ("After shearing, hear is my flock: ")
flock[flock.index(max(flock))] = 8
print (flock)
print ("-----------------------------------------")
for i in range(m):
print ("Month",i+1,":")
print ("--------")
print ("One month passed.")
print ("My sheep have grown. Here is my flock: ")
for i in range(n):
flock[i] += 50
print (flock)
print ("Now my biggest sheep has size", max(flock), ". Let's shear it")
print ("After shearing, hear is my flock: ")
print (flock)
flock[flock.index(max(flock))] = 8
print ("-----------------------------------------")
return()
def ex4():
# word jumble
kt4 = "Y"
while kt4 in ("Y","y"):
print ("Let's play word jumble")
print ("Guess my word")
print ("You have a clue")
seq = []
chaos = []
words = ['champion', 'hexagon', 'meticulous','olympia','victory','forbidden','diamond','dragon']
n = random.randrange(0,len(words))
w = words[n]
l = len(w)
for i in range(l):
seq.append(i)
for i in range(l):
j = random.randrange(0,len(seq))
print (w[seq[j]], end = " ")
del seq[j]
print()
ws = input("Your answer is: ")
while ws != w:
ws = input("Wrong! Try again: ")
print("Hura! You are fabulous!")
kt4 = input("Wanna play again? (Y/N): ")
return()
# Main:
kt = "y"
while kt == ("y" or "Y"):
import os
os.system("cls")
n0 = int(input('''What do you want:
1. Draw shape
2. Manage clothes shop
3. Shear the sheep
4. Play word jumble
'''))
while n0 not in (1,2,3,4):
n0 = int(input("Invalid input. Re-enter: "))
if n0 == 1:
import turtle
sc = turtle.TurtleScreen()
t = turtle.Turtle()
ex1(t)
#sc = t.getscreen()
#sc.onclick("stop")
elif n0 == 2:
ex2()
elif n0 == 3:
ex3()
else:
import random
ex4()
kt = input("Again (Y/N): ")
print("Thank you!")
|
3a9b3bd247f66ff19cb1af243cf1976de807c731 | joeyzoland/2018_Algos | /MergeNode_4-15-18.py | 1,445 | 4 | 4 | #https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem
"""
Find the node at which both lists merge and return the data of that node.
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def FindMergeNode(headA, headB):
if (headA == headB):
return headA
listA = [headA]
listB = [headB]
currentA = headA.next
currentB = headB.next
while (currentA is not None or currentB is not None):
if (currentA is not None):
for i in range(0, len(listB)):
if (currentA == listB[i]):
return currentA.data
listA.append(currentA)
currentA = currentA.next
if (currentB is not None):
for j in range(0, len(listA)):
if (currentB == listA[j]):
return currentB.data
listB.append(currentB)
currentB = currentB.next
return("Error: Both lists should converge at some point, but do not")
#Sample list
sampleHead = Node(6)
sampleFirst = Node(5)
sampleSecond = Node(2)
sampleThird = Node(7)
sampleHead.next = sampleFirst
sampleFirst.next = sampleSecond
sampleSecond.next = sampleThird
#Sample list2
sampleHead2 = Node(1)
sampleFirst2 = Node(9)
sampleHead2.next = sampleFirst2
sampleFirst2.next = sampleThird
print(FindMergeNode(sampleHead, sampleHead2))
|
21347714d47babceee1e130a895b2d5ff9104e21 | armgit5/algorithms | /python/csDojo/subsets.py | 602 | 3.890625 | 4 | # https://www.youtube.com/watch?v=bGC2fNALbNU&list=PLBZBJbE_rGRVnpitdvpdY9952IsKMDuev&index=6
arr = [1,2]
def helper(arr, subset, i):
if i == len(arr):
print(subset)
else:
subset[i] = 0
helper(arr, subset, i+1)
subset[i] = arr[i]
helper(arr, subset, i+1)
def subsets(arr):
subset = [0] * len(arr)
helper(arr, subset, 0)
def subsetsIter(arr):
subset = [[]]
temp = []
for num in arr:
for item in subset:
temp += [item + [num]]
subset += temp
print(temp)
# subsets(arr)
print("")
subsetsIter(arr) |
93545361d37c8a8dad46b5887fa5fed55c956db0 | dchassin/gridlabd | /converters/csv-table2glm-library.py | 3,693 | 3.625 | 4 | import sys
import pandas
DTYPES = {
"float64" : "double",
"int64" : "int64",
"datetime" : "timestamp",
"str" : "string",
"bool" : "bool",
}
def convert(input_file, output_file, options={}):
"""Convert a CSV data table to a GLM library object list
This converts a CSV data file to a GLM library object list. The options control
how the GLM file is generated.
ARGUMENTS
input_file (str) - input file name (csv file)
ouput_file (str) - output file name (glm file)
OPTIONS
class=CLASS (required)
Specifies the class name to use when generating objects.
module={MODULE,runtime} (optional)
Specifies the module to load prior to defining object. If a module name is
specified, then the columns of the table must match the properties of the
class specified, which must be a class defined in the module specified.
index=COLUMN (optional)
Specifies the column to use as the object name. If none is specified then
objects will be anonymous.
NAME=VALUE (optional, repeated)
Specifies the NAME and VALUE of a define statement. This permits the use
of variables in fields, e.g., ${NAME} will be expanded at runtime into VALUE.
RETURNS
None
"""
oclass = None
module = None
index = None
table = pandas.read_csv(input_file)
with open(output_file,"wt") as fh:
print(f"// generated by csv-table2glm-library/convert({input_file.__repr__()},{output_file.__repr__()},{options})",file=fh)
for name, value in options.items():
if name == 'class':
oclass = options['class']
elif name == 'module':
module = options['module']
if module != 'runtime':
print(f"import {module};",file=fh)
elif name == 'index':
index = value
else:
print(f"#define {name}={value}",file=fh)
dtypes = {}
if module == 'runtime':
print(f"class {oclass}",file=fh)
print("{",file=fh)
for name, dtype in zip(table.columns.to_list(),table.dtypes.to_list()):
if name != index:
dtypes[name] = str(dtype)
if str(dtype) in DTYPES.keys():
print(f"\t{DTYPES[str(dtype)]} {name}; // {dtype}",file=fh)
else:
print(f"\t// unsupported: {dtype} {name}",file=fh)
else:
print(f"\t// index: {dtype} {name}",file=fh)
print("}",file=fh)
module = None
for id, data in table.iterrows():
if 'class' in data.keys():
oclass = data['class']
del data['class']
elif 'class' in options.keys():
oclass = options['class']
else:
raise Exception("class must defined either in data or in options")
if module:
print(f"object {module}.{oclass}",file=fh)
else:
print(f"object {oclass}",file=fh)
print("{",file=fh)
for name, value in data.items():
if name == index:
print(f"\tname \"{value}\";",file=fh)
elif module != 'runtime' or dtypes[name] in DTYPES.keys():
print(f"\t{name} \"{value}\";",file=fh)
else:
print(f"\t// {name}={value}: type {dtype} is not valid in GridLAB-D",file=fh)
print("}",file=fh)
|
ccb545b7b0babd9a0e94f0a63bdbc56e845bb48c | kalmuthu/DMS | /src/CompilerConfiguration.py | 1,011 | 3.515625 | 4 | import syslog
import string
def check_values(config_values):
"""Check if all the configuration values are correct and usable.
Emit a warning for each bad value.
Return false if at least one configuration value is erroneous,
and a tuple containing the keys that contain bad values, and need to be replaced
by default ones."""
# tuple containing names of the configuration dictionnary keys that
# are erroneous
erroneous_keys = []
config_valid = 1
# check if the scheduler_port is a valid string int
try:
string.atoi(config_values["scheduler_port"], 10)
except:
config_valid = 0
erroneous_keys.append("scheduler_port")
syslog.syslog(syslog.LOG_WARNING | syslog.LOG_DAEMON, \
"Warning : in the configuration file the scheduler_port is "\
+ "a bad string representing an int : "
+ config_values["scheduler_port"])
return (tuple(erroneous_keys), config_valid)
|
d1b6daa8620f9a5e5f8b87f18dddf7a2b5ff469e | sk84uhlivin/pokemon-gen2-clockreset-calculator | /gen2clkrst.py | 1,251 | 3.625 | 4 | #!/usr/bin/python3
print()
print('Pokémon Gen 2 Clock Reset Calculator v1.0 by sk84uhlivin')
print()
arbval = 63
dcon = 256
magicnumber = 65535
class calc:
def name(input_name):
x = 0
y = 0
if len(input_name) > 4:
for x in range(5):
y+=ord(input_name[x])
y+=arbval
return y
else:
for x in range(len(input_name)):
y+=ord(input_name[x])
y+=arbval
return y
def id(input_id):
return (int(input_id)//dcon)+(int(input_id)%dcon)
def cash(input_cash):
if input_cash > magicnumber:
modinput_cash = input_cash%magicnumber
return ((modinput_cash)//dcon)+((modinput_cash)%dcon)
else:
return ((input_cash)//dcon)+((input_cash)%dcon)
#Prints results of calc functions
def debug():
print('Debug info:')
print(calc.name(input_name),calc.id(input_id),calc.cash(input_cash))
def main():
input_name = input("NAME? ")
input_id = int(input("ID#? "))
input_cash = int(input("CASH? "))
password = calc.name(input_name) + calc.id(input_id) + calc.cash(input_cash)
print()
print(str(password).zfill(5))
print()
if __name__ == '__main__':
while True:
main()
if input('Restart? ') != 'y':
break
else:
print() |
f8f06d6f6f30efcb941b167231427aaabdc9f715 | MCavigli/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 182 | 4.09375 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
for i in matrix:
for j in i:
print("{:d}".format(j), end="" if j == i[-1] else " ")
print()
|
ec1ffa1f0cbf37ae3c5d631543aa2a58fe2ad69f | dani0f/mail-extraction-regex-analisis | /regex.py | 4,198 | 3.59375 | 4 | import re
#código basado de https://github.com/benstreb/regex-generator
def generate_regex(samples):
characters_list = []
for sample in samples:
characters_list = extend_characters_list(characters_list, len(sample))
for i, character in enumerate(sample):
characters_list[i].add(character)
return "".join(display_group(characters) for characters in characters_list)
def display_group(characters):
if len(characters) == 1:
template = "{}"
else:
template = "[{}]"
return template.format("".join(sorted(characters)))
def extend_characters_list(characters_list, length):
extension_length = max(length - len(characters_list), 0)
return characters_list + [set() for i in range(extension_length)]
#Código para reducir el regex generado
def dif(str1,str2):
minS = str1
maxS = str2
if(len(str1) > len(str2)):
minS=str2
maxS=str1
num = len(minS)
for i in range(num):
maxS=maxS.replace(minS[i],"", 1)
return(maxS)
def reduceRegex(resultArray):
arraySintax= []
for i in range(len(resultArray)):
sintax=""
if(resultArray[i][0] == "["):
if(len(resultArray[i][1:]) > 5 ):
stringAux = resultArray[i][1:]
if(stringAux.isdigit()):
sintax= "\d"
if(stringAux.isupper() and sintax==""):
sintax= "A-Z"
if(stringAux.islower() and sintax==""):
sintax= "a-z"
if(bool(re.search(r'[^A-Za-z0-9]', stringAux)) and sintax==""):
specialC =""
specialCArray=re.findall(r'[^A-Za-z0-9]', stringAux)
for c in specialCArray:
specialC= specialC +c
sintax = "a-zA-Z0-9"+specialC
elif(sintax==""):
sintax= "^A-Za-z0-9"
sintax = "["+sintax+"]"
else:
sintax = resultArray[i]+"]"
else:
arrayAux= resultArray[i].split("[")
if( len(arrayAux) > 1):
sintax=arrayAux[0]+"["+arrayAux[1]+"]"
else:
sintax=arrayAux[0]
arraySintax.append(sintax)
resFinalStr=""
a=0
while(a < len(arraySintax)):
numAgrup = 0
if(arraySintax[a][0]=="["):
agrupFinal =""
for b in range(a,len(arraySintax)):
resDif=dif(arraySintax[a],arraySintax[b])
cond = 0
if(len(resDif) < 4):
if(len(arraySintax[a]) == len(arraySintax[b])):
if(len(resDif)!= 0):
arraySintax[a] = arraySintax[a][:-1] + resDif + "]"
cond = 1
numAgrup =numAgrup + 1
if((len(arraySintax[a])> len(arraySintax[b])) and cond == 0):
arraySintax[a] = arraySintax[b][:-1]+resDif+"]"
numAgrup = numAgrup +1
if((len(arraySintax[a])< len(arraySintax[b])) and cond == 0):
arraySintax[a] = arraySintax[a][:-1]+resDif+"]"
numAgrup = numAgrup +1
else:
agrupFinal = r"{"+ str(numAgrup) +r"}"
if(numAgrup == 1):
agrupFinal=""
arraySintax[a]=arraySintax[a]+agrupFinal
break
resFinalStr = resFinalStr + arraySintax[a]
if(numAgrup >0):
a=a+numAgrup
else:
a=a+1
return(resFinalStr)
def getRegexIdFile(namefile):
f = open (namefile,'r')
msg = f.read()
msgArray = msg.split()
f.close()
result = generate_regex(msgArray)
result2 = reduceRegex(result.split("]"))
return(result2)
def getRegexId(msgArray):
result = generate_regex(msgArray)
result2 = reduceRegex(result.split("]"))
return(result2)
#A partir de un archivo:
#a=getRegexIdFile("entrenamiento.txt")
#print(a)
#A partir de un arreglo
#a=getRegexId(["holaaa423423423","hola4343424332"])
#print(a) |
ef1b2007fd5d68b5a138ae05ee8b69890fb7f194 | hanzhi713/thinkcs-python3-solutions | /Chapter 8/E5.py | 1,017 | 4.25 | 4 | import string
def eCounter(text):
newText = ""
count = 0
numofwords = 0
for char in text:
if char not in string.punctuation:
newText += char
newText = newText.split()
for words in newText:
numofwords += 1
if words.find("e") != -1:
count += 1
print("Your text contains {0} words, of which {1} ({2}%) contain an 'e'.".format(str(numofwords), str(count),
str(count / numofwords * 100)))
text = '''Assign to a variable in your program a triple-quoted string that contains your favourite paragraph of text — perhaps a poem, a speech, instructions to bake a cake, some inspirational verses, etc.
Write a function which removes all punctuation from the string, breaks the string into a list of words, and counts the number of words in your text that contain the letter “e”. Your program should print an analysis of the text like this:'''
eCounter(text)
|
3177527ab463c92cdd85f82d5663e9ee92fc84c5 | Aasthaengg/IBMdataset | /Python_codes/p02624/s840158023.py | 187 | 3.53125 | 4 | def main():
N=int(input())
ans=0
for i in range(1,N+1):
m=N//i
ans+=i*m*(m+1)//2
#print(i,N//i,m)
print(ans)
if __name__ == '__main__':
main() |
29069c499c53049136b049a223fe55f1b06fcbec | yqxd/LEETCODE | /67AddBinary.py | 978 | 3.796875 | 4 | '''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
Each string consists only of '0' or '1' characters.
1 <= a.length, b.length <= 10^4
Each string is either "0" or doesn't contain any leading zero.
'''
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a) < len(b):
a, b = b, a
b = '0' * (len(a) - len(b)) + b
num = ''
k = 0
for i in range(len(a)-1, -1, -1):
num = str((int(a[i]) + int(b[i]) + k) % 2) + num
k = (int(a[i]) + int(b[i]) + k) // 2
if k == 1:
return '1' + num
else:
return num
A = Solution()
print(A.addBinary('1010', '1011'))
|
5c83769aefc7f75bf5f83b56610fc75b5bd32515 | nihn/radix-sort | /radix_sort.py | 1,292 | 3.546875 | 4 | from functools import reduce
class ZeroList(list):
"""
List which returns 0 when requested index is outside it.
"""
def __getitem__(self, item):
try:
return super().__getitem__(item)
except IndexError:
return 0
def counting_sort(array, key=lambda x: x):
length = key(max(array, key=key))
counting_array = [list() for _ in range(length + 1)]
for item in array:
counting_array[key(item)].append(item)
return [item for subarray in counting_array for item in subarray]
def convert(number, base):
new = []
while number > 0:
new.append(number % base)
number //= base
return ZeroList(reversed(new))
def radix_sort(array, return_base10=True):
base = len(array)
helper_array = []
max_len = 0
for number in array:
converted = convert(number, base)
helper_array.append(converted)
max_len = max(max_len, len(converted))
for i in range(max_len):
helper_array = counting_sort(helper_array, key=lambda x: x[-i-1])
return [reduce(lambda x, y: x + y[1] * (base ** y[0]),
zip(range(len(number)), reversed(number)),
0)
for number in helper_array] if return_base10 else helper_array
|
a59592cde5ca5559bfb313e61c12808237df050a | KrisAesoey/Kattis | /nodup.py | 198 | 3.71875 | 4 | import sys
s = input()
seen = []
words = s.split()
for word in words:
if word in seen:
print("no")
sys.exit()
else:
seen.append(word)
print("yes") |
ae7cb2e1ade4bca6c9fee807224c839dc39483e8 | broooo24/contactBook | /main.py | 2,586 | 4.625 | 5 | # This is one of the excellent python projects for beginners.
# Everyone uses a contact book to save contact details, including name, address, phone number,
# and even email address. This is a command-line project where you will design a contact book application
# that users can use to save and find contact details. The application should also allow users to update contact information,
# delete contacts, and list saved contacts. The SQLite database is the ideal platform for saving contacts.
# To handle a project with Python for beginners can be helpful to build your career with a good start.
import os
import json
import sqlite3
con = sqlite3.connect('contact.db')
cur = con.cursor()
def createTable():
cur.execute('''CREATE TABLE contact
(name text, addres text, phone text, email text)''')
def createUser(name, addres, phone, email):
cur.execute("insert into contact (name, addres, phone, email) values (?, ?, ?, ?)",
(name, addres, phone, email))
con.commit()
def showAllTable():
cur.execute("SELECT * FROM contact")
rows = cur.fetchall()
for row in rows:
print(row)
def deleteUser(name):
sql_update_query = """DELETE from contact where name= ?"""
cur.execute(sql_update_query, (name,))
con.commit()
def updateUser(name, addres, phone, email):
sql_update_query = """UPDATE contact SET addres = ? ,
phone = ? ,
email = ?
WHERE name = ?"""
cur.execute(sql_update_query, (addres, phone, email, name))
def closeConnection():
con.close()
def menu():
print("1 Create User\n2 Delete User\n3 Update user\n4 Show all table")
choice = int(input("Enter your value: "))
print(choice)
if(choice == 1):
name = input("Enter name: ")
addres = input("Enter address: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
createUser(name, addres, phone, email)
elif (choice == 2):
name = input("Enter name: ")
deleteUser(name)
elif (choice == 3):
name = input("Enter name: ")
addres = input("Enter address: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
updateUser(name, addres, phone, email)
elif (choice == 4):
showAllTable()
# createUser("John", "Tokyo", "3333", "johny@gmail.com")
# deleteUser("John")
#updateUser("Jürgen", "homeless", "3333", "homelessgermannotexist@gmail.com")
menu()
closeConnection()
|
231af89ae80130a4613c4300b13659fb36e3ca84 | csepdo/codecool | /com_div.py | 218 | 3.875 | 4 | while True:
from math import gcd
i = input('Type in the two numbers you want to know the Greatest Common Divisor of. ')
r = list(map(int, i.split(',')))
result = gcd(r[0], r[1])
print(result)
|
fb8e402dec9a4a801274a95daf967ef66e1dad8c | hmanoj59/python_scripts | /anagram.py | 149 | 3.875 | 4 | def anagram(str1, str2):
str1 = str1.replace(' ', '').lower()
str2 = str2.replace(' ', '').lower()
return sorted(str1) == sorted(str2)
|
2e2d6a1fecf58771bdd66347b84905aa6cfa0d4e | eliben/code-for-blog | /2009/csp_for_euler68/csplib.py | 9,926 | 3.875 | 4 | """ Based on the AIMA Python code.
"""
from collections import deque
class CSP(object):
""" A finite-domain Constraint Satisfaction Problem.
Specified by the following:
vars:
A list of variables (ints or strings)
domains:
A dict holding for each var a list of its possible
values.
neighbors:
A dict holding for each var a list of the other
variables that participate in constraints with this
var.
binary_constraint:
A function func(A, a, B, b) that returns True iff
neighbors A, B satisfy the constraint when they have
values A=a, B=b.
global_constraint:
A function func(new_asgn, cur_asgn) that returns
True iff the var=val in new_asgn (a dict of var=val)
conflict with the current assignment.
The solution of a CSP is an 'assignment' - a dictionary
mapping a variable to a value.
Usage:
Create a new CSP and then call a 'solve' method.
Public interface:
solve_search(init_assign=False, mcv=False, lcv=False):
Solve the CSP using backtracking search with forward
checking constraint propagation. 'init_assign' is
an initial assignment from which the search starts
running (useful for problems like Sudoku).
'mcv' turns the most constrained variable heuristic on
'lcv' turns the least constraining value heuristic on
Returns an assignment if one can be found, None
otherwise.
check_consistency(assignment):
Check that the given assignment is consistend (i.e.
has no internal conflicts) in this CSP.
to_str(assignment):
Sub-classes may reimplement this to convert a solved
CSP into a string.
Attributes:
nassigns:
Statistical measure of the amount of assignments made
during the search.
loglevel:
Set to enable logging printouts.
"""
def __init__(self, vars, domains, neighbors,
binary_constraint=None, global_constraint=None):
""" Construct a new CSP. If vars is empty, it becomes
domains.keys()
"""
self.vars = vars or domains.keys()
self.domains = domains
self.neighbors = neighbors
self.binary_constraint = binary_constraint or (lambda *args: True)
self.global_constraint = global_constraint or (lambda *args: True)
self.clear()
def clear(self):
""" Clears the internal state of the CSP, allowing to run
a solve method again.
"""
# For forward checking
self.curr_domains, self.pruned = {}, {}
# For statistics
self.nassigns = 0
# Minimal level of log messages to be printed
self.loglevel = 999
def to_str(self, assignment):
raise NotImplementedError()
def check_consistency(self, assignment):
""" Checks that the assignment is consistent for this CSP.
Returns True if it is, False if there are conflicts.
"""
for var, val in assignment.iteritems():
if self._has_conflicts(var, val, assignment):
return False
return True
def solve_search( self, init_assign=None,
mcv=False, lcv=False):
self.mcv = mcv
self.lcv = lcv
self.curr_domains, self.pruned = {}, {}
for A in self.vars:
self.curr_domains[A] = self.domains[A][:]
self.pruned[A] = []
def aux_backtrack(assignment):
# Success if all the vars were assigned
if len(assignment) == len(self.vars):
return assignment
# Pick a variable to assign next
var = self._select_unassigned_var(assignment)
# Try to assign the available domain values to this
# variable. If an assignment doesn't immediately
# conflict, explore this path recursively.
# If an assignment eventually fails, remove it and
# backtrack.
#
for val in self._order_domain_values(var, assignment):
if not self._has_conflicts(var, val, assignment):
self._assign(var, val, assignment)
result = aux_backtrack(assignment)
if result is not None:
return result
# This assignment didn't succeed, so backtrack.
# Note: calling _unassign is harmless if this var
# wasn't actually assigned by _assign
#
self._unassign(var, assignment)
return None
# Make initial assignment
#
assignment = {}
if init_assign:
self._log(20, '======== Initial assignment ========')
for A in init_assign:
self._assign(A, init_assign[A], assignment)
self._log(20, '======== END Initial assignment ========')
return aux_backtrack(assignment)
def _log(self, level, msg):
if level >= self.loglevel:
print msg
def _select_unassigned_var(self, assignment):
""" Select the var to try to assign next.
"""
if self.mcv:
# Most constrained variable heuristic.
# Pick the unassigned variable that has fewest legal
# values remaining.
#
unassigned = [v for v in self.vars if v not in assignment]
return min(unassigned,
key=lambda var: self._num_legal_values(var))
else:
# No heuristic: just select the first unassigned var
#
for v in self.vars:
if v not in assignment:
return v
def _order_domain_values(self, var, assignment):
""" Returns an iterator over the domain values to be tried
for 'var' for the next assignment.
"""
domain = self.curr_domains[var]
if self.lcv:
# Least constraining value heuristic.
# Consider values with fewer conflicts first.
#
key = lambda val: self._nconflicts(var, val, assignment)
domain.sort(key=key)
return domain
def _nconflicts(self, var, val, assignment):
""" The number of conflicts var=val has with the other
variables.
Note: subclasses may implement this more efficiently
using domain knowledge.
"""
return (
0 + (not self.global_constraint({var: val}, assignment)) +
sum(self._aux_neighbor_conflict(var, val, v, assignment)
for v in self.neighbors[var]))
def _assign(self, var, val, assignment):
""" Add var=val to assignment. If var already has a value
in the assignment, it's replaced.
"""
assignment[var] = val
self.nassigns += 1
self._log(20, 'Assigning %s = %s' % (var, val))
# Propagate constraints
self._forward_check(var, val, assignment)
def _unassign(self, var, assignment):
""" Unassign var from the assignment.
"""
if var in assignment:
self._log(20, 'Backtracking %s = %s' % (var, assignment[var]))
# Restore the domains pruned from the previous value
# tried for var.
#
for (B, b) in self.pruned[var]:
self.curr_domains[B].append(b)
self.pruned[var] = []
del assignment[var]
def _aux_neighbor_conflict(self, var, val, var2, assignment):
""" Does var=val have conflicts with var2 in the
assignment?
"""
val2 = assignment.get(var2, None)
return not (
val2 is None or
self.binary_constraint(var, val, var2, val2))
def _has_conflicts(self, var, val, assignment):
""" Does var=val have conflicts with the assignment?
"""
return (
not self.global_constraint({var: val}, assignment) or
any(self._aux_neighbor_conflict(var, val, v, assignment)
for v in self.neighbors[var]))
def _num_legal_values(self, var):
""" The amount of legal values possible for 'var'.
"""
return len(self.curr_domains[var])
def _forward_check(self, var, val, assignment):
""" Do forward checking (constraint propagation) for
var=val with the given assignment.
"""
# Remove all neighbor values that conflict with
# var=val from their curr_domains
#
for B in self.neighbors[var]:
if B in assignment:
continue
for b in self.curr_domains[B]:
if not (self.binary_constraint(var, val, B, b) and
self.global_constraint({var: val, B: b}, assignment)):
self.curr_domains[B].remove(b)
self.pruned[var].append((B, b))
self._log(10, 'FC: %s=%s, %s' % (var, val, assignment))
self._log(10, ' : %s' % self.curr_domains)
|
aca0e80bc040ee3d698d6f60fb590f734ad5e83a | Krieg0-0/LearnPython | /EX19.py | 787 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 20:46:05 2019
@author: 薛
"""
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of cracker!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20,30)
print("OR, we can use variable from our script:")
amount_of_cheese = 10
amount_of_crackers =50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 +20, 5+6)
print("And we can combine the two, variable and math:")
cheese_and_crackers(amount_of_cheese +100, amount_of_crackers) |
0699e502db865b88893ab38221a3694b2b9b03f9 | bufordsharkley/advent_of_code | /2015/day14.py | 1,066 | 3.53125 | 4 | import operator
class Reindeer(object):
def __init__(self, name, speed, stamina, rest):
self.name = name
self.speed = speed
self.tank = self.stamina = stamina
self.wait = self.rest = rest
self.position = 0
def move(self):
if self.tank:
self.position += self.speed
self.tank -= 1
self.wait = self.rest
else:
self.wait -= 1
if not self.wait:
self.tank = self.stamina
if __name__ == "__main__":
reindeers = []
for ln in open('input/input14.txt'):
name, _, _, speed, _, _, stamina, _, _, _, _, _, _, rest, _ = ln.split()
reindeers.append(Reindeer(name, int(speed), int(stamina), int(rest)))
points = {x.name: 0 for x in reindeers}
for ii in range(2503):
for reindeer in reindeers:
reindeer.move()
current = sorted(reindeers, key=lambda x: x.position)[-1].name
points[current] += 1
print max(x.position for x in reindeers)
print max(points.values())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.