blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
3eefb470c6da99f23213785fba479914399f8728
Nouw/Programming-class
/les-8/8.1_while-loop_numbers.py
264
3.671875
4
running = True som = 0 getallen = -1 while running: getal = int(input("Geef en getal:")) som += getal getallen += 1 if getal == 0: running = False print("Er zijn " + str(getallen) + " getallen ingevoerd, de som is: " + str(som))
d4613de5a15162d087a76da28fd82077cfebc928
Nouw/Programming-class
/les-11/11.2_json-files_schrijven.py
961
3.609375
4
import json import os def store(name, firstl, birthdate, email): # Basically checks if the data.json file exists if not then create data.json file files = [] for f_name in os.listdir('.'): files.append(f_name) if 'data.json' not in files: with open('data.json', 'w') as file: file.write('[]') # get all the data from the json file and add the login to it with open('data.json') as data_file: old_data = json.load(data_file) old_data.append({"naam": name, "voorletters": firstl, "geb_datum": birthdate, "e-mail": email}) with open('data.json', 'w') as outfile: json.dump(old_data, outfile, indent=4) while True: naam = input("Wat is je achternaam? ") if naam == "einde": break voorl = input("Wat zijn je voorletters? ") gbdatum = input("Wat is je geboortedatum? ") email = input("Wat is je e-mail adres? ") store(naam, voorl, gbdatum, email)
90d57fc0012c7370848d13f914790c03a9f10054
Nouw/Programming-class
/les-8/ns-kaartautomaat.py
2,035
4.1875
4
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', "'s-Hertogenbosch", 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht'] def inlezen_beginstation(stations): running = True while running: station_input = input('Wat is uw begin station?') if station_input in stations: running = False return stations.index(station_input) else: print('Het opgegeven station bestaat niet!') def inlezen_eindstation(stations, beginstation): running = True while running: station_input = input('Wat is uw eind station?') if station_input in stations: if beginstation < stations.index(station_input): running = False return stations.index(station_input) else: print("Het station is de verkeerde kant op!") else: print('Het opgegeven station bestaat niet!') def omroepen_reis(stations, beginstation, eindstation): nameBeginstation = stations[beginstation] nameEndstation = stations[eindstation] distance = eindstation - beginstation price = distance * 5 print("Het beginstation " + nameBeginstation + " is het " + str(beginstation) + "e station in het traject \n" + "Het eindstation " + nameEndstation + " is het " + str(eindstation) + "e station in het traject \n" + "De afstand bedraagt " + str(distance) + " station(s) \n" + "De prijs van het kaartje is " + str(price) + " euro") print("Jij stapt in de trein in: " + nameBeginstation) for stationIndex in range((len(stations))): if eindstation > stationIndex > beginstation: print("-" + stations[stationIndex]) print("Jij stapt uit in: " + nameEndstation) beginstation = inlezen_beginstation(stations) eindstation = inlezen_eindstation(stations, beginstation) omroepen_reis(stations, beginstation, eindstation)
4ab0c17cea4ecc2344962dd34235a0afd3eea132
Nouw/Programming-class
/les-6/6.5_string_functions.py
491
3.796875
4
# Schrijf functie gemiddelde(), die de gebruiker vraagt om een willekeurige zin in te voeren. De functie berekent vervolgens de gemiddelde lengte van de woorden in de zin en print dit uit. def gemiddelde(zin): words = zin.split() print(words) totalLength = 0 wordCount = 0 for word in words: length = len(word) totalLength += length wordCount += 1 return print(totalLength / wordCount) zin = input('Tik een willekeurige zin') gemiddelde(zin)
a0d1ec47af81124c47b0c16ea678b230255f2ec7
Iretiayomide/Week-8
/Assignment 7b.py
594
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[9]: #import libraries import matplotlib.pyplot as plt import pandas as pd #create dataset names = ['Bob','Jessica','Mary','John','Mel'] status = ['Senior','Freshman','Sophomore','Senior', 'Junior'] grades = [76,95,77,78,99] GradeList = zip(status,grades) #create dataframe df = pd.DataFrame(data = GradeList, columns=['Status', 'Grades']) #plot graph get_ipython().magic(u'matplotlib inline') df.plot(kind='bar') # In[10]: #add code to plot dataset, replacing x-axis with Names column df2 = df.set_index(df['Status']) df2.plot(kind="bar")
8bf44c4718c44c230b4cac4d0fc5589c0313e31b
lexatnet/school
/python/17-pygame/01-ball/05-collision/engine/collision.py
2,246
3.5
4
def ball_to_box_collision(ball, box): return { 'x': ball_to_box_collision_x(ball, box), 'y': ball_to_box_collision_y(ball, box) } def ball_to_box_collision_x(ball, box): width = box['size']['width'] height = box['size']['height'] if (ball['rect'].left < 0) or (ball['rect'].right > width): return True return False def ball_to_box_collision_y(ball, box): width = box['size']['width'] height = box['size']['height'] if ball['rect'].top < 0 or ball['rect'].bottom > height: return True return False def ball_to_ball_collision(ball_a, ball_b): return { 'x': ball_to_ball_collision_x(ball_a, ball_b), 'y': ball_to_ball_collision_y(ball_a, ball_b) } def ball_to_ball_collision_x(ball_a, ball_b): interval_y = max(ball_a['rect'].bottom, ball_b['rect'].bottom) - min(ball_a['rect'].top, ball_b['rect'].top) coverage_y = ball_a['rect'].bottom - ball_a['rect'].top + ball_b['rect'].bottom - ball_b['rect'].top interval_x = max(ball_a['rect'].right, ball_b['rect'].right) - min(ball_a['rect'].left, ball_b['rect'].left) coverage_x = ball_a['rect'].right - ball_a['rect'].left + ball_b['rect'].right - ball_b['rect'].left if ( (interval_y < coverage_y) and (interval_x < coverage_x) ): return True return False def ball_to_ball_collision_y(ball_a, ball_b): interval_x = max(ball_a['rect'].right, ball_b['rect'].right) - min(ball_a['rect'].left, ball_b['rect'].left) coverage_x = ball_a['rect'].right - ball_a['rect'].left + ball_b['rect'].right - ball_b['rect'].left interval_y = max(ball_a['rect'].bottom, ball_b['rect'].bottom) - min(ball_a['rect'].top, ball_b['rect'].top) coverage_y = ball_a['rect'].bottom - ball_a['rect'].top + ball_b['rect'].bottom - ball_b['rect'].top if ( (interval_x < coverage_x) and (interval_y < coverage_y) ): return True return False def get_ball_to_balls_collisions(balls, ball): collisions = [] print('ball = {}'.format(ball['rect'])) for test_ball in balls: test_ball_collision = ball_to_ball_collision(ball, test_ball) print('here') if (test_ball_collision['x'] or test_ball_collision['y']): print('here 1') collisions.append(test_ball) return collisions
f6b956a6dc2d4a44bb586c79f16d541ac2c66cff
matanyehoshua/13.10.21
/Page 38_8.py
243
4
4
# Page 38_8 x = int(input("Enter a number: ")) y = int(input("Enter another number: ")) # prints the row x times and how many each row y times: for i in range(x): for i in range(y): print ('*', end = ' ') print()
2c8771dfe733ce5d3e7fb1af3105edd36d18534e
JVLJunior/Exercicios-URI---Python
/URI_1153.py
91
3.515625
4
n = int(input()) cont = n fat = 1 while cont > 0: fat *= cont cont -= 1 print(fat)
582a8b75d58698a4d89826aecb927d5dd22458d8
zhuweida/Tracing-Trends-in-Macronutrient-Intake-and-Energy-Balance-Across-Demographics-with-Statistics-and-Ma
/code/pr2.py
4,428
4
4
""" the function of converting RDD into csv file is based on http://stackoverflow.com/questions/31898964/how-to-write-the-resulting-rdd-to-a-csv-file-in-spark-python/31899173 And some of the initialization code is provided by our instructor Dr. Taufer. """ import re import argparse import collections import sys from pyspark import SparkContext,SparkConf import csv,io conf = SparkConf() sc = SparkContext(conf=conf) global t t=[] column=[] for i in range(20): t.append([]) def list_to_csv_str(x): """Given a list of strings, returns a properly-csv-formatted string.""" output = io.StringIO("") csv.writer(output).writerow(x) return output.getvalue().strip() # remove extra newline def float_number(x): TEMP=[] a=0 #to record whether there are missing data in the row for i in range(len(x)): if x[i] == '': #we use a to record whether there is missing value in this row a=a+1 if x[i] == '5.40E-79': x[i]=0 if a == 0: #if a is still 0 it means there are no missing value in this column #if x[1] == '1': #if the column of recall is 1 for i in range(len(x)): TEMP.append(float(x[i])) #put all of x which we are satisfied with into list of which name is TEMP return TEMP def toCSVLine(data): return ','.join(str(d) for d in data) def convert(x): for i in range(len(x)): t[i].append(x[i]) return t def processFile(fileName): t=[] line=sc.textFile(fileName) a=line.zipWithIndex() b=a.filter(lambda x:x[1]>0).map(lambda x:x[0].split(',')) #make sure to remove the first row which is the name of column(string) c=b.map(lambda x:[str(y) for y in x]).map(lambda x:(float_number(x))) data=c.filter(lambda x:len(x)>0) #row_data d=data.map(lambda x:convert(x)) t=d.collect() for i in range(8): column.append(t[-1][i]) colrdd=sc.parallelize(column) #col data calorie=sc.parallelize(column[4]) protein=sc.parallelize(column[5]) carbon=sc.parallelize(column[6]) fat=sc.parallelize(column[7]) calorie_mean=calorie.mean() protein_mean=protein.mean() carbon_mean=carbon.mean() fat_mean=fat.mean() calorie_sampleStdev=calorie.sampleStdev() protein_sampleStdev=protein.sampleStdev() carbon_sampleStdev=carbon.sampleStdev() fat_sampleStdev=fat.sampleStdev() calorie_variance=calorie.sampleVariance() protein_variance=protein.sampleVariance() carbon_variance=carbon.sampleVariance() fat_variance=fat.sampleVariance() cor_protein_energy = protein.zip(calorie) cor_carbon_energy=carbon.zip(calorie) cor_fat_energy=fat.zip(calorie) cor1=cor_protein_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(protein_sampleStdev*calorie_sampleStdev))) cor2=cor_carbon_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(carbon_sampleStdev*calorie_sampleStdev))) cor3=cor_fat_energy.map(lambda x:((x[0]-protein_mean)*(x[1]-calorie_mean)/(fat_sampleStdev*calorie_sampleStdev))) print cor1.collect() number = cor1.count() cor=cor1.zip(cor2).zip(cor3) print "protein_mean:"+str(protein_mean) print "carbon_mean:"+str(carbon_mean) print "fat_mean:"+str(fat_mean) print "calorie_mean"+str(calorie_mean) print "protein_variance:"+str(protein_variance) print "carbon_variance:"+str(carbon_variance) print "fat_variance:"+str(fat_variance) print "calorie_variance:"+str(calorie_variance) print "number of samples:"+str(number) print "mean correlation of protein and calorie:" +str(cor1.mean()) print "mean correlation of carbon and calorie:" +str(cor2.mean()) print "mean correlation of fat and calorie:"+str(cor3.mean()) print "remind: everytime you run the code you should change the csv name in line 104 of the code to get the csv of correlation " cors=cor.map(toCSVLine) cors.saveAsTextFile("2010_correlation_dietarydata.csv") def quiet_logs(sc): logger = sc._jvm.org.apache.log4j logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR ) logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR ) def main(): quiet_logs(sc) parser = argparse.ArgumentParser() parser.add_argument('filename', help="filename of input text", nargs="+") args = parser.parse_args() for filename in args.filename: processFile (sys.argv[1]) if __name__ == "__main__": main()
820dcba436961e21d6b9b5eb93ad76608904b663
El-akama/week7_task_oop_encapsulation
/task_oop_incapsulation.py
2,072
3.78125
4
# task1 # class Car: # def __init__(self, make, model, year, odometer=0, fuel=70): # self.make = make # self.model = model # self.year = year # self.odometer = odometer # self.fuel = fuel # def __add_distance(self, km): # self.odometer += km # def __subtract_fuel(self, fuel): # self.fuel -= fuel # def drive(self, km): # if self.fuel * 10 >= km: # self.__add_distance(km) # kml = km // 10 # self.__subtract_fuel(kml) # print('Let’s drive!') # else: # print('Need more fuel!') # a = Car('japan', 'toyota', 2020, 70) # a.drive(100) # print(a.odometer) # print(a.fuel) # task2 # class Mobile: # __imeil = "samsung" # __battery = 100 # __info = 'ssd' # __os = 'charity' # def listen_music(self): # self.__battery -= 5 # print(f'играет музыка, заряд батареи {self.__battery} %') # def watch_video(self): # self.__battery -=7 # print(f"смотрим видео, заряд батареи {self.__battery} %") # if self.__battery <= 10: # print(f"не смотрим видео, заряд батареии {self.__battery} %") # def battery_charging(self): # self.__battery = 100 # print('батарея заряжена') # def info_battery(self): # if self.__battery == 0: # raise Exception ("батарея разряжена, нужно подзарядить") # else: # print(self.__battery) # m = Mobile() # m.listen_music() # m.listen_music() # m.listen_music() # m.listen_music() # m.listen_music() # m.listen_music() # m.watch_video() # m.watch_video() # m.watch_video() # m.watch_video() # m.watch_video() # m.watch_video() # m.watch_video() # m.watch_video() # # m.watch_video() # # m.watch_video() # чтобы вызвать ошибку # m.info_battery() # m.battery_charging() # m.info_battery() # task3 # делаю
9264d91dbaf742726eb9c3bf7d70d8931b4556eb
519984307/BaseHouse
/Python/Base/ProducerConsumer/MultiThread.py
2,357
3.671875
4
import random import time from threading import Thread, Lock, Condition from queue import Queue class Producer(Thread): def __init__(self, queue, lock, condition): super().__init__() self._queue = queue self._lock = lock self._condition = condition def run(self): while True: with self._condition: # 获取或等待线程条件 try: item = random.randint(1, 100) ''' block=True ,如果当前队列已经满了,则put()使调用线程暂停,直到空出一个数据单元 block=False,如果当前队列已经满了,则put()将引发Full异常。 block默认为True ''' if not self._queue.full(): self._lock.acquire() self._queue.put(item, block=False) self._lock.release() self._condition.wait() # 等待 self._condition.notify() # 通知 print('Produce ', item) else: self._condition.notify() print("Queue is full") except Queue.Full: print("Queue is full") time.sleep(1.0e-4) class Consumer(Thread): def __init__(self, queue, lock, condition): super().__init__() self._queue = queue self._lock = lock self._condition = condition def run(self): while True: with self._condition: if not self._queue.empty(): self._lock.acquire() item = self._queue.get() self._lock.release() self._condition.notify() self._condition.wait() print('Consume ', item) else: print("Queue is empty, please wait!") time.sleep(1.0e-4) if __name__ == '__main__': q = Queue(maxsize=20) lock = Lock() # 线程条件变量,实现线程调度 condition = Condition() producer = Producer(q, lock, condition) consumer = Consumer(q, lock, condition) producer.start() consumer.start()
1560e2c88d1c43d1d8dce3f9aeee17b1b861bd73
gracenamucuo/PythonStudy
/ClassAndInstance.py
3,412
4.125
4
class Animal(object): def run(self): print('Animal is running') def run_teice(animal): animal.run() animal.run() #对于Python这样的动态语言来说,不一定需要传入Animal类型,只需要保证传入的对象有一个run()方法就可以。 #判断一个变量是不是某个类型 isinstance(a,Animal) #判断对象类型,使用type()函数: #type()函数返回的是Class类型 #判断一个对象是否是函数 import types def fn(): pass type(fn)==types.FunctionType True type(abs)==types.BuiltinFunctionType True type(lambda x: x)==types.LambdaType True type((x for x in range(10)))==types.GeneratorType True #配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态: class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject() hasattr(obj, 'x') # 有属性'x'吗? True obj.x 9 hasattr(obj, 'y') # 有属性'y'吗? False setattr(obj, 'y', 19) # 设置一个属性'y' hasattr(obj, 'y') # 有属性'y'吗? True getattr(obj, 'y') # 获取属性'y' 19 obj.y # 获取属性'y' 19 #类属性归类所有,但是所有该类的实例都可以访问到。 class Stu(object): pass s = Stu() s.name = '添加属性名字' #绑定方法 #实例绑定方法 def set_age(self,age): self.age = age from types import MethodType s.set_age = MethodType(set_age,s) s.set_age(5) #类绑定方法 def set_score(self,score): self.score = score Stu.set_score = set_score #对实例的属性进行限制 只允许Stu实例添加name和age属性 class Stu(object): __slots__ = ('name','age')#用tuple定义绑定的属性名称 #__slots__仅是对当前类实例起作用,对继承的子类不起作用 #@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。 #类设计的时候,通常主线是单一继承下来的,但是要‘混入’额外功能的时候,通过多继承就可以实现,为了更好地看出继承关系,一般把非主线的继承名字后缀加上MixIn #定制类 # __str__ 类似 重写OC类中description方法 class Stu(object): def __init__(self,name): self.name = name def __str__(self): return 'Stu object (name: %s) ' % self.name print(Stu('你好')) #Stu object (name: 你好 class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name=%s)' % self.name __repr__ = __str__ #如果想一个类可以for……in 循环 需要实现一个__iter__()方法,方法返回一个迭代对象,还需要在该类中实现一个__next__()方法 直到遇到StopIteration # __call__ 我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象 def fn(self,name='world'): print('Hello , %s.' % name) Hello = type('Hello',(object,),dict(hello=fn)) #要创建一个class对象,type()函数需要传入3个参数: #class的名称 #继承的父类的机会,Python支持多继承,如果只有一个父类,也要写成tuple的单元素的写法。 #class的方法名称与函数绑定,上述列子我们把函数fn绑定到方法名hello()上。
96ecc6d78dea8ae6abfb7123f10867092a0697cd
KatherineCG/TargetOffer
/3-相关题目.py
974
3.84375
4
class Solution: def SortInsert(self, a1, a2): if a1 == [] and a2 == []: return a1len = len(a1) a2len = len(a2) for i2 in range(a2len): for i1 in range(len(a1)): if a1[0] > a1[1]: if a2[i2] >= a1[i1]: a1.insert(i1, a2[i2]) break if a2[i2] <= a1[len(a1)-1]: a1.insert(len(a1), a2[i2]) break if a1[0] < a1[1]: if a2[i2] <= a1[i1]: a1.insert(i1, a2[i2]) break if a2[i2] >= a1[len(a1)-1]: a1.insert(len(a1), a2[i2]) break return a1 sortinsert = Solution() a1 = raw_input() a2 = raw_input() array1 = a1.split() array2 = a2.split() print sortinsert.SortInsert(array1, array2)
7443a803eb8dbb482fdb44a726b928adeb29a871
KatherineCG/TargetOffer
/24-二叉搜索树的后序遍历序列.py
925
3.765625
4
#coding=utf-8 #AC笔记:函数返回布尔值 class Solution(): def VerifySquenceOfBST(self, sequence): length = len(sequence) if length <= 0 or sequence == None: return False root = sequence[len(sequence)-1] for i in range(0, length): if sequence[i] > root: break for j in range(i, length): if sequence[j] < root: return False left = True if i > 0: left = self.VerifySquenceOfBST(sequence[:i]) right = True if i < length -1: right = self.VerifySquenceOfBST(sequence[i:length-1]) if left == right and left == True: return True else: return False sequence = input() test = Solution() result = test.VerifySquenceOfBST(sequence) if result == True: print 'true' else: print 'false'
676bc805b36c49dbfb1ecc01daa8b0eb50e63fce
KatherineCG/TargetOffer
/4-替换空格牛客.py
388
3.796875
4
# -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here if not s: return s res = '' for ch in s: if ch == ' ': res += '%20' else: res += ch return res test = Solution() s = raw_input() print test.replaceSpace(s)
ed0e02d164d7d65d7a132809961b80845439aed8
KatherineCG/TargetOffer
/45-圆圈中最后剩下的数字.py
489
3.59375
4
# -*- coding:utf-8 -*- class Solution: def LastRemaining_Solution(self, n, m): # write code here if n == 0 or m == 0: return -1 array = [i for i in range(n)] i = 0 while len(array) > 1: remainder = (m-1) % len(array) array = array[remainder+1:] + array[:remainder] return array[0] test = Solution() n = input() m = input() print test.LastRemaining_Solution(n, m)
fb19b66574d2de75d864c3e5b10abd3050346c8d
KatherineCG/TargetOffer
/27-二叉搜索树与双向链表.py
2,694
3.6875
4
# -*- coding:utf-8 -*- import re class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Convert(self, pRootOfTree): # write code here pLastNodeInList = None pLastNodeInList = self.ConvertNode(pRootOfTree, pLastNodeInList) pHeadOfList = pLastNodeInList while pLastNodeInList != None and pLastNodeInList.left != None: pHeadOfList = pLastNodeInList.left pLastNodeInList = pLastNodeInList.left return pHeadOfList def ConvertNode(self, pNode, pLastNodeInList): if pNode == None: return pCurrent = pNode if pCurrent.left != None: pLastNodeInList = self.ConvertNode(pCurrent.left, pLastNodeInList) pCurrent.left = pLastNodeInList if pLastNodeInList != None: pLastNodeInList.right = pCurrent pLastNodeInList = pCurrent if pCurrent.right != None: pLastNodeInList = self.ConvertNode(pCurrent.right, pLastNodeInList) return pLastNodeInList def HandleInput(data): data = re.sub('[{}]', '', data).split(',') pRoot = CreateBinaryTree(data, 0) return pRoot def CreateBinaryTree(data, n): if len(data) > 0: if n < len(data): if data[n] != '#': if (n+3) <= len(data) and data[n+1] == '#' and data[n+2] != '#': if n+3 == len(data) or data[n+3] == '#': l = n + 2 r = n + 3 else: l = 2 * n + 1 r = 2 * n + 2 pRoot = TreeNode(data[n]) pRoot.left = CreateBinaryTree(data, l) pRoot.right = CreateBinaryTree(data, r) return pRoot else: return None else: return None else: return None inputarray = raw_input() test = Solution() resultltor = '' resultrtol = '' if inputarray == '{}': print None else: pRootHead = HandleInput(inputarray) pLastNodeInList = test.Convert(pRootHead) while pLastNodeInList.left != None: resultrtol = resultrtol + pLastNodeInList.val + ',' pLastNodeInList = pLastNodeInList.left resultrtol = resultrtol + pLastNodeInList.val + ',' while pLastNodeInList != None: resultltor = resultltor + pLastNodeInList.val + ',' pLastNodeInList = pLastNodeInList.right print 'From left to right are:' + resultltor[:len(resultltor)-1] + ';From right to left are:' + resultrtol[:len(resultrtol) - 1] + ';'
586de144105ea4e2cd2f0358e08cd6d4eee20714
KatherineCG/TargetOffer
/29.1-数组中出现超过一半的数字.py
1,148
3.578125
4
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here if self.CheckInvalidArray(numbers): return 0 number = numbers[0] times = 1 for i in range(1,len(numbers)): if numbers[i] == number: times += 1 else: times -= 1 if times == 0: number = numbers[i] times = 1 if self.ChedkMoreThanHalf(numbers, number): return number else: return 0 def CheckInvalidArray(self, numbers): g_bInputInvalid = False if numbers == [] and len(numbers) <= 0 : g_bInputInvalid = True return g_bInputInvalid def ChedkMoreThanHalf(self, numbers, number): times = 0 for i in range(len(numbers)): if numbers[i] == number: times += 1 if times > len(numbers)/2: return True else: return False test = Solution() numbers = input() print test.MoreThanHalfNum_Solution(numbers)
dc06c6c46c4c9c07f2ea7c75cc3a486f1fd4f9fc
KatherineCG/TargetOffer
/3-二维数组的查找.py
1,681
3.96875
4
# coding=utf-8 ''' 在一个二维数组中,每一行都按照从左到右递增的顺序排序 每一列都按照从上到下递增的顺序排序。 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 ''' ''' 查找方式从右上角开始查找 如果当前元素大于target, 左移一位继续查找 如果当前元素小于target, 下移一位继续查找 进行了简单的修改, 可以判定输入类型为字符的情况 ''' class Solution: def Find(self, array, target): if array == []: return False rawnum = len(array) colnum = len(array[0]) if type (target) == float and type (array[0][0]) == int: target = int(target) elif type (target) == int and type (array[0][0]) == float: target = float(target) elif type (target) != type (array[0][0]): return False i = colnum - 1 j = 0 while i >=0 and j < rawnum: if array[j][i] < target: j += 1 elif array[j][i] > target: i -= 1 else: return True return False ''' array = [[1,2,8,9], [2,4,9,12], [4,7,10,13], [6,8,11,15]] ''' target = int(input()) n=int(raw_input("please input the raw number:")) m = int(raw_input("please input the colnum number:")) array= [[0 for col in range(m)] for row in range(n)] for i in range(n): for j in range(m): array[i][j] = int(input()) findtarget = Solution() print(findtarget.Find(array, target))
e8e5aadff96ec0b43260a3f7503e459fbdd88161
KatherineCG/TargetOffer
/33-把数组排成最小的数.py
1,104
3.703125
4
# -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here if not numbers: minnum = '' else: length = len(numbers) numbers = map(str, numbers) self.Compare(numbers, 0, length-1) minnum = ''.join(numbers) return minnum def Compare(self, numbers, start, end): if start >= end: return numbers key = numbers[start] low = start high = end while start < end : while start < end and int(key + numbers[end]) <= int(numbers[end] + key): end -= 1 while start < end and int(key + numbers[end]) > int(numbers[end] + key): numbers[start] = numbers[end] start += 1 numbers[end] = numbers[start] numbers[start] = key self.Compare(numbers, low, start) self.Compare(numbers, start+1, high) return numbers test = Solution() numbers = input() print test.PrintMinNumber(numbers)
f6c4fb4ad8819c4706d19709aa5955c0221bf3a5
KatherineCG/TargetOffer
/13-在O(1)时间删除链表结点.py
1,358
3.78125
4
# coding=utf-8 class ListNode: def __init__(self, data, next = None): self.data = data self.next = None def __del__(self): self.data = None self.next = None class Solution: def __init__(self): self.head = None def DeleteNode(self, pListHead, pToBeDeleted): if not pListHead or not pToBeDeleted: return None #中间结点 if pToBeDeleted.next != None: p = pToBeDeleted.next pToBeDeleted.data = p.data pToBeDeleted.next = p.next p.__del__() #头结点 elif pToBeDeleted == pListHead: pListHead = pToBeDeleted.next pToBeDeleted.__del__() #尾结点 else: p = pListHead while p.next != pToBeDeleted: p = p.next p.next = None pToBeDeleted.__del__() #输出链表 def PrintLinkList(self, pListHead): while pListHead != None: print pListHead.data pListHead = pListHead.next node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node1.next = node2 node2.next = node3 test = Solution() test.PrintLinkList(node1) test.DeleteNode(node1, node3) test.PrintLinkList(node1)
44869bc89939ee9719d4955b5ba8f24542d9df35
KatherineCG/TargetOffer
/13-调整数组顺序使奇数位于偶数前面.py
481
3.671875
4
# -*- coding:utf-8 -*- ''' 用两个列表,一个存储奇数,一个存储偶数 返回奇数列表+偶数列表 ''' class Solution: def reOrderArray(self, array): # write code here if not array: return [] evenres = [] oddres = [] for ch in array: if ch % 2 == 0: evenres.append(ch) else: oddres.append(ch) return oddres + evenres
4f2e3b81459c7de30038d44b7232fea76c621e36
Z3roTwo/GuessTheNumber
/GuessTheNumber.py
1,335
3.796875
4
import random import json loop = True guess = 0 number = 0 rounds = 0 name = 0 #q = 0 name = input("Display name: ") number = random.randint(1, 10) #try: #with open('Storage.json', 'r') as JSON: #data = json.load(JSON) #type(data) #print(data["name"]) #q = data[rounds] #except: #print("2qerrqwreasdf") # Debug thingy # print(number) print(f"Ok {name} the PC have selected a number between 1 - 10") while loop: try: guess = int(input("Your guess: ")) rounds += 1 if guess > number: print("Aw too bad that's the wrong number, it's too high! :(") elif guess < number: print("Aw too bad that's the wrong number, it's to low! :(") elif guess == number: print(f"Congrats you did it! The number was {number} and it only took you {rounds} rounds :D") loop = False #if rounds < int(q): #x = {"name": name, "rounds": rounds} # Sparar x i Storage.json #f = open('Storage.json', 'w') #json.dump(x, f) # Stänger filen #f.close() else: print("Oops something went wrong and the code didn't crash for some reason....") except: print("Please enter a number between 1 and 10")
dff00f606c61a85f97eadf87e8a939121ed22462
mananaggarwal2001/The-Perfect-Guess-Game
/project2-the_perfect_guess.py
999
4.03125
4
import os import random randInt = random.randint(1, 100) userGuess = None Gussess = 0 highScore=None while(userGuess != randInt): userGuess = int(input("Enter Your Guess: ")) if(userGuess == randInt): print("You Guessed it Right") else: if userGuess > randInt: print("Your guesss it Wrong! You have made the larger guess") else: print("Your guess it wrong! You have made the smaller guess") Gussess += 1 print(f"The Number of Gusssess for the Right answer the user made is {Gussess}") with open("highScore.txt", "r") as f: highScore = f.read() if(Gussess < int(highScore)): with open("highScore.txt","w") as f: f.write(str(Gussess)) print(f"You have broken the high Score and the updated high Score for the Number of gussess is {Gussess}") else: print(f"The highest Number of the Guessess the user made for the right answer is :{highScore} ")
25001af33ac7a663e5f20810c42d5cba3ac73242
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/FinalCourseAssignment/pro5.py
620
4.15625
4
#Provided is a list of data about a store’s inventory where each item #in the list represents the name of an item, how much is in stock, #and how much it costs. Print out each item in the list with the same #formatting, using the .format method (not string concatenation). #For example, the first print statment should read The store has 12 shoes, each for 29.99 USD. inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"] item =[] for inv in inventory: item = inv.split(", ") print("The store has {} {}, each for {} USD.".format(item[1], item[0], item[2]))
a53c2faa1c8da8d9f736720d2f653811898ea67a
AhmedElkhodary/Python-3-Programming-specialization
/1- Python Basics/Week4/pro3.py
256
4.3125
4
# For each character in the string already saved in # the variable str1, add each character to a list called chars. str1 = "I love python" # HINT: what's the accumulator? That should go here. chars = [] for ch in str1: chars.append(ch) print(chars)
0362c1ae9a526f1ba7b5923d7e28e1d043648556
ContextLab/quail
/docs/_build/html/_downloads/plot_pnr.py
515
3.625
4
# -*- coding: utf-8 -*- """ ============================= Plot probability of nth recall ============================= This example plots the probability of an item being recalled nth given its list position. """ # Code source: Andrew Heusser # License: MIT # import import quail #load data egg = quail.load_example_data() # analysis analyzed_data = quail.analyze(egg, analysis='pnr', listgroup=['average']*8, position=5) # plot quail.plot(analyzed_data, title='Probability of Recall')
a92b0b7e4b40c97f9dcc7aa74f342b4727212f96
Aakaaaassh/Coding
/Greedy_florist.py
555
3.734375
4
n,x = list(map(int,input().split())) list1 = [] for i in range(n): y = int(input("enter price of flower")) list1.append(y) print("number of flowers are " + str(n) + " and their prices are ", list1) Buyer = x print("Number of buyers are :", Buyer) res = sorted(list1, reverse=True) print(res) def TotalPrice(res): count = 0 price = 0 k = 1 for i in res: count += 1 price = price + k*i if count == Buyer: k += 1 return price print(TotalPrice(res))
c3a03b2fda7d388c9626f9a9213d49239e659d67
Aakaaaassh/Coding
/kth_smallest_element.py
318
3.65625
4
n = int(input("Enter no. of test cases: ")) list2 = [] for i in range(n): a = int(input("Enter size of array: ")) list1 = list(map(int, input().split())) k = int(input("Enter kth smallest element: ")) res = sorted(list1) res = res[k-1] list2.append(res) for i in list2: print(i)
fba8df5f519498639cd582e945b592200227eaf6
IbrahimIrfan/ctci
/1/7.py
580
3.78125
4
# O(M*N) in place def set0(matrix): rows = set() cols = set() m = len(matrix) n = len(matrix[0]) #O(M*N) for r in range(0, m): for c in range(0, n): # O(1) if (matrix[r][c] == 0): rows.update([r]) cols.update([c]) # O(M*N) for r in range(0, m): for c in range(0, n): if (r in rows) or (c in cols): matrix[r][c] = 0 return matrix matrix = [ [0,2,3], [4,5,6], [7,8,9], ] print set0(matrix)
80a40c327baf5f1e7f3e287815d584918410124a
golbeck/PythonExercises
/NeuralNets/MLP pure numpy/NeuralNetV1.py
9,514
3.984375
4
#implements logistic classification #example: handwriting digit recognition, one vs. all import numpy as np import os #################################################################################### #################################################################################### def grad_cost(bias,theta,X,Y,eps): #computes the gradient with respect to the parameters (theta) of the logistic regression model #bias: 0: no bias; 1: bias term #theta: np.array of parameters #X: np.array of inputs (each of the m rows is a separate observation) #Y: np.array of outpus #eps: regularization constant (set to zero if unregularized) #dimension of data #number of rows (observations) n=X.shape[0] #number of columns (features + bias) m=X.shape[1] #number of rows in the dependent variable n_Y=Y.shape[0] #check if X and Y have the same number of observations if(n!=n_Y): print "number of rows in X and Y are not the same" return -9999. #compute logistic function g=1/(1+np.exp(-np.dot(X,theta))) #only the non-bias features are in the regularization terms in the cost func theta_reg=np.copy(theta) if(bias==1): theta_reg[0]=0.0 #gradient with respect to theta J_grad=(np.dot(X.T,g-Y)+eps*theta_reg)/n return J_grad #################################################################################### #################################################################################### def cost_fn(bias,theta,X,Y,eps): #cost function for logistic regression #bias: 0: no bias; 1: bias term #theta: np.array of parameters #X: np.array of inputs (each of the m rows is a separate observation) #Y: np.array of outpus #eps: regularization constant (set to zero if unregularized) #dimension of data #number of rows (observations) n=X.shape[0] #number of columns (features + bias) m=X.shape[1] #number of rows in the dependent variable n_Y=Y.shape[0] #check if X and Y have the same number of observations if(n!=n_Y): print "number of rows in X and Y are not the same" return -9999. #only the non-bias features are in the regularization terms in the cost func theta_reg=np.copy(theta) if(bias==1): theta_reg[0]=0.0 #compute logistic function g=1/(1+np.exp(-np.dot(X,theta))) #log likelihood func temp0=-np.log(g)*Y-np.log(1-g)*(1-Y) temp1=theta_reg**2 J=(temp0.sum(axis=0)+0.5*eps*temp1.sum(axis=0))/n return J #################################################################################### #################################################################################### def prob_logistic_pred(theta,X): #theta: np.array of parameters #X: np.array of inputs (each of the m rows is a separate observation) #compute logistic function g=1/(1+np.exp(-np.dot(X,theta))) y_out=g>0.5 y=np.column_stack((g,y_out)) return y #################################################################################### #################################################################################### def fit_logistic_class(bias,theta,X,y,eps,tol,k_max): #theta: np.array of parameters #bias: 0: no bias; 1: bias term #X: np.array of inputs (each of the m rows is a separate observation) #y: np.array of outputs #eps: regularization constant (set to zero if unregularized) #tol: stopping tolerance for change in cost function #k_max: maximum number of iterations for gradient descent #compute logistic function J=cost_fn(bias,theta,X,Y,eps) k=0 abs_diff=1e8 while((abs_diff>tol)&(k<k_max)): theta-=grad_cost(bias,theta,X,Y,eps) J_new=cost_fn(bias,theta,X,Y,eps) abs_diff=abs(J-J_new) J=J_new k+=1 # print k,J return theta #################################################################################### #################################################################################### def confusion_matrix(y_out,y): #compute logistic function m=y.shape[0] tempTP=0 tempTN=0 tempFP=0 tempFN=0 for i in range(m): if(y_out[i]==y[i]): if(y[i]==1.): tempTP+=1 else: tempTN+=1 if(y_out[i]!=y[i]): if(y_out[i]==1.): tempFP+=1 else: tempFN+=1 CF=np.array([[tempTP,tempFN],[tempFP,tempTN]]) return CF #################################################################################### #################################################################################### def confusion_matrix_multi(y_out,y,n_class): #compute logistic function m=y.shape[0] tempTP=0 tempTN=0 tempFP=0 tempFN=0 #rows: actual class label #cols: predicted class label CF=np.zeros((n_class,n_class)) for i in range(m): if(y_out[i]==y[i]): CF[y[i]-1,y[i]-1]+=1 else: CF[y[i]-1,y_out[i]-1]+=1 return CF #################################################################################### #################################################################################### pwd_temp=%pwd dir1='/home/sgolbeck/workspace/PythonExercises/NeuralNets' if pwd_temp!=dir1: os.chdir(dir1) dir1=dir1+'/data' dat=np.loadtxt(dir1+'/ex2data1.txt',unpack=True,delimiter=',',dtype={'names': ('X1', 'X2', 'Y'),'formats': ('f4', 'f4', 'i4')}) n=len(dat) Y=dat[n-1] m=len(Y) X=np.array([dat[i] for i in range(n-1)]).T #de-mean and standardize data X=(X-X.mean(0))/X.std(0) #add in bias term X=np.column_stack((np.ones(m),np.copy(X))) tol=1e-6 k_max=400 theta=np.random.normal(size=n) eps=0.1 k_max=400 k=0 bias=1 theta=fit_logistic_class(bias,theta,X,Y,eps,tol,k_max) y_out=prob_logistic_pred(theta,X)[:,1] print confusion_matrix(y_out,Y) #################################################################################### #################################################################################### #compare to statsmodels logistic regression method import statsmodels.api as sm from sklearn.metrics import confusion_matrix # fit the model logit=sm.Logit(Y,X) result=logit.fit() #classify if prediction > 0.5 Y_out=result.predict(X) Y_out_ind=Y_out>0.5 #confusion matrix cm = confusion_matrix(Y,Y_out_ind) print(cm) #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### import scipy.io as sio dat=sio.loadmat(dir1+'/ex3data1.mat') Y_all=np.array(dat['y']) #reshape to 1d np.array Y_all=Y_all.ravel() X=np.array(dat['X']) m=X.shape[0] n=X.shape[1] #add in bias term bias=1 if(bias==1): n=X.shape[1]+1 X=np.column_stack((np.ones(m),np.copy(X))) tol=1e-6 eps=0.1 k_max=10000 k=0 Y_class=np.arange(1,11) prob_out=np.zeros((m,10)) for i in Y_class: Y=(Y_all==i).astype(int) theta=np.random.normal(size=n) theta=fit_logistic_class(bias,theta,X,Y,eps,tol,k_max) y=prob_logistic_pred(theta,X) prob_out[:,i-1]=y[:,0] Y_out=prob_out.argmax(axis=1)+1 CM=confusion_matrix_multi(Y_out,Y_all,10) print CM error_rate=CM.diagonal().sum(0)/m print error_rate #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### Y_class=np.arange(1,11) prob_out_skl=np.zeros((m,10)) for i in Y_class: Y=(Y_all==i).astype(int) logit=sm.Logit(Y,X) result=logit.fit() #classify if prediction > 0.5 Y_out=result.predict(X) prob_out_skl[:,i-1]=Y_out_ind Y_out_skl=prob_out_skl.argmax(axis=1)+1 CM=confusion_matrix_multi(Y_out_skl,Y_all,10) #################################################################################### #################################################################################### #################################################################################### #################################################################################### #################################################################################### from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC Y_out_SVC=OneVsRestClassifier(LinearSVC(random_state=0)).fit(X, Y_all).predict(X) cm = confusion_matrix(Y_all,Y_out_SVC) print(cm)
453a816c318a213493b5f6cc9cd9ca2567ae55b9
golbeck/PythonExercises
/twitter/tweet_parserV1.py
5,928
3.6875
4
import oauth2 as oauth import urllib2 as urllib import numpy as np from pandas import DataFrame, Series import pandas as pd import json # See Assignment 1 instructions or README for how to get these credentials access_token_key = "89257335-W8LCjQPcTMIpJX9vx41Niqe5ecMtw0tf2m65qsuVn" access_token_secret = "5tmU9RDxP3tiFShmtDcFE5VVzWy7dGBRvvDp6uwoZWyW2" consumer_key = "qknqCAZAOOcpejiYkyYZ00VZr" consumer_secret = "xQM8ynjjXQxy6jWus4qTlCDEPItjZyxqhnAEbbmmUj2Q1JlX5w" _debug = 0 oauth_token = oauth.Token(key=access_token_key, secret=access_token_secret) oauth_consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() http_method = "GET" http_handler = urllib.HTTPHandler(debuglevel=_debug) https_handler = urllib.HTTPSHandler(debuglevel=_debug) ''' Construct, sign, and open a twitter request using the hard-coded credentials above. ''' def twitterreq(url, method, parameters): req = oauth.Request.from_consumer_and_token(oauth_consumer, token=oauth_token, http_method=http_method, http_url=url, parameters=parameters) req.sign_request(signature_method_hmac_sha1, oauth_consumer, oauth_token) headers = req.to_header() if http_method == "POST": encoded_post_data = req.to_postdata() else: encoded_post_data = None url = req.to_url() opener = urllib.OpenerDirector() opener.add_handler(http_handler) opener.add_handler(https_handler) response = opener.open(url, encoded_post_data) return response def fetchsamples(feed,max_id): #to build a query, see: #https://dev.twitter.com/docs/using-search # feed: string containing the term to be searched for (see above link) # max_id: string with the ID of the most recent tweet to include in the results # url = "https://api.twitter.com/1.1/search/tweets.json?q=" url="https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" url=url+feed #download the maximum number of tweets url=url+'&count=200' url=url+'&exclude_replies=true' url=url+'&include_rts=false' if len(max_id)>0: url=url+'&max_id='+max_id parameters = [] response = twitterreq(url, "GET", parameters) return json.load(response) feed='from%3Acnbc' feed='cnn' response=fetchsamples(feed,'') temp=response.keys() DF0=DataFrame(response[str(temp[1])]) count=len(DF0.index) max_id=int(min(DF0.ix[:,'id']))-1 while count <= 3200: if len(str(max_id))>0: response=fetchsamples(feed,str(max_id)) count0=len(response[str(temp[1])]) print count0 DF1=DataFrame(response[str(temp[1])],index=range(count,count+count0)) DF0=pd.concat([DF0,DF1]) print DF0.index max_id=int(min(DF0.ix[:,'id']))-1 print max_id count+=count0 print count for i in range(0,len(response['statuses'])): #twitter screen name print response['statuses'][i]['user']['screen_name'] #name of the user # print response['statuses'][i]['user']['name'] #time and date at which tweet was created print response['statuses'][i]['created_at'] #The UTC datetime that the user account was created on Twitter # print response['statuses'][i]['user']['created_at'] #unique id code for the user # print response['statuses'][i]['user']['id'] #unique id code for the user print response['statuses'][i]['text'] feed='from%3Acnbc' feed='from%3Acnn' response=fetchsamples(feed,'') temp=response.keys() DF0=DataFrame(response[str(temp[1])]) count=len(DF0.index) max_id=int(min(DF0.ix[:,'id']))-1 response=fetchsamples(feed,str(max_id)) count0=len(response[str(temp[1])]) print count0 DF1=DataFrame(response[str(temp[1])],index=range(count,count+count0)) DF0=pd.concat([DF0,DF1]) print DF0.index max_id=int(min(DF0.ix[:,'id']))-1 print max_id count+=count0 print count for i in range(0,len(response['statuses'])): #twitter screen name print response['statuses'][i]['user']['screen_name'] #name of the user # print response['statuses'][i]['user']['name'] #time and date at which tweet was created print response['statuses'][i]['created_at'] #The UTC datetime that the user account was created on Twitter # print response['statuses'][i]['user']['created_at'] #unique id code for the user # print response['statuses'][i]['user']['id'] #unique id code for the user print response['statuses'][i]['text'] for line in response: print line.strip() if __name__ == '__main__': fetchsamples() #def fetchsamples(): # url = "https://api.twitter.com/1.1/search/tweets.json?q=microsoft" # parameters = [] # response = twitterreq(url, "GET", parameters) # return json.load(response) ## for line in response: ## print line.strip() ##if __name__ == '__main__': ## fetchsamples() myResults = fetchsamples() #print type(myResults) #print myResults.keys() #print myResults["statuses"] #print type(myResults["statuses"]) results = myResults["statuses"] #print results[0] #print type(results[0]) #print results[0].keys() #print results[0]["text"] #print results[2]["text"] #print results[5]["text"] #for i in range(10): # print results[i]["text"] ############################################### #build dictionary afinnfile = open("AFINN-111.txt") scores = {} for line in afinnfile: term, score = line.split("\t") scores[term] = float(score) #print scores.items() ############################################### #read in tweets and save into a dictionary atweetfile = open("output.txt") tweets = [] for line in atweetfile: try: tweets.append(json.loads(line)) except: pass print len(tweets) tweet = tweets[0] print type(tweet) print tweet.keys() print type(tweet["text"]) print tweet["text"]
57df74cd1011bcce2d372806326c2f61adc6ea14
naveen-kulkarni0/tensorflow
/flower-classification-tensorflow/data-genr.py
3,608
3.890625
4
"""# Data Loading In order to build our image classifier, we can begin by downloading the flowers dataset. We first need to download the archive version of the dataset and after the download we are storing it to "/tmp/" directory. After downloading the dataset, we need to extract its contents. """ _URL = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" zip_file = tf.keras.utils.get_file(origin=_URL, fname="flower_photos.tgz", extract=True) base_dir = os.path.join(os.path.dirname(zip_file), 'flower_photos') """The dataset we downloaded contains images of 5 types of flowers: 1. Rose 2. Daisy 3. Dandelion 4. Sunflowers 5. Tulips So, let's create the labels for these 5 classes: """ classes = ['roses', 'daisy', 'dandelion', 'sunflowers', 'tulips'] """Also, the dataset we have downloaded has following directory structure. <pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" > <b>flower_photos</b> |__ <b>daisy</b> |__ <b>dandelion</b> |__ <b>roses</b> |__ <b>sunflowers</b> |__ <b>tulips</b> </pre> As you can see there are no folders containing training and validation data. Therefore, we will have to create our own training and validation set. Let's write some code that will do this. The code below creates a `train` and a `val` folder each containing 5 folders (one for each type of flower). It then moves the images from the original folders to these new folders such that 80% of the images go to the training set and 20% of the images go into the validation set. In the end our directory will have the following structure: <pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" > <b>flower_photos</b> |__ <b>daisy</b> |__ <b>dandelion</b> |__ <b>roses</b> |__ <b>sunflowers</b> |__ <b>tulips</b> |__ <b>train</b> |______ <b>daisy</b>: [1.jpg, 2.jpg, 3.jpg ....] |______ <b>dandelion</b>: [1.jpg, 2.jpg, 3.jpg ....] |______ <b>roses</b>: [1.jpg, 2.jpg, 3.jpg ....] |______ <b>sunflowers</b>: [1.jpg, 2.jpg, 3.jpg ....] |______ <b>tulips</b>: [1.jpg, 2.jpg, 3.jpg ....] |__ <b>val</b> |______ <b>daisy</b>: [507.jpg, 508.jpg, 509.jpg ....] |______ <b>dandelion</b>: [719.jpg, 720.jpg, 721.jpg ....] |______ <b>roses</b>: [514.jpg, 515.jpg, 516.jpg ....] |______ <b>sunflowers</b>: [560.jpg, 561.jpg, 562.jpg .....] |______ <b>tulips</b>: [640.jpg, 641.jpg, 642.jpg ....] </pre> Since we don't delete the original folders, they will still be in our `flower_photos` directory, but they will be empty. The code below also prints the total number of flower images we have for each type of flower. """ for cl in classes: try: img_path = os.path.join(base_dir, cl) images = glob.glob(img_path + '/*.jpg') print("{}: {} Images".format(cl, len(images))) train, val = images[:round(len(images)*0.8)], images[round(len(images)*0.8):] for t in train: if not os.path.exists(os.path.join(base_dir, 'train', cl)): os.makedirs(os.path.join(base_dir, 'train', cl)) shutil.move(t, os.path.join(base_dir, 'train', cl)) for v in val: if not os.path.exists(os.path.join(base_dir, 'val', cl)): os.makedirs(os.path.join(base_dir, 'val', cl)) shutil.move(v, os.path.join(base_dir, 'val', cl)) except: print("File already exists") """For convenience, let us set up the path for the training and validation sets""" train_dir = os.path.join(base_dir, 'train') val_dir = os.path.join(base_dir, 'val')
5be89cf95fc14294714788db895b2f1ebfc3156b
DiegoCol93/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
192
3.78125
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): a_new_dictionary = a_dictionary.copy() for value in a_dictionary: a_new_dictionary[value] *= 2 return(a_new_dictionary)
a1b182cd04c27dc9c000923a627c7e6cb2a2ff3b
DiegoCol93/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,275
4.25
4
#!/usr/bin/python3 """ Module for storing the Square class. """ from models.rectangle import Rectangle from collections import OrderedDict class Square(Rectangle): """ Por Esta no poner esta documentacion me cague el cuadrado :C """ # __init__ | Private | method |-------------------------------------------| def __init__(self, size, x=0, y=0, id=None): """ __init__: Args: size(int): Size of the Square object. x(int): Value for the offset for display's x position. y(int): Value for the offset for display's y position. """ super().__init__(size, size, x, y, id) # __str__ | Private | method |--------------------------------------------| def __str__(self): """ Returns the string for the Rectangle object """ return "[Square] ({}) {}/{} - {}".format(self.id, self.x, self.y, self.width) # update | Public | method |----------------------------------------------| def update(self, *args, **kwargs): """ Updates all attributes of the Rectangle object. """ if bool(args) is True and args is not None: try: self.id = args[0] self.size = args[1] self.x = args[2] self.y = args[3] except Exception as e: pass else: for i in kwargs.keys(): if i in dir(self): setattr(self, i, kwargs[i]) # to_dictionary | Public | method |---------------------------------------| def to_dictionary(self): """ Returns the dictionary representation of a Square object. """ ret_dict = OrderedDict() ret_dict["id"] = self.id ret_dict["size"] = self.width ret_dict["x"] = self.x ret_dict["y"] = self.y return dict(ret_dict) # Set & Get __width | Public | method |------------------------------------ @property def size(self): """ Getter of the Rectangle's width value. """ return self.width @size.setter def size(self, number): """ Setter of the Rectangle's width value. """ self.width = number self.height = number
dec9ef388badcb3f32458c369c96a74e7f132c90
DiegoCol93/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
303
3.921875
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): if my_list: list_TF = [] index = 0 for i in my_list: if i % 2 == 0: list_TF.append(True) else: list_TF.append(False) index += 1 return list_TF
49e4ff54cc9940d752f512059d312e3be381c885
DiegoCol93/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
238
3.9375
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): new_list = my_list.copy() i = 0 while i < len(my_list): if my_list[i] == search: new_list[i] = replace i += 1 return new_list
b6474efae6cd4d892f987547912e85c73bb9fb0e
limelier/advent-of-code-2020
/19/main.py
2,233
3.640625
4
import re from typing import List def get_input(): rules = {} with open('input.txt') as file: for line in file: line = line.strip() if line: index, contents = line.split(':') index = int(index) contents = contents.strip() if '"' in contents: # if literal, extract letter contents = contents[1] else: if '|' not in contents: contents = [int(num) for num in contents.split(' ')] else: cont1, cont2 = contents.split(' | ') cont1 = [int(num) for num in cont1.split(' ')] cont2 = [int(num) for num in cont2.split(' ')] contents = cont1, cont2 rules[index] = contents else: break strings = [line.strip() for line in file] return rules, strings def collapse_rules(rules, root=0): rule = rules[root] if isinstance(rule, str): return rule elif isinstance(rule, List): return ''.join(collapse_rules(rules, idx) for idx in rule) else: left, right = rule left = ''.join(collapse_rules(rules, idx) for idx in left) right = ''.join(collapse_rules(rules, idx) for idx in right) return f'({left}|{right})' def part_1(): rules, strings = get_input() pattern = collapse_rules(rules) regex = re.compile(r'^' + pattern + r'$') print(sum(1 for string in strings if regex.fullmatch(string))) def part_2(): rules, strings = get_input() # rule 0: (8)(11) = (42){n}(42){m}(31){m} = (42){m+n}(31){m} # a{m+n}b{m} is not possible with pure regex, so we will test for different values of m up to 50 rule_31 = collapse_rules(rules, 31) rule_42 = collapse_rules(rules, 42) regexes = [ re.compile('^' + rule_42 + '+' + rule_42 + '{' + str(i) + '}' + rule_31 + '{' + str(i) + '}$') for i in range(1, 51) ] print(sum(1 for string in strings if any(regex.fullmatch(string) for regex in regexes))) if __name__ == '__main__': part_1() part_2()
b220a0f233abe8c47401f5f91da93abc776434f1
Jokerzhai/OpenCVPython
/test2/UsingMatplotlib.py
445
3.546875
4
#Matplotlib is a plotting library for Python which gives you wide variety of plotting methods. # You will see them in coming articles. Here, you will learn how to display image with Matplotlib. # You can zoom images, save it etc using Matplotlib. import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('board.jpg',0) plt.imshow(img,cmap = 'gray',internpolation = 'bicubic') plt.xticks([]),plt.yticks([]) plt.show()
e4e7696f0a6eb2eeec5a62723bb85bbcc2fd96b6
manasakandimalla/ICG-Lab
/Lab_5/transition.py
337
3.9375
4
import matplotlib.pyplot as plt import math def translation(x,y,h,k): plt.plot(x,y,marker = 'o') plt.plot(x+h,y+k,marker='o') print "enter the co-ordinates of point :" x0 = input() y0 = input() print "enter the co-ordinates of the new origin :" h = input() k = input() translation(x0,y0,h,k) plt.axis([-10,10,-10,10]) plt.show()
1c226cd18e417faf1cc865499b4f801b0481f6a2
nrvanwyck/DS-Unit-3-Sprint-2-SQL-and-Databases
/SC/demo_data.py
1,207
3.859375
4
import sqlite3 conn = sqlite3.connect("demo_data.sqlite3") curs = conn.cursor() create_demo_table = """ CREATE TABLE demo ( s TEXT, x INT, y INT ); """ curs.execute(create_demo_table) insert_row = """ INSERT INTO demo (s, x, y) VALUES ('g', 3, 9);""" curs.execute(insert_row) insert_row = """ INSERT INTO demo (s, x, y) VALUES ('v', 5, 7);""" curs.execute(insert_row) insert_row = """ INSERT INTO demo (s, x, y) VALUES ('f', 8, 7);""" curs.execute(insert_row) conn.commit() query = """ SELECT COUNT(*) FROM demo;""" row_count = curs.execute(query).fetchall()[0][0] query = """ SELECT COUNT(*) FROM demo WHERE x >= 5 AND y >=5;""" x_and_y_at_least_5_count = curs.execute(query).fetchall()[0][0] query = """ SELECT COUNT(DISTINCT y) FROM demo;""" unique_y_count = curs.execute(query).fetchall()[0][0] curs.close() print("Number of rows:", row_count, "\nNumber of rows where both x and y are at least 5:", x_and_y_at_least_5_count, "\nNumber of unique y values:", unique_y_count) # Output: # Number of rows: 3 # Number of rows where both x and y are at least 5: 2 # Number of unique y values: 2
3160db69d05f0aed6bbc63f9b2b84020ef4343e0
CorSar5/Python-World2
/exercícios 36-71/ex051.py
209
3.765625
4
num = int(input('Primeiro termo: ')) r = int(input('Indique a razão da PA(Progressão Aritmética)')) décimo = num +(10-1)*r for c in range(num,décimo,r): print('{}'.format(c), end='->') print('ACABOU')
31a9968211779836bb0e80e1f2c698f69db92b28
CorSar5/Python-World2
/exercícios 36-71/ex049.py
99
3.796875
4
t = int(input('Digite um número:')) for n in range(1,11): print(f'{n}*{t} é igual a {n * t}')
7496d32ad90fe4e113b616d72ee8773c9a923897
CorSar5/Python-World2
/exercícios 36-71/ex050.py
274
3.796875
4
soma = 0 cont = 0 print('Peço-lhe que me indique 6 números') for c in range(1, 7): num = int(input(f'Digite o {c}º valor: ')) if num %2 ==0: soma += num cont += 1 print('Deu {} números pares e a soma dos números pares foi {}.'.format(cont,soma))
cf09393ec6a76c29cdd9ba6b187edc1121fe612b
CorSar5/Python-World2
/exercícios 36-71/ex052.py
220
4.15625
4
n = int(input('Escreva um número: ')) if n % 2 == 0 or n % 3 == 0 or n % 5== 0 or n % 7 == 0: print('Esse número {} não é um número primo'.format(n)) else: print('O número {} é um número primo'.format(n))
a9b43780275bd7e9d95650b80cf984f2619f60ea
SjoerdvanderHeijden/endless-ql
/Jordy_Dennis/QL/expressionnode.py
8,583
4.21875
4
""" An expression can be a single variable, or a combination of a variables with an operator (negation) and multiple other expressions. All of the types are comparable with boolean operators: If the variable is 0 or unset, the variable will be converted to a boolean False, True otherwise (just like python does it) Only numerical values will be accepted for comparison operations such as >, <, <=, etc, Mathematical operations are can also only be performed on numbers (so no + for strings), the exception to this rule is the != and ==, which can be applied to any child as long as they have the same type An error will be thrown if the types are incomparible """ from .ast_methods import * """ Expressions with a left and right side, all of the operators that cause this node to exist are listed in the constructor """ class BinaryNode: def __init__(self, left, right, op, line): self.left = left self.right = right self.op = op self.line = line self.numOps = ["<", "<=", ">", ">="] self.arithmeticOps = ["+", "-", "/", "*"] self.allOps = ["!=", "=="] self.boolOps = ["and", "or"] """ Check the actual expression type """ def checkTypes(self): leftType = self.left.checkTypes() rightType = self.right.checkTypes() # Compare for the numOp (check that both types are floats/ints), we always return a bool in this case if self.op in self.numOps: goodType, expType = self.typeCompareNumOp(leftType, rightType) if goodType: return bool else: errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str( self.line) throwError(errorstring) # Check if both children are of a numerical type, and return the type (compareOp) elif self.op in self.arithmeticOps: goodType, expType = self.typeCompareNumOp(leftType, rightType) if goodType: return expType else: errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str( self.line) throwError(errorstring) # Boolean operators can always be compared # (unset or set is converted to True and False) so we do not need a function to check the types serperately elif self.op in self.boolOps: return bool # check it for == and !=, which are boolean operators elif self.op in self.allOps: return self.typeCompareAllOp(leftType, rightType) else: errorstring = "Unknown operator at line " + str(self.line) throwError(errorstring) """ Check if both types are numerical (int or float), return true, and if they are not of the same type, return float (a.k.a convert the int) """ def typeCompareNumOp(self, leftType, rightType): if leftType == float and rightType == float: return True, float elif leftType == float and rightType == int: return True, float elif leftType == int and rightType == float: return True, float elif leftType == int and rightType == int: return True, int else: return False, None """ Only return the the bool if they are not the same, otherwise throw an error, the only exception are numericals since we can compare an converted int to a float """ def typeCompareAllOp(self, leftType, rightType): goodType, _ = self.typeCompareNumOp(leftType, rightType) if goodType: return bool elif leftType == rightType: return bool else: errorstring = "Incomparible types: " + str(leftType) + " and " + str(rightType) + "; at line " + str( self.line) throwError(errorstring) """ Call linkVars for children """ def linkVars(self, varDict): self.left.linkVars(varDict) self.right.linkVars(varDict) """ Evaluate expression """ def evaluate(self): left_exp = self.left.evaluate() right_exp = self.right.evaluate() return eval(str(left_exp) + " " + self.op + " " + str(right_exp)) # Return string representation of expression for DEBUG def getName(self): return str(self.left.getName()) + self.op + str(self.right.getName()) def __repr__(self): return "Binop: {} {} {}".format(self.left, self.op, self.right) """ Class for expressions with the unary operator ! """ class UnaryNode: def __init__(self, left, op, line): self.left = left self.op = op self.line = line """ Negation of a variable is always a bool, a set variable will be True and an unset variable is false """ def checkTypes(self): self.left.checkTypes() # If this is all correct, return a bool return bool """ Call linkVars for children """ def linkVars(self, varDict): self.left.linkVars(varDict) """ Return string representation of expression """ def getName(self): return self.op + str(self.left.getName()) """ Evaluate expression of children and negate the expression """ def evaluate(self): left_exp = self.left.evaluate() return eval("not " + str(left_exp)) def __repr__(self): return "Monop: {} {}".format(self.op, self.left) """ Class for a literal value like 4, or 'apples' """ class LiteralNode: def __init__(self, value, _type, line): self.value = value self.line = line self.type = _type """ return the type for type checking the expression """ def checkTypes(self): return self.type """ We do not have to modify the dict here, so we can pass this method """ def linkVars(self, varDict): pass """ Return string representation of expression """ def getName(self): return str(self.value) def evaluate(self): return self.value def __repr__(self): return "literal: {}({}) ".format(self.value, self.type) """ Class for a variable created during an assignment or question operation, all values have a default value """ class VarNode: def __init__(self, varname, _type, line, assign=False): self.varname = varname self.line = line self.type = _type self.value = None if assign: self.value = self.getDefaultValue() """ Check if the variable actually exists, if so, set our own type, and now this node will be the node used in the dictionary """ def linkVars(self, varDict): if self.varname in varDict: self.type = varDict[self.varname]['type'] self.value = self.getDefaultValue() # We finally append the node to the node_list in order to easily change its value in the GUI varDict[self.varname]['node_list'].append(self) else: errorstring = "Undeclared variable '" + self.varname + "' at line " + str(self.line) throwError(errorstring) def getDefaultValue(self): default_values = { int: 0, str: "", bool: False, float: 0.0 } try: return default_values[self.type] except KeyError: errorstring = "Invalid default type: " + str(self.type) + "; at line " + str(self.line) throwError(errorstring) """ Return the type for type checking the expression """ def checkTypes(self): return self.type def evaluate(self): return self.value """ Some useful getters and setters -------------- """ def getVarname(self): return self.varname def getLine(self): return self.line def getName(self): return self.varname # Set the value of the variable, and only accept its own type or a int to float conversion def setVar(self, var): if type(var) == self.type: self.value = var elif self.type == float and type(var) == int: self.value = float(var) else: throwError("Bad assignment of variable after expression") def __repr__(self): return "VarNode: {} {} {}".format(self.varname, self.type, self.value)
388da7afc9018562b7670d03135ae6fa5d649aa1
SjoerdvanderHeijden/endless-ql
/Jordy_Dennis/GUI/form_scroll_frame.py
2,087
3.875
4
""" A scrollframe is basically a modifyable frame with a scrollbar Each scrollFrame contains a scrollbar, a canvas, and a contentsFrame. The contentsFrame can contain widgets. The canvas is only used to attach the scrollbar to the contents frame """ from .gui_imports import * class ScrollFrameGui: def __init__(self, parent): self.frame = create_frame(parent) self.frame.pack(expand=True, fill='both') self.canvas, self.contentsFrame = self.createScrollCanvas(self.frame) self.contentsFrame.pack(expand=True, fill="both") self.canvas.pack(expand=True, fill="both") # create a window for the contents frame inside the canvas self.window = self.canvas.create_window((0, 0), window=self.contentsFrame, anchor='nw') # binding correct update functions to canvas and contents self.contentsFrame.bind("<Configure>", self.onConfigureContentFrame) self.canvas.bind("<Configure>", self.onConfigureCanvas) """ Create the canvas, together with the frame that will contain the contents """ def createScrollCanvas(self, parent): canvas = Canvas(parent, background="white") contentsFrame = create_frame(canvas, "white") scrollbar = Scrollbar(parent, command=canvas.yview) scrollbar.pack(side=RIGHT, fill='both') canvas.configure(yscrollcommand=scrollbar.set) return canvas, contentsFrame """ used to set the window of the canvas to the total width of the canvas """ def onConfigureCanvas(self, event): canvas_width = event.width self.canvas.itemconfig(self.window, width=canvas_width) """ Making sure the scroller stays on the canvas and doesnt allow to scroll to infinity """ def onConfigureContentFrame(self, event): self.canvas.configure(scrollregion=self.canvas.bbox('all')) """ Return contents so widgets can be added """ def get_contents(self): return self.contentsFrame def get_frame(self): return self.frame
e729e644c6046753e00b30d7d121a6a192054fb6
merv1618/Python-short-programs
/sample_prime_script.py
353
3.859375
4
from prime_count import primecount def random_polynomial(x): return x**2 + 3*x + 1 if __name__ == '__main__': n = primecount(10) print("Look at me, I calculated the 10th prime number - it's %i" % n) print("Now watch me calculate some random polynomial of the 10th prime number") print("Oh look, it's %i" % random_polynomial(n))
4c374bce6543ab75b8ff194de2eaa543457c6159
ezalos/Rhinoforcement
/state.py
7,393
3.671875
4
#!/usr/bin/env python import numpy as np import copy from color import * MAX_ROWS = 6 MAX_COLS = 7 class state(): def __init__(self): self.init_board = np.zeros([MAX_ROWS, MAX_COLS]).astype(str) self.init_board[self.init_board == "0.0"] = " " self.player = "X" self.board = self.init_board self.last_move = [-1,-1] self.turn = 0 self.victory = '' def is_game_over(self): ''' returns 1, 0 assumes self.victory has been updated (done everytime we drop_piece) ''' if self.victory == ".": return (0.0000000001) elif self.victory == "X": return (1.0) elif self.victory == "O": return (1.0) else: return (0.0) def do_action(self, column): ''' changes player, turn and victory ''' if self.victory != '' : print("Game Over") elif self.board[0, column] != " ": print("Invalid move") print(column) else: row = MAX_ROWS - 1 while " " != self.board[row, column]: row -= 1 self.board[row, column] = self.player self.last_move = [row, column] self.turn += 1 self.check_winner() self.player = "X" if self.player == "O" else "O" def undrop_piece(self): if self.last_move[0] != -1: self.board[self.last_move[0]][self.last_move[1]] = " " self.turn -= 1 self.player = "X" if self.player == "O" else "O" else: print("No memory of last move") def check_line(self, y, x): player = self.player row = self.last_move[0] col = self.last_move[1] if 0: if y == 1 and x == 0: print("|") elif y == 0 and x == 1: print("_") elif y == 1 and x == 1: print("/") elif y == -1 and x == 1: print("\\") count = 0 found = 0 for i in range(0, 4): if 0 <= ((i * x) + row) and ((i * x) + row) < MAX_ROWS: if 0 <= ((i * y) + col) and ((i * y) + col) < MAX_COLS: if player == self.board[row + (x * i), col + (y * i)]: count += 1 found = 1 elif found: break for i in range(-1, -4, -1): if 0 <= (row + (i * x)) and ((i * x) + row) < MAX_ROWS: if 0 <= ((i * y) + col) and ((i * y) + col) < MAX_COLS: if player == self.board[row + (x * i), col + (y * i)]: count += 1 elif found: break if 0: print("Count : ", count) if count >= 4: self.victory = player return True return False def check_winner(self): if self.last_move[0] == -1: for row in MAX_ROWS: for col in MAX_COLS: self.last_move = [row, col] if self.check_line(1, 0): return True elif self.check_line(0, 1): return True elif self.check_line(1, 1): return True elif self.check_line(-1, 1): return True self.last_move = [-1, -1] else: if self.check_line(1, 0): return True elif self.check_line(0, 1): return True elif self.check_line(1, 1): return True elif self.check_line(-1, 1): return True if self.turn >= 42: self.victory = "." return False def get_reward(self): ''' returns 1, 0 assumes self.victory has been updated (done everytime we drop_piece) ''' if self.victory == ".": return (0) elif self.victory == "X": return (1) elif self.victory == "O": return (1) else: return None def actions(self): ''' returns array of possible actions ''' acts = [] for col in range(MAX_COLS): if self.board[0, col] == " ": acts.append(col) return acts def valid_moves_mask(self): valid = np.zeros([MAX_COLS]) for col in range(MAX_COLS): if self.board[0, col] == " ": valid[col] = 1 return (valid) def reset(self): self.player = "X" self.last_move = [-1,-1] self.turn = 0 self.victory = '' for row in range(MAX_ROWS): ## replace by init board ? for col in range(MAX_COLS): self.board[row][col] = " " def copy(self, other): ''' copies all attributes of other into self ''' self.player = other.player self.last_move[0] = other.last_move[0] self.last_move[1] = other.last_move[1] self.turn = other.turn self.victory = other.victory for row in range(MAX_ROWS): for col in range(MAX_COLS): self.board[row][col] = other.board[row][col] def encode_board(self): encoded = np.zeros([3, MAX_ROWS, MAX_COLS]).astype(float) player_conv = {"O":0, "X":1} for row in range(MAX_ROWS): for col in range(MAX_COLS): pos = self.board[row, col] encoded[2, row, col] = player_conv[self.player] if pos != " ": encoded[player_conv[pos], row, col] = 1.0 return encoded def decode_board(self, encoded): self.reset() player_conv = {0:"O", 1:"X"} for row in range(MAX_ROWS): for col in range(MAX_COLS): for player in range(2): pos = encoded[row, col, player] if pos == 1: self.board[row, col] = player_conv[player] self.turn += 1 self.player = player_conv[encoded[0,0,2]] self.check_winner() def display(self): board = self.board move = self.last_move print("Turn", YELLOW, self.turn - 1, RESET, "for ", end="") if self.player == "X": print(BLUE + 'O' + RESET, end="") else: print(RED + 'X' + RESET, end="") print("") for rows in range(MAX_ROWS): for cols in range(MAX_COLS): spot = board[rows, cols] if cols == move[1] and rows == move[0]: print(UNDERLINE, end="") if spot == 'X': print(RED + 'X' + RESET, end="") elif spot == 'O': print(BLUE + 'O' + RESET, end="") else: print('.' + RESET, end="") print(' ', end="") print('\n', end="") print("0 1 2 3 4 5 6") if (self.victory != ''): print("Victory: ", self.victory) print('\n', end="") def stringify(self): return (str(self.last_move) + np.array_repr(self.board) + self.player)
e63ebf17f9e55783a8c81d4e88cd29870d62c29c
grvn/aoc2018
/15/day15-1.py
3,312
3.65625
4
#!/usr/bin/env python3 from sys import argv from heapq import heappop from heapq import heappush ######################################### # Denna innehåller problem med hörnfall # # påverkar ej resultatet av input # # dessa är fixade i day15-2.py # # har ej orkat fixa dem här # ######################################### atp=3 starthp=200 def main(): elves={} goblins={} walls=set() turns=0 with open(argv[1]) as f: input=[list(x.strip()) for x in f] for y,line in enumerate(input): for x,val in enumerate(line): if val=='E': elves[(x,y)]=starthp elif val=='G': goblins[(x,y)]=starthp elif val=='#': walls.add((x,y)) while elves and goblins: order=sorted(list(elves)+list(goblins),key=lambda x:(x[1],x[0])) while order: # order är sorterad efter ordningen de får röra sig who=order.pop(0) if who in elves: # det är en elf hp=elves.pop(who) notfoos=elves foos=goblins elif who in goblins: # det är en goblin hp=goblins.pop(who) notfoos=goblins foos=elves else: # död innan den får agera continue targets=list(foos) inuse=set(elves)|set(goblins)|walls inrange=adjacent(targets)-inuse nextmove=pickmove(who,inrange,inuse) if nextmove is None: # kan inte göra något notfoos[who]=hp continue notfoos[nextmove]=hp if nextmove in inrange: # kan attackera attack(nextmove,foos) if elves and goblins: turns+=1 print(turns*(sum(elves.values())+sum(goblins.values()))) def attack(mypos,targets): inrange=adjacent({mypos}) postargets=[x for x in inrange if x in targets] if postargets: target=min(postargets, key=lambda x: targets[x]) targets[target]-=atp if targets[target]<=0: targets.pop(target) def adjacent(positions): return set ((x+dx,y+dy) for x,y in positions for dx,dy in [(0,-1),(-1,0),(0,1),(1,0)]) def pickmove(mypos,targetpos,inuse): if not targetpos: # finns inga rutor bredvid mål som går att nå return None if mypos in targetpos: return mypos routes=shortestroutes(mypos,targetpos,inuse) posmove=[x[1] for x in routes] return min(posmove,key=lambda x:(x[1],x[0])) if posmove else None def shortestroutes(mypos,targetpos,inuse): # tack google Dijkstra's algoritm # heapq har ingen sortfunction som man kan skicka lambda till! # måste invertera x,y för att få sort korrekt # borde ha haft koordinater som (y,x) från början # eller söka vidare på google efter prioriterad kö res=[] shortest=None been=set([t[::-1] for t in inuse]) x,y=mypos todo=[(0,[(y,x)])] tarpos=[t[::-1] for t in targetpos] while todo: dist,path=heappop(todo) if shortest and len(path)>shortest: # se om vi funnit kortast och gått längre return res currpos=path[-1] # ta sista objekt if currpos in tarpos: # funnit kortast väg res.append([t[::-1] for t in path]) shortest=len(path) continue if currpos in been: # redan besökt continue been.add(currpos) for neigh in adjacent({currpos}): if neigh in been: continue heappush(todo,(dist+1,path+[neigh])) return res if __name__ == '__main__': main()
b6d45c2603128eac609cb2199510960df3fbac95
grvn/aoc2018
/02/day2-2.py
437
3.53125
4
#!/usr/bin/env python3 from sys import argv def main(): with open(argv[1]) as f: input=f.readlines() id1,id2=next((x,y) for x in input for y in input if sum(1 for a,b in zip(x,y) if a!=b)==1) # Hitta de två rätta ID där endast ett enda tecken diffar svar="".join(x for x,y in zip(id1,id2) if x==y).strip() # jämför de två rätta och ta bort de tecken som inte stämmer print(svar) if __name__ == '__main__': main()
676a6639f3231701b8c3d53f9a5572bc8948e394
Daniel-HarrisNL/sprintproject
/graphing/main.py
9,978
3.75
4
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Homework Helper This program prompts for an input name of an algebraic function then prompts the user for necessary coefficiencts. It will compute the graph and ask the user if they wish to display the graph or save it to a file. Authors: Annette Clarke, Nicholas Hodder, Daniel Harris ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import graphing import numpy from matplotlib import pyplot as plt #Available functions for user to choose from graph_list = { "linear" : "f(x) = a*x + b", "quadratic" : "f(x) = a*x^2 + b*x + c", "cubic" : "f(x) = a*x^3 + b*x^2 + c*x + d", "quartic" : "f(x) = a*x^4 + b*x^3 + c*x^2 + d*x + e", "exponential" : "f(x) = a * b^(c*x + d)", "logarithmic" : "f(x) = a * log(b*x + c)", "sine" : "f(x) = a * sin(b*x + c)", "cos" : "f(x) = a * cos(b*x + c)", "squareroot" : "f(x) = a * sqrt(b*x + c)", "cuberoot" : "f(x) = a * sqrt(b*x + c)" } def graph_type(): ''' Description: Receives user choice for which function to graph, confirms that the input is an available choice. Parameters: None Returns: User selected function type. ''' while True: function_type = input("Please select a graph type, or enter 'List' to view available choices: ") if not function_type.isalpha(): print("Error: Function name must be one word with all alphabetical characters ONLY.") continue elif function_type.lower() == "list": graph_type_list() elif function_type.lower() not in graph_list: print("Error: The name provided does not match an available function type.") continue else: print("Graph type selected: {}".format(function_type)) break return function_type.lower() def graph_type_list(): ''' Description: Shows a list of all available graph types which user can select from Paramaters: None Returns: Nothing ''' print("Here is a list of available graph types, displaying name and function:\n") for key,value in graph_list.items(): print("{}: {}\n".format(key.upper(),value)) return def get_range(graph_type_chosen): ''' Description: Recieves user inputs for the range start, end and spacing. Paramaters: graph_type_chosen - A string containing the user selected graph type Returns: Starting range, ending range, and range spacing. ''' while True: try: range_start = int(input("Input the start of the range: ")) range_end = int(input("Input the end of the range: ")) range_spacing = int(input("Input the number of points to generate: ")) if range_start > range_end: print("Error: Starting range value must be less than ending range value.") continue if (graph_type_chosen == "logarithmic" or graph_type_chosen == "squareroot") and (range_start < 0 or range_end < 0): print("Error: Logarithmic and Square root functions must have non-negative range.") continue if (range_start < -2147483648) or (range_end > 2147483647): print("Warning: Extremely large ranges may potentially not work as intended on certain hardware.") break except: print("Error: Must be a number") continue return range_start, range_end, range_spacing def feature_choices(): ''' Description: Prompts user for their choice of graph features, validates the feature name within a loop until correct value entered. Paramaters: None Returns: A list of features configured with user input, with 'legend' on its own as True or False. ''' xlabel = None ylabel = None title = None features = [xlabel, ylabel, title] fname = ["x-axis", "y-axis", "title"] counter = 0 while counter < len(features): while True: features[counter] = input("Enter a label for the " + fname[counter] + " or leave blank to skip: ") is_valid = validate(features[counter]) counter = counter + 1 if is_valid == "skip": features[counter-1] = False break elif is_valid == True: break #If the entry is invalid the loop will restart, so decrement the counter to retry last value. counter = counter - 1 legend = input("Enter 'Y' to include a legend or submit any other input (including blank) to skip: ") if legend.isspace() or legend.lower != 'y' or not legend: legend = False return features, legend def validate(name, deny_special_chars = False): ''' Description: Validates user inputs with naming conventions, Paramaters: name - String to be validated with the convention tests deny_special_chars - Default false, true if no characters other than alphanumeric are permitted. Returns: True if name string passes test, false if string fails. ''' if (name.isspace() or not name) and not deny_special_chars: return "skip" elif not name[0].isalnum(): print("Error: Name must begin with an alphanumeric character.") return False if deny_special_chars: if not name.isalnum(): print("Error: Name must contain only alphanumeric characters.") return False return True def draw_graph(x,y,graph_type_chosen,xlabel,ylabel,title,legend): ''' Description: Renders the graph using all data obtained throughout program Paramaters: x - List of all x coordinates y - List of all y coordinates graph_type_chosen - A string containing the user selected graph type xlabel - User input string for x-axis name, default None if skipped. ylabel - User input string for y-axis name, default None if skipped. title - User input string for graph title, default None if skipped. legend - Boolean determined by user selection Returns: Nothing. ''' # Set axis of the graph including negative numbers fig = plt.figure() ax = fig.add_subplot(1, 1, 1) #If the x-range is negative, shift the spines if any(x < 0): ax.spines['left'].set_position('center') #else: # ax.spines['left'].set_position('zero') #If the y-range is negative, shift the spines if any(y < 0): ax.spines['bottom'].set_position('center') #else: # ax.spines['bottom'].set_position('zero') #Static settings ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') #Plot the graph and assign it a legend label according to it's type plt.plot(x,y, label=graph_type_chosen) #Draw the optional graph features if selected by the user if xlabel and any(y < 0): plt.xlabel(xlabel, veticalalignment='bottom') elif xlabel: plt.xlabel(xlabel) if ylabel and any(x < 0): plt.ylabel(ylabel, horizontalalignment='left') elif ylabel: plt.ylabel(ylabel) if legend: plt.legend() if title: plt.title(title) def save_graph(): ''' Description: Saves the graph to a filename defined by user Paramaters: None Returns: Nothing. ''' file_name = input ("Please name the file (it will save as a .png): ") while not validate(file_name, deny_special_chars = True): file_name = input("Please try again, enter a valid file name: ") plt.savefig(file_name + ".png") return #Program Start if __name__ == "__main__": while True: #Prompt for graph type graph_type_chosen = graph_type() #Assign the range using get_range() NOTE: Start value must be assigned before end value followed by spacing. range_start, range_end, range_spacing = get_range(graph_type_chosen) x = numpy.linspace(range_start, range_end, range_spacing) #Determine graphing function from graphing.py using graph_type_chosen (function name as a string), use get_function() to execute the retrieved function. get_function = getattr(graphing, graph_type_chosen) y = get_function(x) #Input choices for graph features. features, legend = feature_choices() xlabel = features[0] ylabel = features[1] title = features[2] #Render the graph in memory draw_graph(x,y,graph_type_chosen,xlabel,ylabel,title,legend) #Display or Save while True: output_type = input("Would you like to save or display the graph? Please enter 'S' or 'D': ") if not validate(output_type): print("Please try again.") continue output_type = output_type.lower() if output_type == "d": plt.show() break elif output_type == "s": save_graph() break else: print("Error: Wrong character entered, please select one of the options.") #Continue or end cont = input("Would you like to make a new graph? Enter 'Y' to continue or any other input to exit.") if cont.lower() != "y": break
56351369d6585b08ddc07a36b49e940e08003dae
Omkar-Atugade/Python-Function-Files-and-Dictionaries
/week2.py
8,680
4.1875
4
#1. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. #Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as each key’s value. #ANSWER : medal_count={'United States':70,'Great Britain':38,'China':45,'Russia':30,'Germany':17} #2. Given the dictionary swimmers, add an additional key-value pair to the dictionary with "Phelps" as the key and the integer 23 as the value. # Do not rewrite the entire dictionary. #ANSWER : swimmers = {'Manuel':4, 'Lochte':12, 'Adrian':7, 'Ledecky':5, 'Dirado':4} swimmers['Phelps']=23 #3. Add the string “hockey” as a key to the dictionary sports_periods and assign it the value of 3. # Do not rewrite the entire dictionary. #ANSWER : sports_periods = {'baseball': 9, 'basketball': 4, 'soccer': 4, 'cricket': 2} sports_periods['hockey']=3 #4. The dictionary golds contains information about how many gold medals each country won in the 2016 Olympics. #But today, Spain won 2 more gold medals. #Update golds to reflect this information. #ANSWER : golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} golds['Spain']=21 #5. Create a list of the countries that are in the dictionary golds, and assign that list to the variable name countries. # Do not hard code this. #ANSWER : golds = {"Italy": 12, "USA": 33, "Brazil": 15, "China": 27, "Spain": 19, "Canada": 22, "Argentina": 8, "England": 29} countries=golds #6. Provided is the dictionary, medal_count, which lists countries and their respective medal count at the halfway point in the 2016 Rio Olympics. #Using dictionary mechanics, assign the medal count value for "Belarus" to the variable belarus. #Do not hardcode this. #ANSWER : medal_count = {'United States': 70, 'Great Britain':38, 'China':45, 'Russia':30, 'Germany':17, 'Italy':22, 'France': 22, 'Japan':26, 'Australia':22, 'South Korea':14, 'Hungary':12, 'Netherlands':10, 'Spain':5, 'New Zealand':8, 'Canada':13, 'Kazakhstan':8, 'Colombia':4, 'Switzerland':5, 'Belgium':4, 'Thailand':4, 'Croatia':3, 'Iran':3, 'Jamaica':3, 'South Africa':7, 'Sweden':6, 'Denmark':7, 'North Korea':6, 'Kenya':4, 'Brazil':7, 'Belarus':4, 'Cuba':5, 'Poland':4, 'Romania':4, 'Slovenia':3, 'Argentina':2, 'Bahrain':2, 'Slovakia':2, 'Vietnam':2, 'Czech Republic':6, 'Uzbekistan':5} belarus=medal_count.get('Belarus') #7. The dictionary total_golds contains the total number of gold medals that countries have won over the course of history. # Use dictionary mechanics to find the number of golds Chile has won, and assign that number to the variable name chile_golds. #Do not hard code this! #ANSWER : total_golds = {"Italy": 114, "Germany": 782, "Pakistan": 10, "Sweden": 627, "USA": 2681, "Zimbabwe": 8, "Greece": 111, "Mongolia": 24, "Brazil": 108, "Croatia": 34, "Algeria": 15, "Switzerland": 323, "Yugoslavia": 87, "China": 526, "Egypt": 26, "Norway": 477, "Spain": 133, "Australia": 480, "Slovakia": 29, "Canada": 22, "New Zealand": 100, "Denmark": 180, "Chile": 13, "Argentina": 70, "Thailand": 24, "Cuba": 209, "Uganda": 7, "England": 806, "Denmark": 180, "Ukraine": 122, "Bahamas": 12} chile_golds=total_golds.get("Chile") #8. Provided is a dictionary called US_medals which has the first 70 metals that the United States has won in 2016, and in which category they have won it in. # Using dictionary mechanics, assign the value of the key "Fencing" to a variable fencing_value. #Remember, do not hard code this. #ANSWER : US_medals = {"Swimming": 33, "Gymnastics": 6, "Track & Field": 6, "Tennis": 3, "Judo": 2, "Rowing": 2, "Shooting": 3, "Cycling - Road": 1, "Fencing": 4, "Diving": 2, "Archery": 2, "Cycling - Track": 1, "Equestrian": 2, "Golf": 1, "Weightlifting": 1} fencing_value=US_medals.get('Fencing') #9. The dictionary Junior shows a schedule for a junior year semester. #The key is the course name and the value is the number of credits. #Find the total number of credits taken this semester and assign it to the variable credits. #Do not hardcode this – use dictionary accumulation! #ANSWER : Junior = {'SI 206':4, 'SI 310':4, 'BL 300':3, 'TO 313':3, 'BCOM 350':1, 'MO 300':3} credits=0 for i in Junior.values(): credits=credits+i #10. Create a dictionary, freq, that displays each character in string str1 as the key and its frequency as the value. #ANSWER : str1 = "peter piper picked a peck of pickled peppers" freq={} for c in str1: if c not in freq: freq[c]=0 freq[c]=freq[c]+1 #11. Provided is a string saved to the variable name s1. Create a dictionary named counts that contains each letter in s1 and the number of times it occurs. #ANSWER : s1 = "hello" counts={} for c in s1: if c not in counts: counts[c]=0 counts[c]=counts[c]+1 #12. Create a dictionary, freq_words, that contains each word in string str1 as the key and its frequency as the value. #ANSWER : str1 = "I wish I wish with all my heart to fly with dragons in a land apart" x=str1.split() freq_words={} for c in x: if c not in freq_words: freq_words[c]=0 freq_words[c]=freq_words[c]+1 #13. Create a dictionary called wrd_d from the string sent, so that the key is a word and the value is how many times you have seen that word. #ANSWER : sent = "Singing in the rain and playing in the rain are two entirely different situations but both can be good" x=sent.split() wrd_d={} for c in x: if c not in wrd_d: wrd_d[c]=0 wrd_d[c]=wrd_d[c]+1 #14. Create the dictionary characters that shows each character from the string sally and its frequency. #Then, find the most frequent letter based on the dictionary. #Assign this letter to the variable best_char. #AMSWER : sally = "sally sells sea shells by the sea shore" characters={} for c in sally: if c not in characters: characters [c]=0 characters[c]=characters [c]+1 #15. Find the least frequent letter. # Create the dictionary characters that shows each character from string sally and its frequency. #Then, find the least frequent letter in the string and assign the letter to the variable worst_char. #ANSWER : sally = "sally sells sea shells by the sea shore and by the road" characters={} for i in sally: characters [i]=characters.get(i,0)+1 sorted (characters.items(), key=lambda x: x[1]) worst_char=sorted(characters.items(), key=lambda x: x[1])[-13][0] #16. Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1. # Challenge: Letters should not be counted separately as upper-case and lower-case. #Intead, all of them should be counted as lower-case. #ANSWER : string1 = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures." string1.lower() letter_counts={} for c in string1.lower(): if c not in letter_counts: letter_counts[c]=0 letter_counts[c]=letter_counts[c]+1 #17: Create a dictionary called low_d that keeps track of all the characters in the string p and notes how many times each character was seen. #Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as a “t” for example. #ANSWER : p = "Summer is a great time to go outside. You have to be careful of the sun though because of the heat." p.lower() low_d={} for c in p.lower(): if c not in low_d: low_d[c]=0 low_d[c]=low_d[c]+1
971187848e721a42aec82fb6aa5d13f881d84ff4
johnmwalters/dsp
/python/q8_parsing.py
1,242
4.40625
4
# The football.csv file contains the results from the English Premier League. # The colums labeled 'Goals and 'Goals Allowed' contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in 'for' and 'against' goals. import csv def read_data(data): with open(data) as csvfile: reader = csv.DictReader(csvfile) low_diff = 9999 club = '' for row in reader: print row['Team'], row['Games'], row['Wins'], row['Losses'], row['Draws'],row['Goals'], row['Goals Allowed'], row['Points'] goal_difference = int(row['Goals']) - int(row['Goals Allowed']) abs_goal_difference = abs(int(row['Goals']) - int(row['Goals Allowed'])) print abs_goal_difference if abs_goal_difference < low_diff: club = row['Team'] print club low_diff = abs_goal_difference else: low_diff = low_diff print club # COMPLETE THIS FUNCTION #def get_min_score_difference(self, parsed_data): # COMPLETE THIS FUNCTION #def get_team(self, index_value, parsed_data): # COMPLETE THIS FUNCTION read_data('football.csv')
e14986cfefedad1430fb1686076503a05adcc7e1
pavelkasyanov/euler_problems
/src/problem_5/main.py
345
3.75
4
def ifDividesAll(num): for i in (3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19): if num % i != 0: return False return True def main(): num = 20 while True: if ifDividesAll(num): break else: num = num + 10 print(num) if __name__ == '__main__': main()
09ebba380e8d5b0fb3681b64d0b9613293f0769b
pavelkasyanov/euler_problems
/src/problem_2/main.py
474
3.8125
4
MAX_FIB_NUMBER = 4 * 1000000 def main(): result_sum = 2 n1 = 1 n2 = 2 while True: print("=== start iteration ===") print("n1={}, n2={}".format(n1, n2)) n = n1 + n2 print("n={}".format(n)) if n > MAX_FIB_NUMBER: print("result sum={}".format(result_sum)) return if n % 2 == 0: result_sum += n n1 = n2 n2 = n if __name__ == '__main__': main()
714808135eb230b3fca687200a112a888a7809fd
dutraph/python_2021
/basic/while_calc.py
675
4.21875
4
while True: print() n1 = input("Enter 1st number: ") n2 = input("Enter 2nd number: ") oper = input("Enter the operator: ") if not n1.isnumeric() or not n2.isnumeric(): print("Enter a valid number...") continue n1 = int(n1) n2 = int(n2) if oper == '+': print(n1 + n2) elif oper == '-': print(n1 - n2) elif oper == '*': print(n1 * n2) elif oper == '/': div = n1 / n2 print(f'{div:.2f}') else: print("Must enter a valid operator..") continue print(end='\n\n') exit = input("Exit? [y/n]: ") if exit == 'y': break
fa747700c4617f59a616d2f7cf12d8ad3e85e77f
dutraph/python_2021
/basic/guess_game.py
853
4.09375
4
secret = 'avocado' tries = [] chances = 3 while True: if chances <= 0: print("You lose") break letter = input('Type a letter: ') if len(letter) > 1: print('type 1 letter...') continue tries.append(letter) if letter in secret: print(f'awesome letter {letter} exists...') else: print(f'you missed it... {letter} doesnt exists...') tries.pop() secret_temp = '' for secret_letter in secret: if secret_letter in tries: secret_temp += secret_letter else: secret_temp += '*' if secret_temp == secret: print(f'you win... {secret_temp} is the word.') break else: print(secret_temp) if letter not in secret: chances -= 1 print(f'you still get {chances} chances...') print()
c750ed33c5ec4069676685a31f4257f58055d9b0
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio023 - Separando digitos de um numero.py
811
4.1875
4
""" Desafio 023 Faça um programa que leia um número de 0 a 9999 e mostre na tela um dos dígitos separados. Ex: Digite um número: 1834 Unidade: 4 Dezena: 3 Centena: 8 Milhar: 1 """ # Solução 1: com está solução só é possível obter o resulatdo esperado quando se coloca as quatro unidades num = input('Digite um número entre 0 e 9999: ') print('Unidade: {} \nDezena: {} \nCentena: {} \nMilhar: {}'.format(num[3], num[2], num[1], num[0])) # Solução 2: com a lógica matematica é possível obter o resultado desejado independente de quantas unidades sejam usadas n = int(input('Digite um número entre 0 e 9999: ')) u = n % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('O número {} tem: \nUnidade(s): {} \nDezena(s): {} \nCentena(s): {} \nMilhar(es): {}'.format(n, u, d, c, m))
c2e3b043f0166381203eeda2ef0305c7f67a9290
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio064 - Tratando varios valores v1.0.py
556
4.0625
4
""" Desafio 064 Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag) """ num = int(input('Informe um número ou 999 para parar: ')) soma = cont = 0 while num != 999: soma += num cont += 1 num = int(input('Informe um número ou 999 para parar: ')) print('Foram digitados {} números e a soma entre eles é {}'.format(cont, soma))
6282e26c75b7c3673cdbbe6a5418af6232cfa647
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio035 - Analisando triangulos v1.0.py
574
4.21875
4
""" Desafio 035 Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo """ reta1 = float(input('Informe o valor da primeira reta:')) reta2 = float(input('Informe o valor da segunda reta:')) reta3 = float(input('Informe o valor da terceira reta:')) if (reta2 - reta3) < reta1 < reta2 + reta3 and (reta1 - reta3) < reta2 < reta1 + reta3 and (reta1 - reta2) < reta3 < \ reta1 + reta2: print('Essas retas podem forma um triângulo') else: print('Essas retas não podem formam um triângulo')
dd1ae1af46e3a860d227f51cc14f5270e6e4d66d
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio004 - Dissecando uma variavel.py
718
4.25
4
""" Desafio 004 Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele """ msg = input(' Digite algo: ') print('O valor {} e ele é do tipo primitivo desse valor é {}'.format(msg, type(msg))) print('Esse valor é númerico? {}'.format(msg.isnumeric())) print('Esse valor é alfabetico? {}'.format(msg.isalpha())) print('Esse valor é alfanúmerico? {}'.format(msg.isalnum())) print('Esse valor está todo em maiúsculo? {}'.format(msg.isupper())) print('Esse valor está todo em minúsculo? {}'.format(msg.islower())) print('Esse valor tem espaços? {}'.format(msg.isspace())) print('Esse valor está capitalizado? {}'.format(msg.istitle()))
1bc9ada8524c22e186391996992ee6458c992b98
nataliaqsoares/Curso-em-Video
/Mundo 03/desafio075 - Analise de dados em uma tupla.py
853
4.28125
4
""" Desafio 075 Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: a) quantas vezes apareceu o valor 9; b) em que posição foi digitado o primeiro valor 3; c) quais foram os números pares; """ conjunto = (int(input('Informe um número: ')), int(input('Informe um número: ')), int(input('Informe um número: ')), int(input('Informe um número: ')),) cont = 0 print(f'Foram informados os números: {conjunto}\nO 9 apareceu {conjunto.count(9)} vezes') if conjunto.count(3) == 0: print(f'O número 3 não foi informado') else: print(f'O 3 apareceu na {conjunto.index(3) + 1}º posição') print(f'Os números pares digitados foram: ', end='') for num in conjunto: if num % 2 == 0: print(num, end=' ') else: cont += 1 if cont == 4: print('nenhum')
0048caeb7b3546c1ae8cc917685d0df5242ad2b3
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio033 - Maior e menor valores.py
600
4.15625
4
""" Desafio 033 Faça um programa que leia três números e mostre qual é o maior e qual é o menor. """ n1 = int(input('Informe um número: ')) n2 = int(input('Informe mais um número: ')) n3 = int(input('Informe mais um número: ')) maior = 0 menor = 0 if n1 > n2 and n1 > n3: maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 if n1 < n2 and n1 < n3: menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 print('Dos três números informados o maior número é {} e o menor número é {}'.format(maior, menor))
474e5fbf97eca5b09a0527b9cf59290b4f4ff08c
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio053 - Detector de palindromo.py
579
3.921875
4
""" Desafio 053 Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Ex.: Apos a sopa / A sacada da casa / A torre da derrota / O lobo ama o bolo / Anotaram a data da maratona """ frase = str(input('Informe uma frase: ')).lower().split() frase = ''.join(frase) cont_frase = len(frase)-1 cont = 0 for c in range(0, len(frase)): if frase[c] == frase[cont_frase]: cont += 1 cont_frase -= 1 if len(frase) == cont: print('Essa frase é um palíndromo') else: print('Essa frase não é um palíndromo')
fccf2bdb5f6afe42e695468b8cefc57fedb19783
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio028 - Jogo de Adivinhacao v.1.0.py
526
4.25
4
""" Desafio 028 Escreva um programa que faça o computador 'pensar' em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu """ from random import randint print('Estou pensando em um número entre 0 e 5...') n1 = randint(0, 5) n2 = int(input('Em qual número eu pensei? ')) if n1 == n2: print('Você acertou!') else: print('Você errou! Eu estava pensando no número {}'.format(n1))
693dd4620876b1525d56d4b03c47a34f032feb20
nataliaqsoares/Curso-em-Video
/Mundo 02/desafio036 - Aprovando emprestimo.py
842
4.1875
4
""" Desafio 036 Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado """ valor_casa = float(input('Qual valor da casa que deseja financiar? R$')) salario = float(input('Qual seu salário mensal? R$')) anos = int(input('Em quantos anos deseja pagar a casa? ')) prestacao = valor_casa / (anos * 12) if prestacao >= (salario * 0.3): print('Infelizmente não foi possível financiar está casa no momento') else: print('Seu financiamento foi aprovado! As prestações mensais para pagar a casa de {:.2f} em {} anos são de {:.2f}' .format(valor_casa, anos, prestacao))
4fdbc344aff48594e6fedfe984943a25854f6aed
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio012 - Calculando desconto.py
292
3.65625
4
""" Desafio 012 Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto """ preco = float(input('Informe o preço do produto: ')) novopreco = preco - (preco * 0.05) print('O produto de preço {} com desconto fica por {:.2f}'.format(preco, novopreco))
b32e3fa30f283a656532c6154c7795e319ef6c84
nataliaqsoares/Curso-em-Video
/Mundo 03/desafio100 - Funcoes para sortear e somar.py
754
4.0625
4
""" Desafio 100 Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar(). A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar a soma entre todos os valores pares sorteados pela função anterior """ from random import randint from time import sleep def sorteia(lst): print('Sorteando os 5 valores da lista: ', end='') for c in range(0, 5): n = randint(0, 10) lst.append(n) print(n, end=' ') sleep(1) print('Pronto!') def somaPar(lst): s = 0 for c in lst: if c % 2 == 0: s += c print(f'Somando os valores pares de {lst}, temos {s}') num = [] sorteia(num) somaPar(num)
967aa21504999e6fd116ebd555c548bc26f6903c
nataliaqsoares/Curso-em-Video
/Mundo 01/desafio002.1 - Data de nascimento.py
514
4.125
4
""" Desafio002.1 Crie um programa que leia o dia, o mês e o ano de nascimento de uma pessoa e mostre uma mensagem com a data formatada (mensagem de saida = Você nasceu no dia x de x de x. Correto?) """ # Solução 1 nasci = input('Quando você nasceu? ') print('Você nasceu em', nasci, 'Correto?') # Solução 2 dia = input('Em qual dia você nasceu? ') mes = input('Em qual mês você nasceu? ') ano = input('Em qual ano você nasceu? ') print('Você nasceu no dia', dia, 'de', mes, 'de', ano, 'Correto?')
acfc2d6ff4b396815192db8f0e87fc8a514fc55d
Guilherme-Avellar/primeiras_aulas
/jogo do ppt aprimorado.py
1,227
4.03125
4
# jogo do pedra, papel ou tesoura, com biblioteca de sorteio print("Jogo do pedra papel ou tesoura") player = input("Joque pedra, papel ou tesoura: ") from random import * computador = randint(0,2) if player == "pedra" or player == "Pedra" or player == "PEDRA": player = 0 else: if player == "papel" or player == "Papel" or player == "PAPEL": player = 1 else: if player == "tesoura" or player == "Tesoura" or player == "TESOURA": player = 2 else: computador = "O computador não jogou" player = 3 if player < 0 or player > 2: print("O jogo feito está escrito errado ou está inválido") else: if player == computador: print("Empate") else: if (player == 0 and computador == 2) or (player == 1 and computador == 0) or (player == 2 and computador == 1): print("Você venceu") else: print("Derrota") if computador == 0: computador = "O computador jogou pedra" else: if computador == 1: computador = "O computador jogou papel" else: if computador == 2: computador = "O computador jogou tesoura" print(computador)
a916c4834eeb10336fe9c75e2e58e83684fafac8
thales-mro/python-cookbook
/3-numbers-dates-hours/15-convert-string-to-datetime.py
487
4.0625
4
from datetime import datetime #way faster solution than showed in main() def parse_ymd(s): year_s, month_s, day_s = s.split('-') # only works if you know the string format return datetime(int(year_s), int(month_s), int(day_s)) def main(): text = '2020-01-25' y = datetime.strptime(text, '%Y-%m-%d') z = datetime.now() diff = z - y print(diff) print(datetime.strftime(y, '%A %B %d, %Y')) print(parse_ymd(text)) if __name__ == "__main__": main()
68a32e533997a2817579198a90aafaad911e3fbd
thales-mro/python-cookbook
/2-strings/5-search-and-replace.py
650
3.9375
4
import re from calendar import month_abbr def replace_callback(m): mon_name = month_abbr[int(m.group(2))] return '{} {} {}'.format(m.group(1), mon_name, m.group(3)) def main(): text = 'yeah, but no, but yeah, but no, but yeah' print(text.replace('yeah', 'yep')) text = "Today is 02/01/2020. In a week it will be 09/01/2020." datepat = re.compile(r'(\d+)/(\d+)/(\d+)') print(datepat.sub(r'\3-\2-\1', text)) print(datepat.sub(replace_callback, text)) print("If it is desired to know the number of replacements:") _, n = datepat.subn(r'\3-\2-\1', text) print(n) if __name__ == "__main__": main()
499b850f68b05aceb843bcd4f6f94c9cb1077afc
thales-mro/python-cookbook
/2-strings/4-pattern-match-and-search.py
1,181
4.125
4
import re def date_match(date): if re.match(r'\d+/\d+/\d+', date): print('yes') else: print('no') def main(): text = 'yeah, but no, but yeah, but no, but yeah' print(text.find('no')) date1 = '02/01/2020' date2 = '02 Jan, 2020' date_match(date1) date_match(date2) print("For multiple uses, it is good to compile the regex") datepat = re.compile(r'\d+/\d+/\d+') if datepat.match(date1): print("yes") else: print("no") if datepat.match(date2): print("yes") else: print("no") text = "Today is 02/01/2020. In a week it will be 09/01/2020." print(datepat.findall(text)) print("Including capture groups (in parenthesis)") datepat = re.compile(r'(\d+)/(\d+)/(\d+)') m = datepat.match('26/09/1998') print(m) print(m.group(0), m.group(1), m.group(2), m.group(3), m.groups()) print(datepat.findall(text)) for month, day, year in datepat.findall(text): print('{}--{}--{}'.format(year, month, day)) print("With finditer:") for m in datepat.finditer(text): print(m.groups()) if __name__ == "__main__": main()
881166784fd6a82253a5b189f956582a7a8de5e0
firebirdrazer/CodingTests
/check_paren.py
1,952
4.40625
4
def check_bracket(Str): stack = [] #make a empty check stack while Str != "": #as long as the input is not empty tChar = Str[0] #extract the first character as the test character Str = Str[1:] #the rest characters would be the input in the next while loop if tChar == "(" or tChar == "{": #as the test character is a left-bracket "(" or "{" stack.append(tChar) #the character would be added into the stack elif tChar == ")" or tChar == "}": #if the test character is a right-bracket ")" or "}" if len(stack) == 0: #then we have to check the stack to see if there's a corresponding one return False #if no or empty, the string would be invalid else: #if yes, we can pop the corresponding character from the stack if tChar == ")" and stack[-1] == "(": stack.pop(-1) elif tChar == "}" and stack[-1] == "{": stack.pop(-1) else: return False if stack == []: #which means if the string is valid, the stack would be empty return True #after the process else: #if there's anything left after the process return False #the function would return False #main program Test=input() #input string print(check_bracket(Test)) #return True if the input has valid brackets
5794112ddeb0e6706ded784d7fec7249659e9450
mango915/haliteRL
/Modules/encode.py
22,954
3.84375
4
import numpy as np def one_to_index(V,L): """ Parameters ---------- V: LxL matrix with one entry = 1 and the others = 0 L: linear dimension of the square matrix Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row. Returns ------- integer corresponding to the non-zero element of V. """ return np.arange(L**2).reshape((L, L))[V.astype(bool)] def encode(v_dec, L): """ Parameters ---------- v_dec: list or numpy array of two integers between 0 and L L : linear dimension of the square matrix Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row. Returns ------- integer corresponding to the element (v_dec[0],v_dec[1]) of the encoding matrix. """ V = np.arange(0,L**2).reshape((L,L)) v_enc = V[v_dec[0],v_dec[1]] return v_enc def decode(v_enc, L): """ Parameters ---------- v_enc: scalar between 0 and L**2 - 1, is the encoding of a position (x,y) L : linear dimension of the square matrix Assign increasing integers starting from 0 up to L**2 to an LxL matrix row by row. Returns ------- numpy array containg the row and the column corresponding to the matrix element of value v_enc. """ V = np.arange(0,L**2).reshape((L,L)) v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0]]) return v_dec def get_halite_vec_dec_v0(state, q_number = 3, map_size = 7): """ Parameters ---------- state: [map_size,map_size,>=3] numpy array, which layers are: Layer 0: map halite, Layer 1: ship position, Layer 2: halite carried by the ships (a.k.a. cargo) q_number : number of quantization levels map_size : linear size of the squared map Returns ------- quantized halite vector [𝐶,𝑂,𝑆,𝑁,𝐸,𝑊], numpy array of shape (6,) (where C stands for the halite carried by the ship and O for the cell occupied by the ship) """ def halite_quantization(halite_vec, q_number = 3): """ Creates q_number thresholds [t0,t1,t2] equispaced in the log space. Maps each entry of halite_vec to the corresponding level: if h <= t0 -> level = 0 if t0 < h <= t1 -> level = 1 else level = 2 Parameters ---------- halite_vec : numpy array which elements are numbers between 0 and 1000 q_number : number of quantization levels Returns ------- level : quantized halite_vec according to the q_number thresholds """ # h can either be a scalar or a matrix tresholds = np.logspace(1,3,q_number) # [10, 100, 1000] = [10^1, 10^2, 10^3] h_shape = halite_vec.shape h_temp = halite_vec.flatten() mask = (h_temp[:,np.newaxis] <= tresholds).astype(int) level = np.argmax(mask, axis = 1) return level.reshape(h_shape) pos_enc = one_to_index(state[:,:,1], map_size) pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices ship_cargo = state[pos_dec[0],pos_dec[1],2] cargo_quant = halite_quantization(ship_cargo).reshape(1)[0] # quantize halite map_halite = state[:,:,0] halite_quant = halite_quantization(map_halite) # quantize halite halite_vector = [] halite_vector.append(cargo_quant) halite_vector.append(halite_quant[pos_dec[0], pos_dec[1]]) halite_vector.append(halite_quant[(pos_dec[0]+1)%map_size, pos_dec[1]]) halite_vector.append(halite_quant[(pos_dec[0]-1)%map_size, pos_dec[1]]) halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]+1)%map_size]) halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]-1)%map_size]) return np.array(halite_vector) def get_halite_vec_dec(state, map_h_thresholds = np.array([100,500,1000]), cargo_thresholds = np.array([200,400,800,1000]), map_size = 7): """ Parameters ---------- state: numpy array, shape (map_size,map_size,>=3), which layers are: Layer 0: map halite, Layer 1: ship position, Layer 2: halite carried by the ships (a.k.a. cargo) map_h_thresholds: quantization thresholds for halite in map's cells cargo_thresholds: quantization thresholds for cargo map_size : int, linear size of the squared map Returns ------- quantized halite vector [𝐶,𝑂,𝑆,𝑁,𝐸,𝑊], numpy array of shape (6,) (where C stands for the halite carried by the ship and O for the cell occupied by the ship) """ def halite_quantization(halite_vec, thresholds): """ Maps each entry of halite_vec to the corresponding quantized level: if h <= t0 -> level = 0 if t0 < h <= t1 -> level = 1 and so on Parameters ---------- halite_vec : numpy array which elements are numbers between 0 and 1000 thresholds : quantization thresholds Returns ------- level : quantized halite_vec according to the q_number thresholds """ # h can either be a scalar or a matrix h_shape = halite_vec.shape h_temp = halite_vec.flatten() mask = (h_temp[:,np.newaxis] <= thresholds).astype(int) level = np.argmax(mask, axis = 1) return level.reshape(h_shape) pos_enc = one_to_index(state[:,:,1], map_size) pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices ship_cargo = state[pos_dec[0],pos_dec[1],2] cargo_quant = halite_quantization(ship_cargo, cargo_thresholds).reshape(1)[0] # quantize halite map_halite = state[:,:,0] halite_quant = halite_quantization(map_halite, map_h_thresholds) # quantize halite halite_vector = [] halite_vector.append(cargo_quant) halite_vector.append(halite_quant[pos_dec[0], pos_dec[1]]) halite_vector.append(halite_quant[(pos_dec[0]+1)%map_size, pos_dec[1]]) halite_vector.append(halite_quant[(pos_dec[0]-1)%map_size, pos_dec[1]]) halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]+1)%map_size]) halite_vector.append(halite_quant[pos_dec[0], (pos_dec[1]-1)%map_size]) return np.array(halite_vector) def get_halite_direction(state, map_size = 7): """ Returns the direction richest in halite given the ship position. Works only for a single ship. Parameters ---------- state: [map_size,map_size,>=3] numpy array Layer 0: map halite Layer 1: ship position Layer 2: halite carried by the ships (a.k.a. cargo) map_size : linear size of the squared map Returns ------- h_dir : int Dictionary to interpret the output: {0:'S', 1:'N', 2:'E', 3:'W'} """ def roll_and_crop(M, shift, axis, border = 1, center = (3,3)): """ Shift matrix and then crops it around the center keeping a border. Inputs ------ M : squared matrix in numpy array Matrix to be rolled and cropped shift : int or tuple of ints The number of places by which elements are shifted. If a tuple, then `axis` must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while `axis` is a tuple of ints, then the same value is used for all given axes. axis : int or tuple of ints, optional Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored. border : int Border around central cell (after the shift) to be cropped. The resulting area is of 2*border+1 x 2*border+1 Parameters ---------- M_cut : numpy matrix of shape (2*border+1,2*border+1) """ M_temp = np.roll(M, shift = shift, axis = axis) M_crop = M_temp[center[0]-border:center[0]+border+1, center[1]-border:center[1]+border+1] return M_crop map_halite = state[:,:,0] # matrix with halite of each cell of the map shipy_pos_matrix = state[:,:,3] # matrix with 1 in presence of the shipyard, zero otherwise pos_enc = one_to_index(state[:,:,1], map_size) # ship position pos_dec = decode(pos_enc, map_size) # decode position to access matrix by two indices shipy_enc = one_to_index(shipy_pos_matrix, map_size) # shipyard position shipy_dec = decode(shipy_enc, map_size) #position_decoded shift = (shipy_dec[0]-pos_dec[0],shipy_dec[1]-pos_dec[1]) centered_h = np.roll(map_halite, shift = shift, axis = (0,1)) #centers map_halite on the ship mean_cardinal_h = [] # this could be generalized to wider areas, like 5x5, but 3x3 it's enough for a 7x7 map perm = [(a,sh) for a in [0,1] for sh in [-2,2]] # permutations of shifts and axis to get the 4 cardinal directions for a,sh in perm: mean_h = np.mean(roll_and_crop(centered_h, shift = sh, axis = a), axis = (0,1)) mean_cardinal_h.append(mean_h) mean_cardinal_h = np.array(mean_cardinal_h) halite_direction = np.argmax(mean_cardinal_h) #+ 1 # take the direction of the 3x3 most rich zone return halite_direction def encode_vector(v_dec, L = 6, m = 3): """ Encodes a vector of L integers ranging from 0 to m-1. Parameters ---------- v_dec: list or numpy array of L integers between 0 and m L : length of the vector Assign increasing integers starting from 0 up to m**L to an m-dimensional matrix "row by row". Returns ------- integer corresponding to the element (v_dec[0],v_dec[1],...,v_dec[L-1]) of the encoding tensor. """ T = np.arange(m**L).reshape(tuple([m for i in range(L)])) return T[tuple(v_dec)] def encode_vector_v1(v_dec, ranges): """ Encodes a vector of len(ranges), whose i-th elements ranges from 0 to ranges[i]. Parameters ---------- v_dec : list or numpy array of integers ranges : ranges of possible values for each entry of v_dec Returns ------- integer corresponding to the element (v_dec[0],v_dec[1],...,v_dec[-1]) of the encoding tensor. """ tot_elements = 1 for r in ranges: tot_elements = tot_elements * r T = np.arange(tot_elements).reshape(tuple(ranges)) return T[tuple(v_dec)] def decode_vector(v_enc, L = 6, m = 3): """ Decodes an encoding for a vector of L integers ranging from 0 to m-1. Parameters ---------- v_enc: scalar between 0 and m**L - 1, is the encoding of a position (x1,x2,...,xL) L : length of the vector Assign increasing integers starting from 0 up to m**L to an m-dimensional matrix "row by row". Returns ------- numpy array containg the indexes corresponding to the tensor element of value v_enc. """ T = np.arange(m**L).reshape(tuple([m for i in range(L)])) return np.array([np.where(v_enc == T)[i][0] for i in range(L)]) def encode2D(v_dec, L1, L2): """ Encodes a vector of 2 integers of ranges respectively L1 and L2 e.g. the first entry must be an integer between 0 and L1-1. Parameters ---------- v_dec: list or numpy array of two integers between 0 and L L1 : range od the first dimension L2 : range od the second dimension Assign increasing integers starting from 0 up to L1*L2-1 to an L1xL2 matrix row by row. Returns ------- integer corresponding to the element (v_dec[0],v_dec[1]) of the encoding 2matrix. """ V = np.arange(0,L1*L2).reshape((L1,L2)) v_enc = V[tuple(v_dec)] return v_enc def decode2D(v_enc, L1, L2): """ Decodes an encoding for a vector of 2 integers of ranges respectively L1 and L2. Parameters ---------- v_enc: scalar between 0 and L1*L2-1, is the encoding of a position (x,y) L1 : range od the first dimension L2 : range od the second dimension Assign increasing integers starting from 0 up to L1*L2-1 to an L1xL2 matrix row by row. Returns ------- numpy array containg the row and the column corresponding to the matrix element of value v_enc. """ V = np.arange(0,L1*L2).reshape((L1,L2)) v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0]]) return v_dec def encode3D(v_dec, L1, L2, L3): """ Encodes a vector of 3 integers of ranges respectively L1, L2 and L3, e.g. the first entry must be an integer between 0 and L1-1. Parameters ---------- v_dec: list or numpy array of three integers between 0 and L L1 : range od the first dimension L2 : range od the second dimension L3 : range od the third dimension Assign increasing integers starting from 0 up to L1*L2*L3 to an L1xL2xL3 3D-matrix "row by row". Returns ------- integer corresponding to the element (v_dec[0],v_dec[1],v_dec[2]) of the encoding 3D-matrix. """ V = np.arange(0,L1*L2*L3).reshape((L1,L2,L3)) v_enc = V[tuple(v_dec)] return v_enc def decode3D(v_enc, L1, L2, L3): """ Decodes an encoding for a vector of 3 integers of ranges respectively L1, L2 and L3. Parameters ---------- v_enc: scalar between 0 and L1*L2*L3 - 1, is the encoding of a position (x,y) L1 : range od the first dimension L2 : range od the second dimension L3 : range od the third dimension Assign increasing integers starting from 0 up to L1*L2*L3 to an L1xL2xL3 3D-matrix "row by row". Returns ------- numpy array containg the indexes corresponding to the 3D-matrix element of value v_enc. """ V = np.arange(0,L1*L2*L3).reshape((L1,L2,L3)) v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0], np.where(v_enc == V)[2][0]]) return v_dec def encode_state(state, map_size = 7, h_lev = 3, n_actions = 5, debug = False): """ Encode a state of the game in a unique scalar. Parameters ---------- state : [map_size,map_size,>=3] numpy array Layer 0: map halite Layer 1: ship position Layer 2: halite carried by the ships (a.k.a. cargo) map_size : int, linear size of the squared map h_lev : int, number of quantization levels of halite n_actions: int, number of actions that the agent can perform deubg : bool, verbose mode to debug Returns ------- s_enc : int, unique encoding of the partial observation of the game state """ debug_print = print if debug else lambda *args, **kwargs : None pos_enc = one_to_index(state[:,:,1], map_size)[0] # ship position debug_print("Ship position encoded in [0,%d]: "%(map_size**2-1), pos_enc) # ADJUST FOR COMPATIBILITY map_h_thresholds = np.array([10,100,1000]) #same for map and cargo halvec_dec = get_halite_vec_dec(state, map_h_thresholds, map_h_thresholds, map_size = map_size) # ADJUST FOR COMPATIBILITY halvec_enc = encode_vector(halvec_dec) # halite vector debug_print("Halite vector encoded in [0,%d]: "%(h_lev**6 -1), halvec_enc) haldir = get_halite_direction(state, map_size = map_size) # halite direction debug_print("Halite direction in [0,3]: ", haldir) s_dec = np.array([pos_enc, halvec_enc, haldir]) debug_print("Decoded state: ", s_dec) s_enc = encode3D(s_dec, L1 = map_size**2, L2 = h_lev**6, L3 = n_actions-1) debug_print("State encoded in [0, %d]: "%(map_size**2*h_lev**6*(n_actions-1)), s_enc, '\n') return s_enc def encode_state_v1(state, map_h_thresholds, cargo_thresholds, map_size = 7, n_actions = 5, debug = False): """ Encode a state of the game in a unique scalar. Parameters ---------- state : [map_size,map_size,>=3] numpy array Layer 0: map halite Layer 1: ship position Layer 2: halite carried by the ships (a.k.a. cargo) map_size : int, linear size of the squared map h_lev : int, number of quantization levels of halite for map cells cargo_lev: int, number of quantization levels of halite for carried halite (a.k.a. cargo) n_actions: int, number of actions that the agent can perform deubg : bool, verbose mode to debug Returns ------- s_enc : int, unique encoding of the partial observation of the game state """ #define some derived quantities h_lev = len(map_h_thresholds) cargo_lev = len(cargo_thresholds) # define debug print function debug_print = print if debug else lambda *args, **kwargs : None pos_enc = one_to_index(state[:,:,1], map_size)[0] # get ship position debug_print("Ship position encoded in [0,%d]: "%(map_size**2-1), pos_enc) halvec_dec = get_halite_vec_dec(state, map_h_thresholds, cargo_thresholds, map_size = map_size) ranges = [cargo_lev] + [h_lev for i in range(5)] halvec_enc = encode_vector_v1(halvec_dec, ranges) # halite vector debug_print("Halite vector encoded in [0,%d]: "%((h_lev**5)*cargo_lev -1), halvec_enc) haldir = get_halite_direction(state, map_size = map_size) # halite direction debug_print("Halite direction in [0,3]: ", haldir) s_dec = np.array([pos_enc, halvec_enc, haldir]) debug_print("Decoded state: ", s_dec) s_enc = encode3D(s_dec, L1 = map_size**2, L2 = (h_lev**5)*cargo_lev, L3 = n_actions-1) debug_print("State encoded in [0, %d]: "%((map_size**2)*(h_lev**5)*cargo_lev*(n_actions-1)), s_enc, '\n') return s_enc def scalar_to_matrix_action(action, state, map_size = 7): # first get the decoded position of the ship ship_pos_matrix = state[:,:,1] pos_enc = one_to_index(ship_pos_matrix, map_size) pos_dec = decode(pos_enc, map_size) # then fill a matrix of -1 mat_action = np.full((map_size,map_size), -1) # finally insert the action in the pos_dec entry mat_action[tuple(pos_dec)] = action return mat_action def sym_encode(s, map_size = 7, h_lev = 3, n_actions = 5, debug=False): # first create all the equivalent states # rotations s90 = np.rot90(s, k = 1) s180 = np.rot90(s, k = 2) s270 = np.rot90(s, k = 3) # reflections s_f = np.flip(s, axis = 1) s90_f = np.flip(s90, axis = 0) s180_f = np.flip(s180, axis = 1) s270_f = np.flip(s270, axis = 0) s8_dec = [s, s90, s180, s270, s_f, s90_f, s180_f, s270_f] # then encode all of them s8_enc = [] for state in s8_dec: s_enc = encode_state(state, map_size = map_size, h_lev = h_lev, n_actions = n_actions, debug=False) s8_enc.append(s_enc) # finally returns all the encoded states return np.array(s8_enc) def sym_action(a): A = np.array([[-1,2,-1],[4,0,3],[-1,1,-1]]) choice = np.full((3,3),a) M = (A==choice) # mask M90 = np.rot90(M, k = 1) M180 = np.rot90(M, k = 2) M270 = np.rot90(M, k = 3) # reflections M_f = np.flip(M, axis = 1) M90_f = np.flip(M90, axis = 0) M180_f = np.flip(M180, axis = 1) M270_f = np.flip(M270, axis = 0) M8 = [M, M90, M180, M270, M_f, M90_f, M180_f, M270_f] a8 = [] for m in M8: a8.append(A[m][0]) return a8 # multi-agent changes def multi_scalar_to_matrix_action(actions, state, map_size = 7): # first get the decoded position of the ship ship_pos_matrix = state[:,:,1] ships_pos_enc = one_to_index(ship_pos_matrix, map_size) # then fill a matrix of -1 mat_action = np.full((map_size,map_size), -1) for i in range(len(ships_pos_enc)): pos_dec = decode(ships_pos_enc[i], map_size) #print("pos_dec: ", pos_dec) # finally insert the action in the pos_dec entry mat_action[tuple(pos_dec)] = actions[i] return mat_action def safest_dir(pos_enc, state, map_size = 7): # pos_enc is of a single ship ship_pos_matrix = state[:,:,1] shipy_enc = one_to_index(state[:,:,3], map_size) shipy_dec = decode(shipy_enc, map_size) pos_dec = decode(pos_enc, map_size) shift = (shipy_dec[0]-pos_dec[0],shipy_dec[1]-pos_dec[1]) centered = np.roll(ship_pos_matrix , shift = shift, axis = (0,1)) #centers map_halite on the ship s1 = shipy_dec + [0,1] s2 = shipy_dec + [0,-1] s3 = shipy_dec + [1,0] s4 = shipy_dec + [-1,0] s = [s1,s2,s3,s4] mask = np.zeros((map_size,map_size)).astype(int) for x in s: mask[tuple(x)] = 1 mask = mask.astype(bool) near_ships = centered[mask] # N,W,E,S -> 2,4,3,1 x = np.array([2,4,3,1]) if near_ships.sum() < 4: safe_dirs = x[~near_ships.astype(bool)] # safe directions safest_dir = np.random.choice(safe_dirs) else: safest_dir = 0 return safest_dir def encode_multi_state(state, map_size = 7, h_lev = 3, n_actions = 5, debug = False): import copy # returns a list containing the encoded state of each ship ship_ids = state[:,:,4][state[:,:,1].astype(bool)] enc_states = [] for i in range(len(ship_ids)): ID = ship_ids[i] # select one ID in order of position in the map mask = (state[:,:,4] == ID) # select only the position of the ship with this ID one_state = copy.deepcopy(state) # work with a deep copy to make changes only on that one_state[:,:,1][~mask] = 0 # map it to a one-ship state pos_enc = one_to_index(one_state[:,:,1], map_size) safe_dir = safest_dir(pos_enc, state, map_size = 7) # new information to encode in the multi-agent case # recycle the function used to encode the one-ship case by masking the other ships s1_enc = encode_state(one_state, map_size = map_size, h_lev = h_lev, n_actions = n_actions, debug = debug) n_states1 = map_size**2*h_lev**6*4 # number of possible states along s1_enc n_states2 = n_actions s_enc = encode2D(np.array([s1_enc, safe_dir]), L1 = n_states1, L2 = n_states2) enc_states.append(s_enc) return enc_states # 4D encoding and decoding for arbitrary lengths of the four axis def encode4D(v_dec, L1, L2, L3, L4): V = np.arange(0,L1*L2*L3*L4).reshape((L1,L2,L3,L4)) v_enc = V[tuple(v_dec)] return v_enc def decode4D(v_enc, L1, L2, L3,L4): V = np.arange(0,L1*L2*L3*L4).reshape((L1,L2,L3,L4)) v_dec = np.array([np.where(v_enc == V)[0][0],np.where(v_enc == V)[1][0], np.where(v_enc == V)[2][0], np.where(v_enc == V)[3][0]]) return v_dec
85e4570b02806f103b50429e1d73ec2652e009fe
iamparul08/Hands-on-P6
/fileio2_ADID.py
394
3.65625
4
#reading first 11 characters from the file print("First 11 characters of the file:") f = open("in1_ADID.txt", "r") print(f.read(11)) f.close() #reading first line print("\nReading first line of the file:") f = open("in1_ADID.txt", "r") print(f.readline()) f.close() #using read() method print("\nRead the content of the file:") f = open("in1_ADID.txt", "r") print(f.read())
cea334a02a27c95069e54496cc08c6c77eb439e1
Miranjunaidi/SRMAP_CodingClub_Tests
/Test1/Solutions/Binary/binStrings.py
568
3.625
4
def all_n_BinStrings(n): if n == 1: return ["0", "1"] else: given = all_n_BinStrings(n-1) res = [] for bistr in given: res.append(bistr + '0') res.append(bistr + '1') return res def numsubString(n, pattern): return sum([(pattern in s) for s in all_n_BinStrings(n)]) #print(numsubString(6, "11011")) if __name__ == "__main__": NumTestCases = int(input()) for i in range(NumTestCases): n = int(input("")) pattern = "110011" print(numsubString(n, pattern))
00b2a919a2f0cb213dfc003e78d64d1957cd5c70
Lyra2108/AdventOfCode
/2015/Day2/Presents.py
623
3.546875
4
def calculate_package_needs(boxes): paper = 0 ribbon = 0 for box in boxes: sizes = list(map(lambda size: int(size), box)) x, y, z = sizes sizes.remove(max(sizes)) x_small, y_small = sizes paper += 2*x*y + 2*x*z + 2*y*z + x_small*y_small ribbon += 2*x_small + 2*y_small + x*y*z return (paper, ribbon) if __name__ == "__main__": raw_boxes = open("sizes.txt", "r").readlines() boxes = map(lambda size: size.split('x'), raw_boxes) print("They need %d square foot of wrapping paper and %d foot of ribbon." % calculate_package_needs(boxes))
e6484be2f1f99100731c9fe5043e918fad434070
Lyra2108/AdventOfCode
/2019/Day1/rocketFuel.py
926
3.75
4
from functools import reduce def read_in_modules(): input_file = open("input.txt", "r") return list(map(lambda x: int(x), input_file.readlines())) def simple_calculate_fuel(modules): return reduce(lambda x, y: x + y, map(lambda module: calculate_fuel(module), modules)) def calculate_fuel(module): fuel = int(module / 3) - 2 return 0 if fuel < 0 else fuel def calculate_fuel_with_fuel_fuel(modules): total_fuel = 0 fuels = modules while fuels: fuels = list(filter(lambda module: module > 0, map(lambda module: calculate_fuel(module), fuels))) if fuels: total_fuel += reduce(lambda x, y: x + y, fuels) return total_fuel if __name__ == '__main__': modules = read_in_modules() print("The modules need %d fuel." % simple_calculate_fuel(modules)) print("The modules need %d fuel including their fuel." % calculate_fuel_with_fuel_fuel(modules))
4789d3e5ea7dae714483f2f25aed18792e2bbfd0
Lyra2108/AdventOfCode
/2018/Day9/MarbleMania.py
1,413
3.5625
4
from collections import defaultdict class Marble: def __init__(self, number): self.number = number self.previous = self self.next = self def add_next(self, number): next_marble = Marble(number) self.next.previous = next_marble next_marble.next = self.next self.next = next_marble next_marble.previous = self def remove(self): self.previous.next = self.next self.next.previous = self.previous def marble_mania(player, last_marble): current_marble = Marble(0) points = defaultdict(lambda: 0) for i in range(1, last_marble + 1): if i % 23 != 0: current_marble.next.add_next(i) current_marble = current_marble.next.next else: pick = current_marble.previous.previous.previous.previous.previous.previous.previous points[i % player] += i + pick.number current_marble = pick.next pick.remove() return max(points.values()) if __name__ == '__main__': assert 32 == marble_mania(9, 25) assert 8317 == marble_mania(10, 1618) assert 146373 == marble_mania(13, 7999) assert 2764 == marble_mania(17, 1104) assert 54718 == marble_mania(21, 6111) assert 37305 == marble_mania(30, 5807) print("Heighscore: %d" % marble_mania(410, 72059)) print("Heighscore: %d" % marble_mania(410, 72059*100))
8c440e1b948f841260b3befc74c8a9130e5e392a
aalvaradof/X-Serv-Python-Multiplica
/calculadora.py
735
3.796875
4
#!/usr/bin/python3 import sys from sys import argv def help(): print('Usage: calculadora.py function op1 op2') print('Possible functions: sumar restar multiplicar dividir') N_ARGS = 4 if len(sys.argv) != N_ARGS: sys.exit("Invalid number of arguments") func = argv[1] op1 = argv[2] op2 = argv[3] try: op1 = float(op1) op2 = float(op2) except ValueError: help() sys.exit("Introduced not numeric arguments") if func == 'sumar': print(op1 + op2) elif func == 'restar': print(op1 - op2) elif func == 'multiplicar': print(op1 * op2) elif func == 'dividir': try: print(op1 / op2) except ZeroDivisionError: print("Cannot divide by 0") else: sys.exit("Invalid operation")
5306872900fb437bba82f703dc3a39fcfe2d2fc6
anuj-chourasiya/Data-Sructure-in-C
/Trie.py
1,373
3.875
4
from collections import defaultdict class TrieNode: def __init__(self,data): self.data=data self.children=defaultdict(lambda: None) self.freq=0 self.isTerminal=False def __str__(self): return "hey "+(self.data) class Trie: def __init__(self,data): self.root=self.getNode(data) def getNode(self,data): return TrieNode(data) def insert(self,word): pointer=self.root for char in word: if not pointer.children[char]: pointer.children[char]=TrieNode(char) pointer=pointer.children[char] pointer.freq+=1 pointer.isTerminal = True def firstOne(self,word): ans="" pointer=self.root for char in word: if pointer.freq>1 or pointer.freq==0: ans+=char pointer=pointer.children[char] elif pointer.freq==1 : return ans if pointer.freq==1: return ans return -1 def uniqueSmallestPrefix(words): root=Trie(0) ans=[] for word in words: root.insert(word) for word in words: ans.append(root.firstOne(word)) return ans inp=["don","duck","donhaihum","dont","anuj","aman"] ans=uniqueSmallestPrefix(inp) print(inp) print(ans)
ac539d583de0ec8897fcd603203f30db94bf7eb9
sachin3496/PythonCode
/batch10_dec_2018/tic_tac_toe.py
4,070
3.5625
4
from itertools import permutations import sys import random import os import time def win(data): win_comb = [ (1,2,3), (1,4,7), (1,5,9), (2,5,8), (3,6,9), (3,5,7),(4,5,6), (7,8,9) ] player_comb = list(permutations(sorted(data),3)) for comb in win_comb: if comb in player_comb : return True else : return False def print_board(msg): clr_scr() print(msg) print("\n\nYour Current Board is : \n") for var in board : print("\t\t\t","-"*19) print("\t\t\t","| | | |") print("\t\t\t",f"| {var[0]} | {var[1]} | {var[2]} |") print("\t\t\t","| | | |") print("\t\t\t","-"*19) print("\n\n") def choice(player): possible_choices = [ '1','2','3','4','5','6','7','8','9' ] print("\n\nLeft Positions : ",*total_pos) ch = input(f"\n\n{player} pos : ") if ch in possible_choices : ch = int(ch) if ch in covered_pos : print_board("") print("\n\nThat Position is Already Choosen Please Select Another Position \n\n") return choice(player) else : covered_pos.append(ch) total_pos.remove(ch) return ch else : print_board("") print("\n\nInvalid Choice please Select only 1-9 positions \nTry Again\n\n") return choice(player) def play_game(p_list): c = 1 ch1 = choice(p_list[1][0]) p_list[1][2].append(ch1) pos_ch1 = pos.get(ch1) board[pos_ch1[0]][pos_ch1[1]] = p_list[1][1] print_board(f'\n\nAfter move {c} the board is ') if win(p_list[1][2]) : print(f"\n\nPlayer {p_list[0][0]} has won the Game\n\n") return True c = c + 1 k = 1 while k <= 4 : ch1 = choice(p_list[0][0]) p_list[0][2].append(ch1) pos_ch1 = pos.get(ch1) board[pos_ch1[0]][pos_ch1[1]] = p_list[0][1] print_board(f'\n\nAfter move {c} the board is ') if win(p_list[0][2]) : print(f"\n\nPlayer {p_list[0][0]} has won the Game\n\n") break c = c + 1 ch1 = choice(p_list[1][0]) p_list[1][2].append(ch1) pos_ch1 = pos.get(ch1) board[pos_ch1[0]][pos_ch1[1]] = p_list[1][1] print_board(f'\n\nAfter move {c} the board is ') if win(p_list[1][2]) : print(f"\n\nPlayer {p_list[1][0]} has won the Game\n\n") break c = c + 1 k = k + 1 else : print(f"\n\nwoooo...Match is Tie Between {p_list[0][0]} and {p_list[1][0]}\n\n") def clr_scr(): os.system('cls') print('\n\n\n') if __name__ == "__main__" : player1 = input("\n\nEnter Player one name : ") player2 = input("\n\nEnter player two name : ") while True : clr_scr() print("\n\nWelcome to Tic Tac Toe Game\n\n") pos = { 1:(0,0), 2:(0,1), 3:(0,2), 4:(1,0), 5:(1,1), 6:(1,2), 7:(2,0),8:(2,1),9:(2,2) } board = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] print_board('\t\tHere are the key Positions to select your move') input("\n\nPress Enter key to Continue Game ") board = [ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' '] ] print_board('\t\tafter initial Move the board is ') time.sleep(2) clr_scr() print("\n\nSymbols --> X and 0 ") print("\n\nChoosing The Symobls for each Player") symbol = [ 'X', '0'] random.shuffle(symbol) print(f'\n\n{player1} symbol is - {symbol[0]}') print(f'\n\n{player2} symbol is - {symbol[1]}') p_list = ( ( player1, symbol[0],[] ),( player2, symbol[1],[] ) ) total_pos = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] covered_pos = [] input("\nPress Any key to Start Game ".center(300)) print_board('Initial Status of Board') play_game(p_list) if input("\n\nDo want to play again : ") : continue else : break
010a132e2ef0c05b75d9c72307d09ca94aa21732
MeiJohnson/compmath
/newton.py
1,395
3.609375
4
import math def f(arg): return arg**3 - 2 * arg**2 + 3 * arg - 5 def df(arg): return 3 * arg**2 - 4 * arg + 3 def ddf(arg): return 6 * arg - 4 def newton(): a = 1 b = 2 e = 0.000001 cntA = 0 cntB = 0 x = a xi = x-f(x)/df(x) cntA += 1 print("a =", a, "b =", b, "eps =", eps, "x0 =", x) while abs(xi - x) > e: x = xi xi = x - f(x)/df(x) cntA += 1 print("Answer A", round(xi, 6),"Count of cycles", cntA) x = b xi = x - f(x)/df(x) cntB += 1 while abs(xi - x) > e: x = xi xi = x - f(x)/df(x) cntB += 1 print("Answer B", round(xi, 6),"Count of cycles", cntB) def f_ind(arg): return arg * math.log10(arg+1) - 1 def df_ind(arg): return (arg+(arg+1)*math.log(arg+1))/((arg+1)*math.log(10)) def ddf_ind(arg): return (arg+2)/((arg+1)*(arg+1)*math.log(10)) def ind_newton(): a = 0 b = 10 e = 0.000001 cntB = 0 x = b xi = x - f_ind(x)/df_ind(x) cntB += 1 print("a =", a, "b =", b, "eps =", eps, "x0 =", x) while abs(xi - x) > e: x = xi xi = x - f_ind(x)/df_ind(x) cntB += 1 print("Answer B", round(xi, 6),"Count of cycles", cntB) def main(): print("x^3-2*x^2+3*x-5=0") newton() print("x*lg(x+1)=1") ind_newton() if __name__ == "__main__": main()
53db74810935731d80a071d178185dbe4f7cdd31
SurajPatil314/Leetcode_Fundamental
/LinkedList/reverseLinkedList.py
651
3.90625
4
""" Reverse a singly linked list. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: temp = [] temp5 = head while (head != None): temp.append(head.val) head = head.next i = 0 print(len(temp)) if len(temp) == 0: return None temp8 = temp5 while (len(temp) > 0): print("qq") temp8.next = ListNode(temp.pop()) temp8 = temp8.next return temp5.next
1312a85c36066029066f2b3d9753b278bc4c4ee3
SurajPatil314/Leetcode_Fundamental
/LinkedList/checkPalndromeLinkedList.py
936
3.796875
4
""" Given a singly linked list, determine if it is a palindrome. """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: temp2 = head3 temp = [] i = 0 while (temp2 != None): temp.append(temp2.val) temp2 = temp2.next print(temp) if len(temp) < 2: return True r = q = int(len(temp) / 2) if len(temp) % 2 == 1: while (q > 0): if (temp[q - 1] != temp[r + 1]): return False q = q - 1 r = r + 1 else: print(q) while (q > 0): if (temp[q - 1] != temp[r]): return False q = q - 1 r = r + 1 return True
7bc5e5d8883fef3affe01b8dcfc80ce1845f46a8
connorjclark/learn-code
/code/roll.py
373
3.75
4
import random import sys def roll(min, max): return random.randint(min, max) def play_round(): result = roll(1, 6) print("You got " + str(result)) if result == 6: print("Nice!") if result == 1: print("not good...") play = True while play: play_round() answer = input("Roll again? y/n: ") if (answer != "y"): play = False print("Bye!")
3f4fe3c9790c8839f9d3c32116fa12d1194e0933
baschte83/os-synchronisation
/LibrarySynchronization.py
4,776
4.0625
4
from sys import argv from time import sleep import threading # semaphore objects # lock objects for book1 copies semBook1 = threading.BoundedSemaphore(3) # lock objects for book2 copies semBook2 = threading.BoundedSemaphore(2) # lock objects for book3 copies semBook3 = threading.BoundedSemaphore(2) # lock objects for global counter how many times 3 books were lend counterSem = threading.BoundedSemaphore() # lock objects for global counter how many times each student lend 3 books counterListSem = threading.BoundedSemaphore() # lock objects for global boolean whether a student has all three books now or not hasAllBooksListSem = threading.BoundedSemaphore() # function to lend a copy of each book def lend_the_books(): # definition of several global variables global waiting_time global counter_list global counter global hasAllBooksList global output_interval # while loop to acquire and release all 3 books while True: # acquiring of all three books semBook1.acquire() semBook2.acquire() semBook3.acquire() # entering "True" in list hasAllBooksList because this student process # has a copy of all three books hasAllBooksListSem.acquire() hasAllBooksList[int(threading.currentThread().getName()) - 1] = True hasAllBooksListSem.release() # this student process has now to "read" its three books # for waiting_time seconds sleep(float(waiting_time)) # several outputs # increase the counter variable which counts, how often three books # were lent over all student processes counterSem.acquire() counter += 1 # increase the counter in list counter_list which stores how often # this special student process has lent all three books counterListSem.acquire() counter_list[int(threading.currentThread().getName()) - 1] += 1 # "if" handles how often we print our outputs to the console. # If output_interval is 1, every time all three books were lent this output # is printed to the console. If output_interval = 100, every 100 loans # this output is printed to the console. if counter % output_interval == 0: # for loop prints how often every single student process has lent all three books for i in range(int(amountStudents)): print("Student " + str(i + 1) + " hat " + str(counter_list[i]) + " Mal alle drei Buecher bekommen!\r") print("") # for loop prints, which student processes have all three books at the moment for j in range(int(amountStudents)): if hasAllBooksList[j]: print("Student " + str(j + 1) + " hat aktuell alle drei Buecher.\r") print("") counterListSem.release() counterSem.release() # releasing of all three books semBook1.release() semBook2.release() semBook3.release() # entering "False" in list hasAllBooksList because this student process # has no copy of any of the three books hasAllBooksListSem.acquire() hasAllBooksList[int(threading.currentThread().getName()) - 1] = False hasAllBooksListSem.release() # main function def main(): # list to start and collect a thread for every student students = [] # for loop creates the required amount of student processes, # appends the current created student process in our list students # of student processes, initializes the corresponding loan counter # of this current created student process in list counter_list, sets the # corresponding boolean in list hasAllBooksList of this current # created student process to false (because it has not all three books # at the moment) and starts the current created student process. for i in range(int(amountStudents)): t = threading.Thread(target=lend_the_books, name=str(i + 1)) students.append(t) counter_list.append(0) hasAllBooksList.append(False) t.start() # for loop joins all student processes for student in students: student.join() # reads number of students from console input (first argument) amountStudents = argv[1] # time a student has to "read" when he/she has all three books (second argument) waiting_time = argv[2] # time a student has to "read" when he/she has all three books (second argument) output_interval = 20 # counter for how many times 3 books were lent counter = 0 # list how many times each student lend 3 books counter_list = [] # list of boolean whether a student has all three books now or not hasAllBooksList = [] # call of main function main()
4718c3808d9323e5e39f1c76fa77b0ad5c175ed9
DivyaraniPhondekar/PythonCode
/date and time.py
425
3.515625
4
import time; import calendar; ticks=time.time() print ("Number of ticks since 12:00am, January 1, 1970:", ticks) print (time.localtime()) localtime = time.asctime( time.localtime()) print ("Local current time :", localtime) cal = calendar.month(2016, 2) print ("Here is the calendar:") print (cal) print ("time.altzone : ", time.altzone) t = time.localtime() print ("asctime : ",time.asctime(t))
412efbd9c79764a161482cb43adcea5b50d0228d
DivyaraniPhondekar/PythonCode
/list.py
538
3.875
4
squares = [] for x in range(1, 11): squares.append(x**2) for x in squares: print x list1 = ['physics', 'chemistry', 'maths'] print max(list1) # checks ASCII value list1.append('history') print list1 print list1.count('maths') print list1.index('maths') list1.insert(2,'computer science') print list1 list1.pop() print list1 list1.pop(1) print list1 list2=['vishal','divya','swati','aniket','amogh'] list2.remove('amogh') print list2 list2.reverse() print list2 list2.sort() print list2
b245f8a691c067e69b89212cd9bb2fff8ee50128
curiousTauseef/cryptography-codes
/diffiehellman.py
1,943
3.578125
4
import random import math def rabinMiller(num): # Returns True if num is a prime number. s = num - 1 t = 0 while s % 2 == 0: s = s // 2 t += 1 for trials in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: # this test does not apply if v is 1. i = 0 while v != (num - 1): if i == t - 1: return False else: i = i + 1 v = (v ** 2) % num return True def isPrime(num): if (num<2): return False lowPrimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59]; if num in lowPrimes: return True for prime in lowPrimes: if (num%prime==0): return False return rabinMiller(num) def generate_random_prime(): while True: num=random.getrandbits(16) if isPrime(num): return num def choose_primitive_root(p): while True: alpha=random.randrange(2,p-2) visited={} #print("alpha ",alpha) for i in range(1,p): #print(i) val=pow(alpha,i,p) if val not in visited: visited[val]=1 else: break if len(visited)==p-1: return alpha # Diffie Hellman Setup p=generate_random_prime() print("Modulus: ",p) alpha=choose_primitive_root(p) print("Primitive root: ",alpha) # Diffie Hellman Key exchange # Alice's parameters a=random.randrange(2,p-2) # Private key of Alice A=pow(alpha,a,p) # Public key of Alice # Bob's parameters b=random.randrange(2,p-2) # Private key of Alice B=pow(alpha,b,p) # Public key of Alice # Session key k1=pow(B,a,p) # Computed by Alice k2=pow(A,b,p) # Computed by Bob if k1==k2: print("Shared session key is: ",k1) else: print("Some error in Diffie Hellman algo")
aebe705c785b68173e4eb3ba196dd27297f6348f
Zhangchuchu1234/MH8811-G1902372H
/06/H1.py
405
3.765625
4
from passwordGenerator import genPassword try: password_length = int(input("Please input the password length (larger or equal to 4): ")) except: print("Input error!") exit() if password_length < 4: print("Input length should be larger or equal to 4! ") exit() password = genPassword(password_length) print("A random password of length {0} is {1}".format(password_length, password))
a1ea84b418022f06070c6155f758f9d980b519bb
moisescantero/keepcoding_bc5_reto_binario_entero
/bin_int_tests.py
1,129
3.796875
4
"""módulo para hacer tests a módulo bin_int_module.py""" import unittest#importar para test de pruebas import bin_int_module#para comprobar funcionalidad class bin_int_test(unittest.TestCase): def test_bin_int(self): self.assertEqual(bin_int_module.convert_bit_int("001"), 1) self.assertEqual(bin_int_module.convert_bit_int("110"), 6) self.assertEqual(bin_int_module.convert_bit_int("211"), "Error de formato") self.assertEqual(bin_int_module.convert_bit_int("kkk"), "Error de formato") self.assertEqual(bin_int_module.convert_bit_int("011001110"), 206) self.assertEqual(bin_int_module.convert_bit_int("101110"), 46) self.assertEqual(bin_int_module.convert_bit_int("11111110000011010001100111111000111"), 34098171847) self.assertEqual(bin_int_module.convert_bit_int("00k10"), "Error de formato") self.assertEqual(bin_int_module.convert_bit_int("k0k1k"), "Error de formato") if __name__ == "__main__":#esto se pone para que al llamar en la consola python bin_int_tests.py ejecute y compruebe los errores de arriba unittest.main()
f76c1e50db88f9f61b22f0a655faf0ff1ed817f7
ryanhgunn/learning
/unique.py
382
4.21875
4
# A script to determine if characters in a given string are unique. import sys string = input("Input a string here: ") for i in range(0, len(string)): for j in range(i + 1, len(string)): if string[i] == string[j]: print("The characters in the given string are not unique.") sys.exit(0) print("The characters in the given string are unique.")
1146076cdd44cc42fe31f4b7ae3d4e36c670ffa9
liramirez/setp01
/Lab N°1/fibonacci.py
832
4.0625
4
#~~~~~~~~~~~~~~~~~~~~~~~~~~# #Nombre : Lizzie Ramirez #Fecha : 28-Abril-2013 #Actividad : 3 - Fibonacci Lab N°1 #~~~~~~~~~~~~~~~~~~~~~~~~~~# #~~~~~~~~~~~~~~~~~~~~~~~~~~# #Declaración de funciones #~~~~~~~~~~~~~~~~~~~~~~~~~~# def fibo(n): if(n==0): return 0 else: if (n==1): return 1 else: return (fibo (n-1) + fibo (n-2)) #~~~~~~~~~~~~~~~~~~~~~~~~~~# #Declaración de funcion principal #~~~~~~~~~~~~~~~~~~~~~~~~~~# def main(): num=input("Ingrese el numero del termino de la serie fibonacci que desea mostrar : ") a=fibo(int(num)) print("El termino ",num," de la serie fibonacci es ",a) return 0 #~~~~~~~~~~~~~~~~~~~~~~~~~~# #Identificador del main #~~~~~~~~~~~~~~~~~~~~~~~~~~# if __name__ == '__main__': main() #~~~~~~~~~~~~~~~~~~~~~~~~~~#
44e5468f266e9019b04d4b7e91812dbe87cc5a96
AlexFSmirnov/Tanks
/py/maze_gen.py
2,174
3.6875
4
from random import randint class Cell: def __init__(self, state, right=0, bottom=0, color=0): self.st = state self.right = right self.bottom = bottom def copyline(prevline): newline = [] for pc in prevline: newcell = Cell(pc.st, pc.right, pc.bottom) newline.append(newcell) return newline def genline(prevline, w, last = 0): line = copyline(prevline) if last: #generating last line for i in range(len(line) - 1): line[i].bottom = 1 line[i].right = 0 line[i + 1].bottom = 1 return line[::] used = set() for cell in line: # Preparing the line for the next generation cell.right = 0 if cell.bottom: cell.st = 0 used.add(cell.st) cell.bottom = 0 if 0 in used: used.remove(0) for cell in line: if not cell.st: cell.st = max(used) + 1 used.add(cell.st) for i in range(len(line)): #generating RIGHT border if i < len(line) - 1: if randint(0, 1): if line[i].st != line[i + 1].st: line[i].right = 1 elif line[i].st == line[i + 1].st: line[i].right = 1 else: line[i + 1].st = line[i].st else: line[i].right = 1 #generating BOTTOM border if randint(0, 1): cnt = 0 for j in line: if j.st == line[i].st and j.bottom == 0: cnt += 1 if cnt > 1: line[i].bottom = True return copyline(line) def maze_gen(w, h): prevline = [Cell(i + 11) for i in range(w)] maze = [[Cell(-1, 1, 1, 0) for i in range(w + 2)]] for i in range(h): if i == h - 1: line = genline(prevline, w, 1) else: line = genline(prevline, w) newline = [Cell(-1, 1, 1, 0)] + line + [Cell(-1, 1, 1, 0)] maze.append(newline) prevline = copyline(line) maze.append([Cell(-1, 1, 1, 0) for i in range(w + 2)]) return maze
d279398b290a9f0320bacaa23864b3be614100c3
AndrewGreen96/Python
/math.py
1,217
4.28125
4
# 4.3 Counting to twenty # Use a for loop to print the numbers from 1 to 20. for number in range(1,21): print(number) # 4.4 One million # Make a list from 1 to 1,000,000 and use a for loop to print it big_list = list(range(1,1000001)) print(big_list) # 4.5 Summing to one million # Create a list from one to one million, use min() and max() to check that it starts at 1 and ends at 1000000 and then sum all of the elements from the list together. onemillion = list(range(1,1000001)) print(min(onemillion)) print(max(onemillion)) print(sum(onemillion)) # 4.6 Odd numbers # Make a list of the odd numbers from 1 to 20 and use a for loop to print each number. odd_numbers = list(range(1,21,2)) for odd in odd_numbers: print(odd) print('\n') # 4.7 Threes # Make a list of the multiples of 3 from 3 to 30 and then print it. threes =list(range(3,31,3)) for number in threes: print(number) # 4.8 Cubes # Make a list of the first 10 cubes. cubes = list(range(1,11)) for cube in cubes: print(cube**3) # 4.9 Cube comprehension # Use a list comprehension to generate a list of the first 10 cubes. cubes =[cube**3 for cube in range(1,11)]
bc890f0f40a7e9c916628d491e473b5ecfa9bb9b
JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT
/Source_Code/Restaurant_Environment/simulatedtempiot.py
1,492
3.734375
4
from random import random import numpy as np class TemperatureSensor: sensor_type = "temperature" unit="celsius" instance_id="283h62gsj" #initialisation def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature): self.average_temperature = average_temperature self.temperature_variation = temperature_variation self.min_temperature = min_temperature self.max_temperature= max_temperature self.value = 0.0 #initialise current temp value #sensing def sense(self): #self.value = self.value + self.simple_random() self.value = self.complex_random() + self.noise() return self.value #noise def noise(self): self.noise_value = np.random.normal(0,1) return self.noise_value #helper function for generating values with min temp as its base def simple_random(self): value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature)) #so that it is in the range return value def complex_random(self): value = self.average_temperature * (1 + (self.temperature_variation/100) * (1 * random() -1)) value = max(value,self.min_temperature) value = min(value,self.max_temperature) return value #creating instance of sensor ts = TemperatureSensor(25,10,16,35)
00ad5d687e667948ad3a0fa1c785dcce1454c33f
JanaranjaniPalaniswamy/Safety-Monitoring-in-Restaurants-based-on-IoT
/Source_Code/Restaurant_Environment/simulatedweightiot.py
1,384
3.578125
4
from random import random import numpy as np class WeightSensor: sensor_type = "weight" unit="kg" instance_id="285h62gsj" #initialisation def __init__(self, average_weight, weight_variation, min_weight, max_weight): self.average_weight = average_weight self.weight_variation = weight_variation self.min_weight = min_weight self.max_weight= max_weight self.value = 0.0 #initialise current temp value #sensing def sense(self): #self.value = self.value + self.simple_random() self.value = self.complex_random() + self.noise() return self.value #noise def noise(self): self.noise_value = np.random.normal(0,0.5) return self.noise_value #helper function for generating values with min temp as its base def simple_random(self): value = self.min_weight + (random() * (self.max_weight - self.min_weight)) #so that it is in the range return value def complex_random(self): value = self.average_weight * (1 + (self.weight_variation/100) * (1 * random() -1)) value = max(value,self.min_weight) value = min(value,self.max_weight) return value #creating instance of sensor ws = WeightSensor(25,30,15.3,29.5)