blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
97e9c17d52538cb992d6395ff15bbe24b067d43c
gbordyugov/playground
/coding/codility-and-leetcode/nesting.py
558
3.828125
4
# Codility. Nesting def nesting(S): count = 0 if not len(S): return 1 for i in S: if i == '(': count += 1 else: count -= 1 if count < 0: return 0 return 0 if count else 1 print(nesting('()()()')) print(nesting('(()(())())')) print(nesting('(()')) print(nesting('(((')) print(nesting('')) print(nesting('))((')) print(nesting('((((')) print(nesting(')()(')) print(nesting('(()()()()()())')) print(nesting('(')) print(nesting('()((()())')) print(nesting('())(()'))
66c697adc51a01a759c883c66b48dd1f3fd297e8
bewbew2/algorithmicToolbox
/Week1/maximum_pairwise_product_4.py
696
4
4
# python3 # implement the "faster algorithm" def swap(ls, ind1, ind2): # swap list[ind1] with list[ind2] ls[ind1], ls[ind2] = ls[ind2], ls[ind1] return ls def max_pairwise_product_fast(numbers): n = len(numbers) - 1 index = 0 for i in range(1, n): if numbers[i] > numbers[index]: index = i swap(numbers, index, n) index = 0 for i in range(0, n): if numbers[i] > numbers[index]: index = i swap(numbers, index, n-1) return numbers[n-1] * numbers[n] if __name__ == '__main__': input_n = int(input()) input_numbers = [int(x) for x in input().split()] print(max_pairwise_product_fast(input_numbers))
cbc2bcf236adb7815e333c8b478fea0b18912411
vikingliu/alg
/classic/walk.py
495
3.953125
4
# coding=utf-8 def walk(N, m, p, k, path=[]): """ 多少种走法 :param N: :param m: start :param p: end position :param k: k-step :param path: from m to p steps :return: """ step = len(path) if step > k or m > N or m < 1: return 0 if m == p and k == step: print(path) return 1 return walk(N, m + 1, p, k, path + [1]) + walk(N, m - 1, p, k, path + [-1]) if __name__ == '__main__': print(walk(5, 2, 4, 4))
734bb2bda36caf6d7ef82d37e277af3226815179
Averaguilar/Traffic-Lights
/intersection.py
1,910
3.734375
4
"""This module holds the implementation of the Intersection class.""" import copy import distributions import road import state import traffic_light class Intersection(object): """Models the state of all roads and their interaction.""" def __init__(self): """Initialize the intersection with two roads.""" self._roads = [road.Road(traffic_light.TrafficLight.RED, distributions.Probability.STANDARD), road.Road(traffic_light.TrafficLight.GREEN, distributions.Probability.STANDARD)] self._switch_time = 0 self._to_switch = None def get_state(self): """Returns the state of the intersection used by the learning module.""" return state.State(self._roads, self._switch_time) def get_performance(self): """Gets the number of cars waiting since it was last called.""" performance = 0 for curr_road in self._roads: performance += curr_road.get_amount_queued() curr_road.reset_queueing() return performance def update_state(self, switch_lights): """Update the state of the roads and potentially switches the lights.""" if switch_lights: assert self._switch_time == 0 for curr_road in self._roads: if curr_road.light_color() == traffic_light.TrafficLight.GREEN: curr_road.flip_color() else: self._to_switch = curr_road self._switch_time = 3 elif self._switch_time != 0: self._switch_time -= 1 if self._switch_time == 1: self._to_switch.flip_color() for curr_road in self._roads: curr_road.update() def get_roads(self): """Get a copy of the roads in the intersection.""" return copy.deepcopy(self._roads)
6c8489b3f8f24c48be839353da192219f230e168
mmall77/malleus_python_challenge
/PyBank/main.py
1,789
3.84375
4
import os import csv # file path to csv file company_data = os.path.join("..", "Resources", "budget_data.csv") # data function deprecated #def companyInfo(company_data): ## list out the names of all variables for calculations ## set variables = 0 to initialize totalMonths = 0 totalProfit = 0 avgChange = 0 greatestIncrease = 0 greatestDecrease = 0 highestMonth = "" lowestMonth = "" change = 0 previousprofloss = 0 changes = [] # read in csv file + skip the headers and store them in a variable "header" in case needed with open(company_data, "r") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") header = next(csvreader) # for loop to iterate through each row of the cols in the csv file totalProfit iterates # through column index 1 to count the profit/losses. for row in csvreader: date = row[0] profloss = int(row[1]) totalProfit += profloss totalMonths += 1 # calculates greatest increase and greatest decrease and avg change. change = profloss - previousprofloss if totalMonths != 1: changes.append(change) if change > greatestIncrease: greatestIncrease = change highestMonth = date if change < greatestDecrease: greatestDecrease = change lowestMonth = date previousprofloss = profloss avgChange = int(round(sum(changes)/len(changes), 2)) # results to terminal data = f""" Total Profit: ${totalProfit} Total Months: {totalMonths} Average Monthtly Change: ${avgChange} Greatest Increase: {highestMonth}, ${greatestIncrease} greatest Decrease: {lowestMonth}, ${greatestDecrease}""" print(data) # out[ut results to txt file output_file = "output.txt" with open(output_file, "w") as doc: doc.write(data)
b2cb7bfd876a7f8bf8741b64cdfa4d4893c1fa90
JariMutikainen/timeCard
/working_day.py
7,066
3.828125
4
''' This file defines the class, which contains all the methods and attributes of one working day. The data is stored in a json file on the disk. ''' import json from time import strftime from day import Day from history_if import HistoryInterface from hhmm import HhMm # Self made time format of 'HH:MM' - like '03:45' class WorkingDay(Day): ''' WorkingDay inherits the __repr__()-method from the Day. It inherits the __init__()-method from the Day, but extends that method by fetching the contents for the instance attributes from the disk. A WorkingDay consists of logins and logouts. Each time the user logs in or out the time stamp of the event is recored and stored in the list of events. All the instance data is maintained in an external file on the disk. Each time a new event takes place the data is loaded from the disk, the new event is recorded an the data is dumped back into the disk. In addition to the login and logout methods this class offers methods for manually adding or subtracting time from the balance. ''' #FILE_OUT = 'temporary.json' #FILE_IN = 'currently_in.json' #FILE_IN = 'currently_out.json' FILE_IN = 'today.json' FILE_OUT = 'today.json' def __init__(self): super().__init__() self.load_working_day() # Load the data from an external file def dump_working_day(self): '''Śtores the data of the working day into the disk.''' with open(WorkingDay.FILE_OUT, 'w') as fh: # Make a dict of the working day to be stored in an external # .json-file on the disk. frozen = self.day_to_dict() json.dump(frozen, fh, indent=4, separators=(',', ': ')) def load_working_day(self): '''Loads the data of the working day from the disk.''' try: with open(WorkingDay.FILE_IN, 'r') as fh: unfrozen = json.load(fh) # unfrozen is a dict containing data of one working day. # Suck that data into the instance self of the class # WorkingDay. self.dict_to_day(unfrozen) except FileNotFoundError: self.date = '17.06.1964' self.now_at_work = False self.morning_balance = '00:00' self.dipped_balance = '00:00' self.balance = '00:00' self.events = [] def login(self): ''' This method records the time stamp of a login event and updates the data of the working day on the disk accordingly. ''' self.load_working_day() time_stamp = strftime('%H:%M') date_stamp = strftime('%d.%m.%Y') day_name = strftime('%A') if self.now_at_work: print("\nCan't log you in, because you are already in.\n") self.show_working_day() return if date_stamp != self.date: # The first time stamp of a new day. # Instantiate a history interface and append the previous working # day into the end of the history file before initializing 'today'. HistoryInterface().append_working_day(self) # Initialize a new working day self.date = date_stamp self.day_name = day_name self.now_at_work = True self.morning_balance = self.balance # Subtract the daily target hours from the morning balance. t_morning = HhMm(self.morning_balance) # The TARGET_HOURS for a weekend day is Zero. if self.day_name in ('Saturday', 'Sunday'): t_target = HhMm('00:00') else: t_target = HhMm(Day.TARGET_HOURS) self.dipped_balance = str(t_morning - t_target) self.balance = self.dipped_balance self.events = [ [time_stamp, 'in', self.balance] ] self.dump_working_day() self.show_working_day() else: # A new login at an already existing day self.now_at_work = True self.events += [ [time_stamp, 'in', self.balance] ] self.dump_working_day() self.show_working_day() def logout(self): ''' This method records the time stamp of a logout event and updates the data of the working day on the disk accordingly. ''' self.load_working_day() time_stamp = strftime('%H:%M') date_stamp = strftime('%d.%m.%Y') if not self.now_at_work: print("\nCan't log you out, because you are already out.\n") self.show_working_day() return if date_stamp != self.date: print("You can't start a new working day by making a logout.\n" "Did you forget to logout yesterday?") self.show_working_day() return self.now_at_work = False # We have to retrieve the latest login time from the self.events # to be able to determine, how many hours to add into the balance # at this logout moment. #last_login_time = self.events[-1][0] last_login_time = self.get_latest_login() t1 = HhMm(last_login_time) t2 = HhMm(self.balance) t3 = HhMm(time_stamp) print(f'last-login: {t1}, balance before: {t2}, time stamp: {t3}') self.balance = str(t2 + (t3 - t1)) print(f'Balance after. {self.balance}') self.events += [[time_stamp, 'out', self.balance]] self.dump_working_day() self.show_working_day() def get_latest_login(self): ''' Returns the time stamp of the latest login. The important thing is not to return the last time stamp of the current day but rather the last time stamp of the current day with "in" as the direction. Bug fix 2.3.2019 by Jari M. ''' indx = -1 while self.events[indx][1] != "in": #events[][1] contains the direction indx -= 1 return self.events[indx][0] # events[][0] contains the time stamp def increment(self, time_s): ''' Increments the Current Balance by time_s. time_s is a string in the format '02:34' ''' self.load_working_day() self.balance = str(HhMm(self.balance) + HhMm(time_s)) self.events += [[time_s, 'inc', self.balance]] self.dump_working_day() self.show_working_day() def decrement(self, time_s): ''' Decrements the Current Balance by time_s. time_s is a string in the format '02:34' ''' self.load_working_day() self.balance = str(HhMm(self.balance) - HhMm(time_s)) self.events += [[time_s, 'dec', self.balance]] self.dump_working_day() self.show_working_day() if __name__ == '__main__': # Testing wd = WorkingDay() #wd.dump_working_day() #print(wd) #wd.login() wd.logout() #wd.increment('02:30') #print(wd) #wd.decrement('01:20') #print(wd)
a70dcc1b2623b7cf626bc6cdb5961cb1d3e5cae4
wegitor/IDZ
/lab5/lab5.py
5,088
3.578125
4
import math class treeN: #self.arr_child=[] #data=None def __init__(self,Data,attr=None): self.data=None self.arr_child=[] self.data=Data self.ar=None self.atr=attr def addLeaf(self,Leaf): self.arr_child.append(Leaf) def addLeafs(self,*args): for i in args: self.addLeaf(i) def setLeaf(self,Num,Leaf): self.arr_child[Num]=Leaf def upDown(self): print 'node:',self.data, if self.atr!=None: print 'atr:',self.atr, for i in self.arr_child: i.upDown() print ' return' def upDownL(self,list): if self.arr_child==[]: print self.data for i in self.arr_child: if i.atr==list[self.data]: i.upDownL(list) input_d=[[0, 0, 0, 1, False], [0, 0, 1, 0, False], [0, 1, 0, 2, True], [0, 1, 1, 1, False], [0, 1, 1, 2, False], [1, 1, 1, 1, False], [1, 1, 0, 0, True], [1, 1, 1, 1, True], [2, 0, 0, 0, True], [2, 0, 0, 1, True], [2, 0, 0, 2, False], [2, 0, 1, 0, False], [2, 0, 1, 2, False], [2, 1, 0, 2, True]] input_d=[[0, 2, 0, 0, False], [0, 2, 0, 1, False], [1, 2, 0, 0, True], [2, 1, 0, 0, True], [2, 0, 1, 0, True], [2, 0, 1, 1, False], [1, 0, 1, 1, True], [0, 1, 0, 0, False], [0, 0, 1, 0, True], [2, 1, 1, 0, True], [0, 1, 1, 1, True], [1, 1, 0, 1, True], [1, 2, 1, 0, True], [2, 1, 0, 1, False]] """ """ def get_range(ar,col): return 0 def logg(x,base): if x==0: return 0 else: return math.log(x,base) def estim_count(ar,col): #print 'est size: ', len(ar) , 'col: ',col #print 'est in:',ar tmp_tr=[] tmp_fa=[] lenc=len(ar[0])-1 i=0 while i in range(lenc): #print 'len: ',lenc,'i: ',i tmp_tr.append(0); tmp_fa.append(0) for el in ar: if el[col]==i: #print 'end el: ', el[len(el)-1] if el[len(el)-1]: tmp_tr[i]+=1 else: tmp_fa[i]+=1 if tmp_tr[i]==0 and tmp_fa[i]==0:#delete elem if is not in range #print 'ok' del tmp_tr[i] del tmp_fa[i] lenc-=1 continue i+=1 tmp_tr.append(0) tmp_fa.append(0) for el in ar: if el[len(el)-1]: tmp_tr[len(tmp_tr)-1]+=1 else: tmp_fa[len(tmp_fa)-1]+=1 #print tmp_tr,tmp_fa E=0 for i in range(len(tmp_tr)-1): val=tmp_tr[i]+tmp_fa[i] val1=(float)(tmp_tr[i])/(float)(val) val2=(float)(tmp_fa[i])/(float)(val) #print val, val1,val2 E+=val*(-(val1*logg(val1,2)) - val2*logg(val2,2) ) #print E E/=len(ar) tr=tmp_tr[len(tmp_tr)-1] fa=tmp_fa[len(tmp_fa)-1] val=tr+fa val1=(float)(tr)/(float)(val) val2=(float)(fa)/(float)(val) gain= ((-(val1*logg(val1,2)) - val2*logg(val2,2) )-E) #print 'Gain:',gain return gain def column(matrix, i): return [row[i] for row in matrix] def dif(ar): ells=column(ar,len(ar[0])-1) tmp=ells[0] for el in ells[1:]: if el!=tmp: return False return True def tree_build(ar,list_c ,atr=None): print 'tree:',ar #print len(ar[0])-1 #if dif(ar, len(ar[0])-1): # return treeN('-',atr)#ar[0][len(ar)-1]) list_tmp=[] len_col=len(ar[0]) for i in range(len_col-1): list_tmp.append(estim_count(ar,i)) print 'estim_count',list_tmp #if len(ar[0])<2: #print 'less: ',ar coll=list_tmp.index(max(list_tmp)) #rint 'len',(len(input_d[0])-1)-(len(ar[0])-1)+coll numCol=(len(input_d[0])-1)-(len(ar[0])-1)+coll numCol=coll col_n=list_c[numCol] print numCol del list_c[numCol] tr=treeN(col_n,atr) tr.ar=ar for i in range(3): tmp_ar=[] for el in ar: #print el[coll],'==',i if el[coll]==i: tmp_el=list(el) #print 'del in: ',el del tmp_el[coll] #print 'after ',tmp_el tmp_ar.append(tmp_el) if tmp_ar!=[]: if not(dif(tmp_ar)) and len(tmp_ar[0])>1: #print 'tr build: ',tmp_ar tr.addLeaf(tree_build(tmp_ar,list(list_c),i)) elif dif(tmp_ar) and len(tmp_ar[0])>1: #print 'create leaf,',tmp_ar[0][len(tmp_ar[0])-1] , tmp_ar tr.addLeaf(treeN(tmp_ar[0][len(tmp_ar[0])-1],i) ) print 'return' return tr tree=tree_build(input_d,range(len(input_d[0])-1)) print tree.data for el in tree.arr_child: print el.data ,': ',el.ar print 'tree print' tree.upDown() #tree.upDownv() #print 'for: ', [2,2,2,2] print 'for: ', [2,1,1,2] #print 'for : ',input_d[0][:-1] print 'is: ', #tree.upDownL(input_d[0][:-1]) #tree.upDownL([2,2,00,1]) tree.upDownL([2,2,1,1])
10da0bb826b9d7c44a8883414b52b574ce4972c0
harmonyrasnick/cs-module-project-hash-tables
/applications/word_count/word_count.py
655
3.921875
4
def word_count(s): cache = {} string = s.lower() ignore = '" : ; , . - + = / \ | [ ] { } ( ) * ^ &'.split(" ") for character in ignore: string = string.replace(character, "") for word in string.split(): if word == "": continue if word not in cache: cache[word] = 1 else: cache[word] += 1 return cache if __name__ == "__main__": print(word_count("")) print(word_count("Hello")) print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.')) print(word_count('This is a test of the emergency broadcast network. This is only a test.'))
7a4376f8d3df6b1970c5208c57bdfd1b5a84f824
Andresmelek/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
838
3.875
4
#!/usr/bin/python3 """ Class student with a list """ class Student(): def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): self_directory = self.__dict__ flag = 0 if type(attrs) is list: for i in attrs: if type(i) is str: flag += 1 if len(attrs) == flag: directory = {} for x in self_directory.keys(): if x in attrs: directory[x] = self_directory[x] return directory else: return self_directory def reload_from_json(self, json): for key, val in json.items(): self.__dict__[key] = val
749783c1d27b3b338c0111a16b03a729dce90241
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/149/28616/submittedfiles/testes.py
241
3.6875
4
# -*- coding: utf-8 -*- import math v=int(input('digite o valor que deseja sacar:')) n20=n//20 a=n-(n20*20) n10=a//10 b=a-(n10*10) n5=b//5 c=b-(n5*5) n2=c//2 d=c-(n2*2) n1=d//1 e=d-(n1*1) print n1 print n2 print n3 print n4 print n4 print n5
4bd4522350adb6a88482d24fe6c2c49649fd88df
kimjane93/udemy-python-100-days-coding-challenges
/day-4-rock-paper-scissors/main.py
2,168
4.09375
4
# Radomization # wrangle deterministic machiines # Python uses a Mersenne Twister - a pseudorandom number generator # khan academy vid on pseudnum gens # Python uses random module methods # diff methods for rand ints, rand whole, random flaoting poitn etc # just import random # random.randint(1,5) # includes start and end # random floating point # random.random() # returns a random floating point number bewteen 0 and 1 but not including 1 # to get a randompflating number between 0 and a larger number, mutople the float from random.random() by the cap number # random_float * 5 # 0.00000 - 4 # random.choice wil randomly pick an items from a list for you etc, passing the list in the paratheses etc # lists in python - data strucutre in python, like arrays # indexing # # append is equvalent of push # .insert(i, x) # .remove(x) - removes first itmf form the list whose values matches x # raises a valueError if no such item exists # .extend - adds a whole nunch of items to end of list # could do .extend(["ab", "cd"]) add those items to the previous list etc # .pop(i) - remvoes teh items at teh given position in the list, and returns it. if no index is specified, removes and returns the last items in the list. # .count() - returns c ount of character in parantehses found in string or list etc. # .index, .sort import random # python module # module is respondible for different bits of functionaltiy for your project, # same principle as when we import a file into another, that's a module your_move = int(input("What do you choose?\nType 0 for Rock, 1 for Paper or 2 for Scissors")) computer_move = random.randint(0, 2) if your_move == computer_move: print("It's A Draw") elif your_move == 0 and computer_move == 1: print("Computer Wins") elif your_move == 1 and computer_move == 2: print("Computer Wins") elif your_move == 2 and computer_move == 0: print("Computer Wins") elif computer_move == 0 and your_move == 1: print("You Win") elif computer_move == 1 and your_move == 2: print("You Win") elif computer_move == 2 and your_move == 0: print("You Win") else: print("Incorrect Input - Forfeit")
11a49a3b979b2a016d003f2b1d429653dbe65687
BenjaminStienlet/CompetitiveProgramming
/tweakers_devv_contest/problem12.py
765
3.578125
4
from queue import PriorityQueue monsters = [300, 600, 850, 900, 1100, 3500] overkill = 0 for monster in monsters: queue = PriorityQueue() queue.put((0, 0)) queue.put((2, 1)) queue.put((0, 2)) queue.put((0, 3)) while monster > 0: t, unit = queue.get() if unit == 0: # warrior monster -= 35 if monster < 0: overkill -= monster queue.put((t+4, 0)) elif unit == 1: # mage monster -= 80 queue.put((t+4, 1)) elif unit == 2: # rogue, primary monster -= 30 queue.put((t+4, 1)) elif unit == 3: # rogue, secondary monster -= 20 queue.put((t+3, 1)) print(overkill)
50f06e85e4b3e6d10ccc72f070d0372c64626acf
fengjisen/python
/20190111/index.py
1,312
4.0625
4
# 打开文件 得到文件句柄并赋值给一个变量 f= open('a.txt','r',encoding='utf-8') #通过句柄对文件操作 data = f.read() print(data) # close file f.close() ''' 打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为: 1、f.close() #回收操作系统级打开的文件 2、del f #回收应用程序级的变量 其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源, 而python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close() 虽然我这么说,但是很多同学还是会很不要脸地忘记f.close(),对于这些不长脑子的同学,我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文 with open('a.txt','w') as f: pass with open('a.txt','r') as read_f,open('b.txt','w') as write_f: data=read_f.read() write_f.write(data) 注意 ''' with open('a.txt','r',encoding='utf-8') as read_f,open('b.txt','w',encoding='utf-8') as write_f: data = read_f.read() write_f.write(data) # with会自动关闭这些流操作
8c641802ca2758d0d06c532f9147159d1789dd83
cchun319/SLAM-Learning
/HW/HW4/p2.py
8,664
3.5
4
import gym import numpy as np import torch as th import torch.nn as nn import random from tqdm import tqdm from matplotlib import pyplot as plt """ Description: A pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The pendulum starts upright, and the goal is to prevent it from falling over by increasing and reducing the cart's velocity. Source: This environment corresponds to the version of the cart-pole problem described by Barto, Sutton, and Anderson Observation: Type: Box(4) Num Observation Min Max 0 Cart Position -4.8 4.8 1 Cart Velocity -Inf Inf 2 Pole Angle -0.418 rad (-24 deg) 0.418 rad (24 deg) 3 Pole Angular Velocity -Inf Inf Actions: Type: Discrete(2) Num Action 0 Push cart to the left 1 Push cart to the right Note: The amount the velocity that is reduced or increased is not fixed; it depends on the angle the pole is pointing. This is because the center of gravity of the pole increases the amount of energy needed to move the cart underneath it Reward: Reward is 1 for every step taken, including the termination step Starting State: All observations are assigned a uniform random value in [-0.05..0.05] Episode Termination: Pole Angle is more than 12 degrees. Cart Position is more than 2.4 (center of the cart reaches the edge of the display). Episode length is greater than 200. Solved Requirements: Considered solved when the average return is greater than or equal to 195.0 over 100 consecutive trials. """ batchSize = 120 gma = 0.99 apa = 0.05 def rollout(e, q, eps=0, T=200): # get the control signal from current step, network(x) -> control signal -> step(control) -> next state traj = [] x = e.reset() for t in range(T): u = q.control(th.from_numpy(x).float().unsqueeze(0), eps=eps) u = u.int().numpy().squeeze() xp,r,d,info = e.step(u) # next state, reward, terminal state t = dict(x=x,xp=xp,r=r,u=u,d=d,info=info) # print(t) x = xp traj.append(t) if d: break return traj class q_t(nn.Module): def __init__(s, xdim, udim, hdim=16): super().__init__() s.xdim, s.udim = xdim, udim s.m = nn.Sequential( nn.Linear(xdim, hdim), nn.ReLU(True), nn.Linear(hdim, udim), ) def forward(s, x): return s.m(x); def control(s, x, eps=0): # 1. get q values for all controls val = s.m(x) ### TODO: XXXXXXXXXXXX # eps-greedy strategy to choose control input # note that for eps=0 # you should return the correct control u u = th.argmax(val, dim=1); prob = np.random.uniform(); if( prob < eps): u = th.tensor([np.random.choice([0,1])]) return u def loss(q, ds, q_tar, ddqn): ### TODO: XXXXXXXXXXXX # 1. sample mini-batch from datset ds # 2. code up dqn with double-q trick # 3. return the objective f randId = np.random.choice(range(len(ds)), batchSize); randPts = []; for id in randId: rid = np.random.choice(range(len(ds[id])), 5) for j in rid: randPts.append(ds[id][j]) f = 0; for id in range(len(randPts)): q_val = q(th.from_numpy(randPts[id]['x']).float().unsqueeze(0))[0, randPts[id]['u']] q_max = th.max(q_tar(th.from_numpy(randPts[id]['xp']).float().unsqueeze(0))) if ddqn == True: u_best = th.argmax(q(th.from_numpy(randPts[id]['x']).float().unsqueeze(0)), dim=1); q_max = q_tar(th.from_numpy(randPts[id]['xp']).float().unsqueeze(0))[0, u_best] # print(u_best) # print(int(randPts[id]['d'])) f += (q_val - randPts[id]['r'] - gma * (1 - int(randPts[id]['d'])) * q_max.detach())**2 f /= len(randPts) return f def evaluate(q): ### TODO: XXXXXXXXXXXX # 1. create a new environment e # 2. run the learnt q network for 100 trajectories on # this new environment to take control actions. Remember that # you should not perform epsilon-greedy exploration in the evaluation # phase # and report the average discounted # return of these 100 trajectories T = 200 numOfTraj = 100 r = 0; e_eval = gym.make('CartPole-v1') for _ in range(numOfTraj): x = e_eval.reset(); for t in range(T): u = q.control(th.from_numpy(x).float().unsqueeze(0), eps=0) u = u.int().numpy().squeeze() xp,tr,d,info = e_eval.step(u) # next state, reward, terminal state # print(t) r += tr; x = xp if d: break r /= numOfTraj return r def evaluateLast10(e, q): T = 200 numOfTraj = 10 r = 0; for _ in range(numOfTraj): x = e.reset(); for t in range(T): u = q.control(th.from_numpy(x).float().unsqueeze(0), eps=0) u = u.int().numpy().squeeze() xp,tr,d,info = e.step(u) # next state, reward, terminal state # print(t) r += tr; x = xp if d: break r /= numOfTraj return r if __name__=='__main__': # th.set_default_dtype(th.float64) e = gym.make('CartPole-v1') # th.set_default_dtype(th.float64) xdim, udim = e.observation_space.shape[0], \ e.action_space.n q = q_t(xdim, udim, 8) q2 = q_t(xdim, udim, 8) # Adam is a variant of SGD and essentially works in the # same way optim = th.optim.Adam(q.parameters(), lr=1e-3, weight_decay=1e-4) training_iter = 20000; ds = [] epss = 0.5 decay_factor = 0.9999 # collect few random trajectories with # eps=1 samping_iter = 500 train_rt = [] losss = [] rewards = [] q_tar = q_t(xdim, udim, 8) q_tar2 = q_t(xdim, udim, 8) q_tar.eval(); q_tar2.eval(); interval = 100 ddqn = True print("Sampling paths") for i in tqdm(range(samping_iter)): ds.append(rollout(e, q, eps=1, T=200)) # e.render(); print("Learning the controllers") for i in tqdm(range(1, training_iter + 1)): q.train() t = rollout(e, q, epss) ds.append(t) # replay buffer # perform weights updates on the q network # need to call zero grad on q function # to clear the gradient buffer q.zero_grad() f = loss(q, ds, q_tar, ddqn) f.backward() optim.step() for tar_para, q_para in zip(q_tar.parameters(), q.parameters()): tar_para.data = (1 - apa) * tar_para + apa * q_para losss.append(f.item()) # evaluate the last 10 traj epss *= decay_factor; if i % interval == 0: rw = evaluate(q); rewards.append(rw) train_rt.append(evaluateLast10(e, q)) # plt.subplot(1, 3, 1) # row 1, col 2 index 1 # plt.plot(range(i), losss) # plt.title("loss") # plt.subplot(1, 3, 2) # index 2 # plt.plot(range(len(train_rt)), train_rt) # plt.title("traning reward") # plt.subplot(1, 3, 3) # index 2 # plt.plot(range(len(train_rt)), rewards) # plt.title("reward") # plt.show() # 1000 iter -> evalution for last 10 traj -> training error # 1000 iter -> generate 10 more traj test evaultion new envrioment # plot the loss # keep track of return by the eval function plt.subplot(1, 3, 1) # row 1, col 2 index 1 plt.plot(range(training_iter), losss) plt.title("loss") plt.subplot(1, 3, 2) # index 2 plt.plot(range(training_iter//interval), train_rt) plt.title("traning reward") plt.subplot(1, 3, 3) # index 2 plt.plot(range(training_iter//interval), rewards) plt.title("reward") plt.show() # # on policy # policy gradient, sample trajectory(currrent policy) past traj is not valid # # off policy # pair(x_t, r, x_(t + 1)) # # actor-critic -> # # actor -> policy # # critic -> reward
a0d21dd0bff30a47fd23d146fff3ba032d803e23
LeejwUniverse/following_deepmid
/kyushikmin_tf1/DQN_GAMES/breakout.py
11,849
3.609375
4
# Atari breakout # By KyushikMin kyushikmin@gamil.com # http://mmc.hanyang.ac.kr # Special thanks to my colleague Hayoung and Jongwon for giving me the idea of ball and block collision algorithm import random, sys, time, math, pygame from pygame.locals import * import numpy as np import copy # Window Information FPS = 30 WINDOW_WIDTH = 480 WINDOW_HEIGHT = 400 INFO_GAP = 40 UPPER_GAP = 40 HALF_WINDOW_WIDTH = int(WINDOW_WIDTH / 2) HALF_WINDOW_HEIGHT = int((WINDOW_HEIGHT - INFO_GAP) / 2) # Colors # R G B WHITE = (255, 255, 255) BLACK = ( 0, 0, 0) RED = (200, 72, 72) LIGHT_ORANGE = (198, 108, 58) ORANGE = (180, 122, 48) GREEN = ( 72, 160, 72) BLUE = ( 66, 72, 200) YELLOW = (162, 162, 42) NAVY = ( 75, 0, 130) PURPLE = (143, 0, 255) bar_width = 60 bar_height = 8 bar_speed1 = 5 bar_speed2 = 10 bar_init_position = (WINDOW_WIDTH - bar_width)/2 ball_init_position_x = WINDOW_WIDTH / 2 ball_init_position_y = (WINDOW_HEIGHT - INFO_GAP) / 2 + UPPER_GAP ball_radius = 5 ball_bounce_speed_range = 10 block_width = 48 block_height = 18 num_block_row = int(((WINDOW_HEIGHT - INFO_GAP) / 4) / block_height) # Number of rows should be less than 8 or you should add more colors num_block_col = int(WINDOW_WIDTH / block_width) block_color_list = [RED, LIGHT_ORANGE, YELLOW, GREEN, BLUE, NAVY, PURPLE] def ReturnName(): return 'breakout' def Return_Num_Action(): return 5 class GameState: def __init__(self): global FPS_CLOCK, DISPLAYSURF, BASIC_FONT # Set the initial variables pygame.init() FPS_CLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption('BreakOut') # pygame.display.set_icon(pygame.image.load('./Qar_Sim/icon_resize2.png')) BASIC_FONT = pygame.font.Font('freesansbold.ttf', 16) # Set initial parameters self.init = True self.score = 0 self.reward = 0 self.num_blocks = num_block_row * num_block_col self.init_block_info = [] for i in range(num_block_row): self.init_block_info.append([]) for j in range(num_block_col): self.init_block_info[i].append([]) for i in range(num_block_row): for j in range(num_block_col): # Horizontal position, Vertical position, Width, Height self.init_block_info[i][j] = [(j * block_width, UPPER_GAP + INFO_GAP + i * block_height, block_width, block_height), 'visible'] self.direction = '' # Main function def frame_step(self, input): # Initial settings reward = 0 terminal = False if self.init == True: self.bar_position = bar_init_position self.ball_position_x = ball_init_position_x self.ball_position_y = ball_init_position_y # self.ball_speed_x = random.randint(-3, 3) self.ball_speed_x = random.uniform(-3.0, 3.0) self.ball_speed_y = 5 self.block_info = copy.deepcopy(self.init_block_info) self.init = False # Key settings for event in pygame.event.get(): # event loop if event.type == QUIT: self.terminate() if input[1] == 1: self.bar_position += bar_speed1 # slow right elif input[2] == 1: self.bar_position += bar_speed2 # fast right elif input[3] == 1: self.bar_position -= bar_speed1 # slow left elif input[4] == 1: self.bar_position -= bar_speed2 # fast left # Constraint of the bar if self.bar_position <= 0: self.bar_position = 0 if self.bar_position >= WINDOW_WIDTH - bar_width: self.bar_position = WINDOW_WIDTH - bar_width # Move the ball self.ball_position_x += self.ball_speed_x self.ball_position_y += self.ball_speed_y # Ball is bounced when the ball hit the wall if self.ball_position_x < ball_radius: self.ball_speed_x = - self.ball_speed_x self.ball_position_x = ball_radius if self.ball_position_x >= WINDOW_WIDTH - ball_radius: self.ball_speed_x = - self.ball_speed_x self.ball_position_x = WINDOW_WIDTH - ball_radius if self.ball_position_y < INFO_GAP + ball_radius: self.ball_speed_y = - self.ball_speed_y self.ball_position_y = INFO_GAP + ball_radius # Ball is bounced when the ball hit the bar if self.ball_position_y >= WINDOW_HEIGHT - bar_height - ball_radius: # Hit the ball! if self.ball_position_x <= self.bar_position + bar_width and self.ball_position_x >= self.bar_position: ball_hit_point = self.ball_position_x - self.bar_position ball_hit_point_ratio = ball_hit_point / bar_width self.ball_speed_x = (ball_hit_point_ratio * ball_bounce_speed_range) - (ball_bounce_speed_range/2) if abs(ball_hit_point_ratio - 0.5) < 0.01: self.ball_speed_x = random.uniform(-0.01 * ball_bounce_speed_range/2 , 0.01 * ball_bounce_speed_range/2) self.ball_speed_y = - self.ball_speed_y self.ball_position_y = WINDOW_HEIGHT - bar_height - ball_radius # reward = 0.5 # Lose :( if self.ball_position_y >= WINDOW_HEIGHT: self.init = True reward = -1 terminal = True # When the ball hit the block check_ball_hit_block = 0 for i in range(num_block_row): for j in range(num_block_col): block_left = self.block_info[i][j][0][0] block_right = self.block_info[i][j][0][0] + self.block_info[i][j][0][2] block_up = self.block_info[i][j][0][1] block_down = self.block_info[i][j][0][1] + self.block_info[i][j][0][3] visible = self.block_info[i][j][1] # The ball hit some block!! # if (block_left <= self.ball_position_x + ball_radius) and (self.ball_position_x - ball_radius <= block_right) and (block_up <= self.ball_position_y + ball_radius) and (self.ball_position_y - ball_radius <= block_down) and visible == 'visible': if (block_left <= self.ball_position_x) and (self.ball_position_x <= block_right) and (block_up <= self.ball_position_y) and (self.ball_position_y <= block_down) and visible == 'visible': # Which part of the block was hit?? # Upper left, Upper right, Lower right, Lower left block_points = [[block_left, block_up], [block_right, block_up], [block_right, block_down], [block_left, block_down]] if self.ball_position_x -self. ball_position_x_old == 0: slope_ball = (self.ball_position_y - self.ball_position_y_old) / (0.1) else: slope_ball = (self.ball_position_y - self.ball_position_y_old) / (self.ball_position_x - self.ball_position_x_old) # ax+by+c = 0 line_coeff = [slope_ball, -1, self.ball_position_y_old - (slope_ball * self.ball_position_x_old)] point1 = [block_left, (-1/line_coeff[1]) * (line_coeff[0] * block_left + line_coeff[2])] point2 = [block_right, (-1/line_coeff[1]) * (line_coeff[0] * block_right + line_coeff[2])] point3 = [(-1/line_coeff[0]) * (line_coeff[1] * block_up + line_coeff[2]), block_up] point4 = [(-1/line_coeff[0]) * (line_coeff[1] * block_down + line_coeff[2]), block_down] # Left, Right, Up, Down intersection = [point1, point2, point3, point4] check_intersection = [0, 0, 0, 0] for k in range(len(intersection)): #intersection point is on the left side of block if intersection[k][0] == block_left and (block_up <= intersection[k][1] <= block_down): check_intersection[0] = 1 if intersection[k][0] == block_right and (block_up <= intersection[k][1] <= block_down): check_intersection[1] = 1 if intersection[k][1] == block_up and (block_left <= intersection[k][0] <= block_right): check_intersection[2] = 1 if intersection[k][1] == block_down and (block_left <= intersection[k][0] <= block_right): check_intersection[3] = 1 dist_points = [np.inf, np.inf, np.inf, np.inf] for k in range(len(intersection)): if check_intersection[k] == 1: dist = self.get_dist(intersection[k], [self.ball_position_x_old, self.ball_position_y_old]) dist_points[k] = dist # 0: Left, 1: Right, 2: Up, 3: Down collision_line = np.argmin(dist_points) if collision_line == 0: self.ball_speed_x = - self.ball_speed_x elif collision_line == 1: self.ball_speed_x = - self.ball_speed_x elif collision_line == 2: self.ball_speed_y = - self.ball_speed_y elif collision_line == 3: self.ball_speed_y = - self.ball_speed_y # Incorrect breaking at corner! # e.g. block was hit on the right side even though there is visible block on the right # Then, the former decision was wrong, so change the direction! if j > 0: if collision_line == 0 and self.block_info[i][j-1][1] == 'visible': self.ball_speed_x = - self.ball_speed_x self.ball_speed_y = - self.ball_speed_y if j < num_block_col - 1: if collision_line == 1 and self.block_info[i][j+1][1] == 'visible': self.ball_speed_x = - self.ball_speed_x self.ball_speed_y = - self.ball_speed_y if i > 0: if collision_line == 2 and self.block_info[i-1][j][1] == 'visible': self.ball_speed_x = - self.ball_speed_x self.ball_speed_y = - self.ball_speed_y if i < num_block_row - 1: if collision_line == 3 and self.block_info[i+1][j][1] == 'visible': self.ball_speed_x = - self.ball_speed_x self.ball_speed_y = - self.ball_speed_y # Move the ball to the block boundary after ball hit the block if collision_line == 0: self.ball_position_x = block_left - ball_radius elif collision_line == 1: self.ball_position_x = block_right + ball_radius elif collision_line == 2: self.ball_position_y = block_up - ball_radius elif collision_line == 3: self.ball_position_y = block_down + ball_radius # make hit block invisible self.block_info[i][j][1] = 'invisible' check_ball_hit_block = 1 reward = 1 # If one block is hitted, break the for loop (Preventing to break multiple blocks at once) if check_ball_hit_block == 1: break # If one block is hitted, break the for loop (Preventing to break multiple blocks at once) if check_ball_hit_block == 1: break # Fill background color DISPLAYSURF.fill(BLACK) # Draw blocks count_visible = 0 for i in range(num_block_row): for j in range(num_block_col): if self.block_info[i][j][1] == 'visible': pygame.draw.rect(DISPLAYSURF, block_color_list[i], self.block_info[i][j][0]) count_visible += 1 # Win the game!! :) if count_visible == 0: self.init = True reward = 11 terminal = True # Display informations score_value = self.num_blocks - count_visible self.score_msg(score_value) self.block_num_msg(count_visible) # Draw bar bar_rect = pygame.Rect(self.bar_position, WINDOW_HEIGHT - bar_height, bar_width, bar_height) pygame.draw.rect(DISPLAYSURF, RED, bar_rect) self.ball_position_x_old = self.ball_position_x self.ball_position_y_old = self.ball_position_y # Draw ball pygame.draw.circle(DISPLAYSURF, WHITE, (int(self.ball_position_x), int(self.ball_position_y)), ball_radius, 0) # Draw line for seperate game and info pygame.draw.line(DISPLAYSURF, WHITE, (0, 40), (WINDOW_WIDTH, 40), 3) pygame.display.update() image_data = pygame.surfarray.array3d(pygame.display.get_surface()) return image_data, reward, terminal # Exit the game def terminate(self): pygame.quit() sys.exit() # Display score def score_msg(self, score): scoreSurf = BASIC_FONT.render('Score: ' + str(score), True, WHITE) scoreRect = scoreSurf.get_rect() scoreRect.topleft = (10, 10) DISPLAYSURF.blit(scoreSurf, scoreRect) # Display how many blocks are left def block_num_msg(self, num_blocks): blockNumSurf = BASIC_FONT.render('Number of Blocks: ' + str(num_blocks), True, WHITE) blockNumRect = blockNumSurf.get_rect() blockNumRect.topleft = (WINDOW_WIDTH - 180, 10) DISPLAYSURF.blit(blockNumSurf, blockNumRect) def get_dist(self, point1, point2): return math.sqrt(math.pow(point1[0] - point2[0],2) + math.pow(point1[1] - point2[1], 2))
9e0361d5aec0c73d9d7c57b46da630ba6e137cdc
amelialin/tuple-mudder
/Problems/remove_character_test.py
390
3.796875
4
from remove_character import remove_character def test_remove_character(): assert remove_character("a", "apple") == "pple" assert remove_character("e", "apple") == "appl" assert remove_character("a", "apple, with a bite") == "pple, with bite" assert remove_character(",", "apple, with a bite") == "apple with a bite" # what is the 'assert' test I would write for throwing an error?
dd3fc90ad49dd4398f2c61d74b7ec8d43228b861
DiamondGo/leetcode
/python/Combinations.py
992
3.71875
4
''' Created on 20160502 @author: Kenneth Tse Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] ''' class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ if k > n: return [[]] allc = [] # l = def search(i, k, comb, allcomb): if n - i < k or k < 0: return if k == 0: allcomb.append(comb) return # take this search(i+1, k -1, comb + [i+1], allcomb) # not take this search(i+1, k, comb, allcomb) search(0, k, [], allc) return allc if __name__ == '__main__': s = Solution() print(s.combine(1,1))
d0de89ef96c87e91b18bc9bfdd6ab1c6585000d0
Team-Afro-Dog/Last-Run
/Modules/background.py
1,813
3.625
4
''' Example on how to use (semi-pseudocode): screen = pygame.display.set_mode(100,100) Background background("backgroundImg.png", screen, 5) while True: if makeBackgroundFaster: background.changeToSpeed(10) if makeBackgroundBackwards: background.changeToSpeed(-5) background.move() # move background background.display() Works well when going left to right but buggy when going right to left ''' import pygame pygame.display.init() class Background(object): def __init__(self, imgPath, screen, speed = 0): self.img = pygame.image.load(imgPath) self.screen = screen self.firstImgXCoordinate = 0 self.secondImgXCoordinate = self.img.get_width() self.speed = speed # maybe implement exceptions if cannot find path def changeImg(self, imgPath): self.img = pygame.image.load(imgPath) def changeToSpeed(self, speed): self.speed = speed def isFirstImgFinish(self): return self.firstImgXCoordinate < -1*self.img.get_width() def isSecondImgFinish(self): return self.secondImgXCoordinate < -1*self.img.get_width() def move(self): if self.isFirstImgFinish(): self.firstImgXCoordinate = self.screen.get_width() if self.isSecondImgFinish(): self.secondImgXCoordinate = self.screen.get_width() self.firstImgXCoordinate -= self.speed self.secondImgXCoordinate -= self.speed def display(self): ''' Need to implement a method to blit only parts of the img that will actually display. Right now we are blitting the entire thing which slows performance. ''' self.screen.blit(self.img, (self.firstImgXCoordinate,0)) self.screen.blit(self.img, (self.secondImgXCoordinate, 0))
27e071748ef9fd9dcd7260fa0a7d1ae2a141c187
ranjanlamsal/Python_Revision
/name__main.py
1,782
4.34375
4
''' We have file name__main.py and name__main2.py to discuss the importance of __name__ == '__main__' in python ''' """ SO basically when we import a module in python then all the functions, objects , sub-modules , attributes , variables are imported from that module... Along with these, the code of that module is also executed and return if there is any executable code that returns something. """ import name__main2 ''' There are 2 functions in name__main2.py module. ''' test = name__main2.testfunc("New File New Content") print(test) test1 = name__main2.tesfunc2("Another new content") print(test1) """ Here when this program is executed , it imports module name__main2.py So its functions are imported and TO BE NOTED its executable codes are also executed so the returns from the execution of name__main.py is also returned in this program """ """ Now to remove this anguish if__name__ == __main__ function is used Go to file : name__main2.py to see the method to use that function """ ''' So what happened here ?? when the __name__ of file is executed in the same file where __name__ = __main__ is defined and executable code is under this function then the return will be "__main__" and when __name__ of the same file is executed and that file is imported in another program..... in such case __name__ == name of the file .. So the condition if __name__ == '__main__' is true.. i.e in the same file where main is defined... the code under it will be executed.. And incase of the program were the module (the module containing main) is imported the code under __main__ is not executed because __name__ = name of module. ''' print(name__main2.name) #here __name__ will be name__main2 (name of file)
8e100c00cf1ed94f98dbf291d0229bdf7759c93a
rui-r-duan/courses
/ai/ex2/caesar_cipher.py
862
3.5
4
#------------------------------------------------------------------------------- # author: Rui Duan (0561866) #------------------------------------------------------------------------------- def caesar_encrypt(msg, key): result = '' for c in msg: if c.isalpha(): if c.islower(): result += chr((ord(c) + key - ord('a')) % 26 + ord('a')) else: result += chr((ord(c) + key - ord('A')) % 26 + ord('A')) else: result += c return result def caesar_decrypt(msg, key): result = '' for c in msg: if c.isalpha(): if c.islower(): result += chr((ord(c) - key - ord('a')) % 26 + ord('a')) else: result += chr((ord(c) - key - ord('A')) % 26 + ord('A')) else: result += c return result
52b59efeda325a98446899f6e5dc36e240f494e3
AmbarDudhane/steganography
/test.py
1,176
3.546875
4
import itertools import collections class Solution(object): def slidingPuzzle(self, board): R, C = len(board), len(board[0]) start = tuple(itertools.chain(*board)) queue = collections.deque([(start, start.index(0), 0)]) seen = {start} target = tuple(list(range(1, R * C)) + [0]) print("Target:", target) while queue: board, posn, depth = queue.popleft() if board == target: return depth for d in (-1, 1, -C, C): nei = posn + d if abs(nei / C - posn / C) + abs(nei % C - posn % C) != 1: continue if 0 <= nei < R * C: newboard = list(board) newboard[posn], newboard[nei] = newboard[nei], newboard[posn] newt = tuple(newboard) if newt not in seen: seen.add(newt) queue.append((newt, nei, depth + 1)) print("Board:", board) return -1 if __name__ == '__main__': arr = [[1, 2, 3], [4, 0, 5]] moves = Solution().slidingPuzzle(arr) print("Moves:", moves)
06a5a4a25fd97bad7c8f707338c3a0277e870918
archanadeshpande/codewars
/Catching Car Mileage Numbers.py
2,765
3.90625
4
# "7777...8?!??!", exclaimed Bob, "I missed it again! Argh!" Every time there's an interesting number coming up, he notices and then promptly forgets. Who doesn't like catching those one-off interesting mileage numbers? # Let's make it so Bob never misses another interesting number. We've hacked into his car's computer, and we have a box hooked up that reads mileage numbers. We've got a box glued to his dash that lights up yellow or green depending on whether it receives a 1 or a 2 (respectively). # It's up to you, intrepid warrior, to glue the parts together. Write the function that parses the mileage number input, and returns a 2 if the number is "interesting" (see below), a 1 if an interesting number occurs within the next two miles, or a 0 if the number is not interesting. # Note: In Haskell, we use No, Almost and Yes instead of 0, 1 and 2. # "Interesting" Numbers # Interesting numbers are 3-or-more digit numbers that meet one or more of the following criteria: # Any digit followed by all zeros: 100, 90000 # Every digit is the same number: 1111 # The digits are sequential, incementing†: 1234 # The digits are sequential, decrementing‡: 4321 # The digits are a palindrome: 1221 or 73837 # The digits match one of the values in the awesome_phrases array # † For incrementing sequences, 0 should come after 9, and not before 1, as in 7890. # ‡ For decrementing sequences, 0 should come after 1, and not before 9, as in 3210. # So, you should expect these inputs and outputs: # # "boring" numbers # is_interesting(3, [1337, 256]) # 0 # is_interesting(3236, [1337, 256]) # 0 # # progress as we near an "interesting" number # is_interesting(11207, []) # 0 # is_interesting(11208, []) # 0 # is_interesting(11209, []) # 1 # is_interesting(11210, []) # 1 # is_interesting(11211, []) # 2 # # nearing a provided "awesome phrase" # is_interesting(1335, [1337, 256]) # 1 # is_interesting(1336, [1337, 256]) # 1 # is_interesting(1337, [1337, 256]) # 2 # Error Checking # A number is only interesting if it is greater than 99! # Input will always be an integer greater than 0, and less than 1,000,000,000. # The awesomePhrases array will always be provided, and will always be an array, but may be empty. (Not everyone thinks numbers spell funny words...) # You should only ever output 0, 1, or 2. def interesting_num(num, awesome): return num in awesome or str(num) in "1234567890 9876543210" or str(num) == str(num)[::-1] or int(str(num)[1:]) == 0 def is_interesting(number, awesome_phrases): if number > 99 and interesting_num(number, awesome_phrases): return 2 if number > 97 and (interesting_num(number + 1, awesome_phrases) or interesting_num(number + 2, awesome_phrases)): return 1 return 0
c3ad812cbaeaf6a5842f1cd275cdb76cd62900de
RJD02/Joy-Of-Computing-Using-Python
/Assignments/Week-12/Assignment12_1.py
695
4.125
4
''' A box is placed at an orientation on the (0,0,0) point. Given other 3 points which are the endpoints. Find the volume of the box. Input format: line 1 - Point 1 coordinates line 2 - Point 2 coordinates line 3 - Point 3 coordinates Output format: Volume of the box Example: Input 2 2 -1 1 3 0 -1 1 4 Output 12 ''' def solve(): p1 = list(map(float, input().split())) p2 = list(map(float, input().split())) p3 = list(map(float, input().split())) d1 = p1[0] * (p2[1] * p3[2] - p2[2] * p3[1]) d2 = p1[1] * (p2[0] * p3[2] - p2[2] * p3[0]) d3 = p1[2] * (p2[0] * p3[1] - p2[1] * p3[0]) res = (d1 - d2 + d3) print(abs(res)) return solve()
650538d7fbfe36b3ae526268d039701543398f29
takamuio/DesafiosAulaYoutube
/venv/teste84.py
877
3.53125
4
pessoas = [] dados = [] maior = menor = 0 while True: dados.append(str(input('Nome: '))) dados.append(float(input('Peso: '))) if len(pessoas) == 0: menor = maior = dados[1] else: if dados[1] > maior: maior = dados[1] if dados[1] < menor: menor = dados[1] pessoas.append(dados[:]) dados.clear() opcao = ' ' while opcao not in 'SsNn': opcao = str(input('Deseja continuar ? [S/N] ')).upper().strip()[0] if opcao in 'Nn': break print('=-'*20) print(f'Foram cadastradas {len(pessoas)} pessoas') print(f'A lista completa {pessoas}') print(f'O maior peso é {maior}Kg de ', end='') for c in pessoas: if c[1] == maior: print(f'[{c[0]}]', end=' ') print(f'\nO menor peso é {menor}KG de ',end='') for c in pessoas: if c[1] == menor: print(f'[{c[0]}]', end=' ')
2d07f8cef185e3b4aecccc94a73e163b65d37550
manuwhs/traphing
/traphing/graph/_plots.py
15,194
3.640625
4
import matplotlib.pyplot as plt from .. import utils as ul # The common properties will be explained here once and shortened in the rest def plot(self, X = None,Y = None, # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties ## Axes options axes = None, # Axes where this will be plotted. If none, it will be the last one. position = None, # If given it will create a new axes [x,y,w,h] sharex = None, sharey = None, # When nf = 1, we are creating a new figure and we can choose # that new axes share the same x axis or yaxis than another one. projection = "2d", # Type of plot # Advanced fonts font_sizes = None, # This is the fontsizes of [tittle, xlabel and ylabel, xticks and yticks] # Layout options xpadding = None, ypadding = None, # Padding in percentage of the plotting, it has preference xlim = None, ylim = None, # Limits of vision ### Special options fill_between = False, # 0 = No fill, 1 = Fill and line, 2 = Only fill alpha_line = 1, # Alpha of the line when we do fillbetween fill_offset = 0, # The 0 of the fill ls = "-", marker = [None, None, None], # [".", 2, "k"], # Axis options axis_style = None, # Automatically do some formatting :) ## Widget options ws = None, # Only plotting the last window of the data. init_x = None, # Initial point to plot # Basic parameters that we can usually find in a plot loc = "best", # Position of the legend ): axes, X,Y, drawings,drawings_type = self._predrawing_settings(axes, sharex, sharey, position, projection, X,Y, None, ws) for i in range(Y.shape[1]): self.zorder+= 1 # colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] alpha_line = alpha if fill_between == 0 else alpha_line drawing, = axes.plot(X[self.start_indx:self.end_indx],Y[self.start_indx:self.end_indx:,i], lw = lw, alpha = alpha_line, color = colorFinal, label = legend_i, zorder = self.zorder, ls = ls, marker = marker[0], markersize = marker[1], markerfacecolor = marker[2]) drawings.append(drawing); drawings_type.append("plot") if (fill_between == True): drawing = self.fill_between(x = X[self.start_indx:self.end_indx], y1 = Y[self.start_indx:self.end_indx,i], y2 = fill_offset, color = colorFinal,alpha = alpha) self._postdrawing_settings(axes, legend, loc, labels, font_sizes, xlim, ylim,xpadding,ypadding,axis_style,X,Y) return drawings def scatter(self, X = [],Y = [], labels = [], legend = [], color = None, lw = 1, alpha = 1.0, # Basic line properties axes = None, position = [], projection = "2d", sharex = None, sharey = None, font_sizes = None,axis_style = None, loc = "best", xlim = None, ylim = None, xpadding = None, ypadding = None, # Limits of vision ws = None,init_x = None, ## Scatter specific marker = "o" ): axes, X,Y, drawings,drawings_type = self._predrawing_settings(axes, sharex, sharey, position, projection, X,Y, None, ws) for i in range(Y.shape[1]): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] drawing = axes.scatter(X,Y, lw = lw, alpha = alpha, color = colorFinal, label = legend_i, zorder = self.zorder, marker = marker) # TODO: marker = marker[0], markersize = marker[1], markerfacecolor = marker[2] drawings.append(drawing); drawings_type.append("scatter") self._postdrawing_settings(axes, legend, loc, labels, font_sizes, xlim, ylim,xpadding,ypadding,axis_style,X,Y) return drawing def stem(self, X = [],Y = [], labels = [], legend = [], color = None, lw = 2, alpha = 1.0, # Basic line properties axes = None, position = [], projection = "2d", sharex = None, sharey = None, font_sizes = None,axis_style = None, loc = "best", xlim = None, ylim = None, xpadding = None, ypadding = None, # Limits of vision ws = None,init_x = None, ## Stem specific marker = [" ", None, None], bottom = 0 ): axes, X,Y, drawings,drawings_type = self._predrawing_settings(axes, sharex, sharey, position, projection, X,Y, None, ws) ############### CALL PLOTTING FUNCTION ########################### for i in range(Y.shape[1]): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] markerline, stemlines, baseline = axes.stem(X,Y[:,i], use_line_collection = True, label = legend_i,#marker[2], bottom = bottom) # properties of the baseline plt.setp(baseline, 'color', 'r', 'linewidth', 1) plt.setp(baseline, visible=False) # properties of the markerline plt.setp(markerline, 'markerfacecolor',colorFinal) plt.setp(markerline, 'color',colorFinal) plt.setp(markerline, visible=False) # Properties of the stemlines plt.setp(stemlines, 'linewidth', lw) plt.setp(stemlines, 'color', colorFinal) plt.setp(stemlines, 'alpha', alpha) drawings.append([markerline, stemlines, baseline]); drawings_type.append("scatter") self._postdrawing_settings(axes, legend, loc, labels, font_sizes, xlim, ylim,xpadding,ypadding,axis_style,X,Y) return [markerline, stemlines, baseline] def fill_between(self, x, y1, y2 = 0, where = None, labels = [], legend = [], color = None, lw = 2, alpha = 1.0, # Basic line properties axes = None, position = [], projection = "2d", sharex = None, sharey = None, font_sizes = None,axis_style = None, loc = "best", xlim = None, ylim = None, xpadding = None, ypadding = None, # Limits of vision ws = None,init_x = None ): axes, X,Y, drawings,drawings_type = self._predrawing_settings(axes, sharex, sharey, position, projection, x,y1, None, ws) y1 = ul.fnp(Y).T.tolist()[0] if (where is not None): where = ul.fnp(where) # where = np.nan_to_num(where) where = where.T.tolist()[0] y2 = ul.fnp(y2) if (y2.size == 1): y2 = y2[0,0] else: y2 = y2.T.tolist()[0] drawing = axes.fill_between(x = X.flatten(), y1 = y1, y2 = y2, where = where, color = color, alpha = alpha, zorder = self.zorder, label = legend) # *args, **kwargs) drawings.append(drawing); drawings_type.append("fill_between") self._postdrawing_settings(axes, legend, loc, labels, font_sizes, xlim, ylim,xpadding,ypadding,axis_style,X,Y) return drawing def step(self, X = [],Y = [], # X-Y points in the graph. labels = [], legend = [], # Basic Labelling color = None, lw = 2, alpha = 1.0, # Basic line properties nf = 0, na = 0, # New axis. To plot in a new axis # TODO: shareX option ax = None, position = [], projection = "2d", # Type of plot sharex = None, sharey = None, fontsize = 20,fontsizeL = 10, fontsizeA = 15, # The font for the labels in the axis xlim = None, ylim = None, xlimPad = None, ylimPad = None, # Limits of vision ws = None, Ninit = 0, loc = "best", dataTransform = None, xaxis_mode = None,yaxis_mode = None,AxesStyle = None, # Automatically do some formatting :) marker = [" ", None, None], where = "pre", # pre post mid ## TODO, part of the step. How thw shit is done fill = 0, fill_offset = 0, ): # Management of the figure and properties ax = self.figure_management(nf, na, ax = ax, sharex = sharex, sharey = sharey, projection = projection, position = position) ## Preprocess the data given so that it meets the right format X, Y = self.preprocess_data(X,Y,dataTransform) NpY, NcY = Y.shape plots,plots_typ = self.init_WidgetData(ws) ################################################################## ############### CALL PLOTTING FUNCTION ########################### ################################################################## ## TODO. Second case where NcY = NcX !! if (Y.size != 0): # This would be just to create the axes ############### CALL PLOTTING FUNCTION ########################### for i in range(NcY): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] alpha_line = alpha if fill == 0 else 1 plot_i, = ax.step(X[self.start_indx:self.end_indx],Y[self.start_indx:self.end_indx:,i], lw = lw, alpha = alpha_line, color = colorFinal, label = legend_i, zorder = self.zorder, where = where) plots.append(plot_i) plots_typ.append("plot") # Filling if needed if (fill == 1): XX,YY1, YY2 = ul.get_stepValues(X[self.start_indx:self.end_indx],Y[self.start_indx:self.end_indx:,i], y2 = 0, step_where = where) self.fill_between(x = XX, y1 = YY1, y2 = fill_offset, color = colorFinal,alpha = alpha, step_where = where) ############### Last setting functions ########################### self.store_WidgetData(plots_typ, plots) # Store pointers to variables for interaction self.update_legend(legend,NcY,ax = ax, loc = loc) # Update the legend self.set_labels(labels) self.set_zoom(ax = ax, xlim = xlim,ylim = ylim, xlimPad = xlimPad,ylimPad = ylimPad) self.format_xaxis(ax = ax, xaxis_mode = xaxis_mode) self.format_yaxis(ax = ax, yaxis_mode = yaxis_mode) self.apply_style(nf,na,AxesStyle) return ax def plot_filled(self, X = [],Y = []): x = X[self.start_indx:self.end_indx] ############### CALL PLOTTING FUNCTION ########################### for i in range(0,NcY): # We plot once for every line to plot if (fill_mode == "stacked"): # print "FFFFFFFFFFFFFFFFFFFFFFF" if (i == 0): # i for i in range(NcY) y1 = Y[self.start_indx:self.end_indx,i] y2 = 0 else: y2 = y1 y1 = y2 + Y[self.start_indx:self.end_indx,i] elif(fill_mode == "between"): y2 = Y[self.start_indx:self.end_indx,i-1] y1 = Y[self.start_indx:self.end_indx,i] else: if (i == NcY -1): break; y2 = Y[self.start_indx:self.end_indx,i] y1 = Y[self.start_indx:self.end_indx,i+1] self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] # With this we add the legend ? # plot_i, = ax.plot([X[0],X[0]],[y1[0],y1[0]], lw = lw, alpha = alpha, # color = colorFinal, zorder = self.zorder) if (step_mode == "yes"): XX,YY1, YY2 = ul.get_stepValues(x,y1, y2, step_where = where) fill_i = self.fill_between(x = XX, y1 = YY1, y2 = YY2, color = colorFinal,alpha = alpha, step_where = where) else: fill_i = self.fill_between(x = x,y1 = y1 ,y2 = y2, color = colorFinal,alpha = alpha, legend = [legend_i]) def bar(self, X = [],Y = [], labels = [], legend = [], color = None, lw = 2, alpha = 1.0, # Basic line properties axes = None, position = [], projection = "2d", sharex = None, sharey = None, font_sizes = None,axis_style = None, loc = "best", xlim = None, ylim = None, xpadding = None, ypadding = None, # Limits of vision ws = None,init_x = None, fill_mode = "independent", # "between", "stacked","independent" # Particular pararm align = "center", # "edge" orientation = "vertical", barwidth = None, # Rectangle width bottom = None, ## If the y-axis start somewhere else despx = 0, # Displacement in the x axis, it is done for the dates # so that we can move some other things (Velero graph) ): axes, X,Y, drawings,drawings_type = self._predrawing_settings(axes, sharex, sharey, position, projection, X,Y, None, ws) if (Y.size != 0): # This would be just to create the axes for i in range(Y.shape[1]): # We plot once for every line to plot self.zorder = self.zorder + 1 # Setting the properties colorFinal = self.get_color(color) legend_i = None if i >= len(legend) else legend[i] if bottom is not None: bottom = bottom[self.start_indx:self.end_indx].flatten() X = X.flatten() if orientation == "vertical": drawing = axes.bar(X[self.start_indx:self.end_indx], Y[self.start_indx:self.end_indx:,i], width = barwidth, align=align, facecolor= colorFinal,alpha=alpha, label = legend_i, zorder = self.zorder, bottom = bottom) elif(orientation == "horizontal"): drawing = axes.bar(width = Y[self.start_indx:self.end_indx:,i], height = barwidth, align=align, facecolor= colorFinal,alpha=alpha, label = legend_i, zorder = self.zorder, left = bottom, bottom = X[self.start_indx:self.end_indx], orientation = "horizontal") drawings.append(drawing); drawings_type.append("bar") self._postdrawing_settings(axes, legend, loc, labels, font_sizes, xlim, ylim,xpadding,ypadding,axis_style,X,Y) return drawings
2d91a07c9b182b34a11f5239e55586229f02f745
YaroslavaCHIB/project-9
/kmeans сортировка для групп.py
773
3.5
4
import pandas as pd from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder df = pd.read_csv('C:\\Users\\teacher\\Desktop\\дз\\final_DataFrame.csv') print(df) labelencoder=LabelEncoder() df['activity']=labelencoder.fit_transform(df['activity']) print(df) labelencoder=LabelEncoder() df['name']=labelencoder.fit_transform(df['name']) print(df) model = KMeans(n_clusters = 5) X = df.iloc[:,[2]].values y = df.iloc[:,[3]].values print(X) print(y) model.fit(X) import matplotlib.pyplot as plt score = [] for i in range(3,15): kmeans = KMeans(n_clusters=i, random_state=42) kmeans.fit(X) tmp = kmeans.inertia_ score.append(tmp) plt.plot(range(3,15), score)
5ea7cbd67575adf7f5451978bc169dab38fef844
kunalprompt/computerScienceFundamentals
/competitiveProgramming/spoj/basic/cpttrn2.py
411
3.75
4
def pattern(m, n): for i in range(m): row = "" for j in range(n): if i==0 or i==m-1: row += "*" elif j==0 or j==n-1: row += "*" else: row += "." print row def main(): t = int(raw_input()) while t: m, n = map(int, raw_input().split()) pattern(m, n) t-=1 if __name__=="__main__": # main() pattern(1, 3) # pattern(3, 1) # pattern(4, 8) # pattern(2, 5) # pattern(3, 5)
3f403ed7b427751d876d2edd224939ec8797da6f
mimipeshy/pramp-solutions
/code/find_duplicates.py
1,563
4.28125
4
"" Find The Duplicates Given two sorted arrays arr1 and arr2 of passport numbers, implement a function findDuplicates that returns an array of all passport numbers that are both in arr1 and arr2. Note that the output array should be sorted in an ascending order. Let N and M be the lengths of arr1 and arr2, respectively. Solve for two cases and analyze the time & space complexities of your solutions: M ≈ N - the array lengths are approximately the same M ≫ N - arr2 is much bigger than arr1. input: arr1 = [1, 2, 3, 5, 6, 7], arr2 = [3, 6, 7, 8, 20] output: [3, 6, 7] "" # O(n + m) time # O(n) space def find_duplicates(arr1, arr2): duplicates = [] m, n = len(arr1), len(arr2) i, j = 0, 0 while i < m and j < n: if arr2[j] > arr1[i]: i += 1 elif arr1[i] > arr2[j]: j += 1 else: # arr1[i] == arr2[j] duplicates.append(arr1[i]) i += 1 j += 1 return duplicates # O(mlogn) time where m = len(arr1) and n = len(arr2) # O(n) space def find_duplicates(arr1, arr2): # Make arr1 the shorter array if arr2 < arr1: arr1, arr2 = arr2, arr1 duplicates = [] # Traverse the shorter array for num in arr1: if binary_search(arr2, num): duplicates.append(num) return duplicates def binary_search(arr, num): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] < num: left = mid + 1 elif arr[mid] > num: right = mid - 1 else: # arr[mid] == num return True return False
ed1d2eba8c696e5f562b7799ab95e6e1cd9abee9
mz-jobs/LeetCode
/1110DeleteTreeNodes.py
1,554
3.578125
4
root = [1, 2, 3, 4, 5, 6, 7] class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # t = None def CreateTree(i, n): if 2**n-1+i >= len(root): return None t = TreeNode(root[2**n-1+i]) t.left = CreateTree(i*2, n+1) t.right = CreateTree(i*2+1, n+1) return t t = CreateTree(0, 0) def treeHeight(t): if not t: return 0 return 1 + max(treeHeight(t.left), treeHeight(t.right)) print('H: ', treeHeight(t)) def treeToArray(tree): H = treeHeight(t) array = [None] * (2**H - 1) def fillArray(i, n, tree): if tree: array[2**n-1+i] = tree.val fillArray(i*2, n+1, tree.left) fillArray(i*2+1, n+1, tree.right) fillArray(0, 0, tree) while array and array[-1] == None: array.pop() return array print('A: ', treeToArray(t)) def printTree(t): if t: print(t.val) printTree(t.left) printTree(t.right) else: print(None) # printTree(t) # def delVal(t, to_del): # if t and t.left.val in to_del: # t.left = None processList = [t] def pruneTree(t, to_delete): if not t: return None if t.val in to_delete: processList.append(t.left) processList.append(t.right) return None t.left = pruneTree(t.left, to_delete) t.right = pruneTree(t.right, to_delete) return t results = [] while processList: results.append(pruneTree(processList.pop(0), [3, 5])) for t in results: print('TREE', treeToArray(t))
eadc6148a620270ed67ebcd841b1a35cf6f97a65
Jxb814/Homework
/P3/Boiler.py
615
3.5
4
import Node class Boiler: ''' The boiler class ''' def __init__(self,inlet,outlet): ''' Initializes the boiler with the previous conditions ''' self.inlet = inlet self.outlet = outlet def simulate(self): ''' Simulates the Boiler and tries to get the exit temperature down to the desiredOutletTemp. This is done by continuously adding h while keeping the P constant. ''' self.outlet.p = self.inlet.p self.outlet.pt() self.Addh = self.outlet.h - self.inlet.h
33c6ce891655c3f463eae625ea6dc6445b17bb9a
otaviowav/ExerciciosEmPython
/Ex_03_JogoParOuImpar.py.py
610
3.9375
4
# Resolução n = int(input()) # Entrada de um número natural maior ou igual a dois. # Contadores de numeros pares e impares seguido dos espaços solicitado no exercício countImpar = n countPar = n par = '' impar = '' # Loop realizando break caso o valor seja negativo while n > 0: countImpar -= 1 countPar += 1 if countImpar %2 == 1: # Caso o resto da divisção seja 1 o numero é impar impar = countImpar if countPar %2 == 0: # Caso o resto da divisção seja 0 o numero é par par = countPar if par != '' and impar != '': print(impar,par) break
2e88f747b1a20eaad1371d469c8206149e2988de
qpdh/DataScience_Code
/4장 선형대수/과제1.py
340
3.9375
4
def pdf(x: float) -> float: return 1 if 2.0 <= x <= 5.0 else 0 # fill in with your code here def cdf(x: float) -> float: if x < 2.0: return 0 elif 2.0 <= x <= 5.0: return (x - 2.0) / 3 else: return 1 # fill in with your code here # print print("pdf(2.5)=", pdf(2.5)) print("cdf(2.5)=", cdf(2.5))
e3cd7dfa4986c7a17f10d15c9ff5504746e44674
Mohamed5894/python_course
/3_data_structures_and_algorithms/2_Data_Structures/linear_ds.py
500
3.765625
4
class LinearDs: def __init__(self): """ initialize an empty python list""" self.items=[] def showItems(self): """ print the data structure contents """ assert len(self.items)!=0 ,"data structure is empty" print(self.items) return def isEmpty(self): """ check if the data structure is empty or has elements""" return self.items==[] def size(self): """ return data structure size""" return len(self.items)
71d12f7d64eded05d37428e22c070c86d9d17631
Keerthilogambal/IBMLabs
/hcf.py
345
3.953125
4
def compute_hcf(x,y): if x>y: smaller=y else: smaller=x for i in range(1,smaller+1): if (x%i==0) and (y%i==0): hcf=i return hcf num1=int(input("Enter a number : ")) num2=int(input("Enter a number : ")) print("The H.C.F of {} and {} is {}".format(num1,num2,compute_hcf(num1,num2)))
2b6e8ffbda2676ff82e49517b77d535c26824e51
hashrm/hashrm
/Learn Python/Python Is Easy Assignments - Hash/02 Functions/main.py.py
1,157
4.3125
4
# Homework Assignment #2: Functions """ Task 1: create functions for song for any 3 attributes (considered as variables in previous assignment) Task 2: when function is called, the function should return corresponding value for the attribute. Example: Artist - AR Rahman """ #creating a function Artist def Artist(): #print statement of the artist name, #the output to be shown print("AR Rahman") #creating a function Song_Name def Song_Name(): #print statement of the Song name, #the output to be shown print("Dil Se") def Duration_in_secs(): #print statement of the nos of seconds the song plays for, #the output to be shown print(390) #calls Artist Function Artist() #calls Song_Name Function Song_Name() #calls Duration_in_secs Function Duration_in_secs() #trying to use boolean as an extra function for extra credit Duration_in_mins = 6.5 def song_length(): if (Duration_in_mins > 4): print("This is a long song") return True else: print("This is a short song") return False #calling the function song_length song_length()
41b06e2cdad07529a2c0c67d94ab2ea4476aba84
ThompsonNJ/CSC231-Introduction-to-Data-Structures
/Assignment 6/sheriff.py
1,157
3.90625
4
from hashtable import * import csv import re reverse_lookup = HashTable(2**11) def valid_number(phone_number): pattern = re.compile("^[\dA-Z]{3}-[\dA-Z]{3}-[\dA-Z]{4}$", re.IGNORECASE) return pattern.match(phone_number) is not None if __name__ == '__main__': # load phone directory into hash table with open('phone_database.csv', newline='') as file: reader = csv.reader(file) next(reader) for row in reader: reverse_lookup.put(row[2], row[1] + ' ' + row[0]) print('Loaded', len(reverse_lookup), 'items.') while True: phone = input('Enter a phone number to search for, or 0 to quit: ') if phone == '0': print('Exiting.') exit(1) elif not valid_number(phone): print('Invalid format for phone number. Try again.') else: result, slot = reverse_lookup.get(phone) if result is None: print('No such number in the registry.') else: print('{} is registered to {}. The data is stored in slot {}.'.format(phone, result, slot))
0a9c77e9be50218a02ee202152c7e8a42d7d5efd
BrayanPisuna/EcuacionesLineales
/ecuacionesLineales.py
2,180
3.5625
4
import numpy as np #PUNTO DE INTERSECCION ENTRE LOS TRES PLANOS import matplotlib.pyplot as plt # UTILIZAMOS COMO PLT from mpl_toolkits.mplot3d import Axes3D # UTILIZAMOS PARA IMPORTAR LOS EJES EN 3D from matplotlib import cm #MAPAS DE COLORES #Matriz donde vamos a poner donde estan las variables, A lado de los coeficientes A= np.array([[2,4,6],[3,8,5],[-1,1,2]]) #Vector solucion o mis coeficientes b=np.array([22,27,2]) #VECTOR SOLUCION donde comenos los argumentos(A,b) sol=np.linalg.solve(A,b) #Imresion de resolucion print(sol) #ECUACIONES PARA IMPRIMIR EN 3D #DESPEJAMOS TODAS LAS ECUACIONES PARA Z #NOS AHORRAMOS UN CICLO FOR VAMOS A CREAR UN ESPACIO DE NUMERO DE 1 A 10 Y AUMENTAR DE 1 A 10 x,y=np.linspace(0,10,10),np.linspace(0,10,10) #CREAMOS UNA CUADRICULA UTILIZANDO LOS VALORES X,Y=np.meshgrid(x,y) #DESPEJE DE TODAS LAS ECUACIONES #DESPEJADAS PARA Z QUE ES LA ULTIMA VARIABLE """ Z1=(22-2*X-4*Y)/6 #DESPEJE DE LA PRIMERA ECUACION Z2=(27-3*X-8*Y)/5 #DESPEJE DE LA SEGUNDA ECUACION Z3=(2 + X- Y)/2 #DESPEJE DE LA TERCERA ECUACION """ #ECUACION DONDE HAY UN CRUZE Y DOS EMPALMES HAYA UNA ECUACION EQUIVALENTE POR ESO NOS MUESTRA ASI """ Z1= 3-5*X-2*Y #DESPEJE DE LA PRIMERA ECUACION Z2=(-12+4*X-4*Y)/8 #DESPEJE DE LA SEGUNDA ECUACION Z3=(-3 + X- Y)/2 #DESPEJE DE LA TERCERA ECUACION """ #MOSTRAR CLARO EJEMPLO QUE NO TIENE NINGUNA RELACION Z1= 1+X+Y #DESPEJE DE LA PRIMERA ECUACION Z2=-50+X+Y #DESPEJE DE LA SEGUNDA ECUACION Z3= 50+X+Y #DESPEJE DE LA TERCERA ECUACION #CUANDO LAS ECUACIONES NO TIENEN NINGUNA RELACION Y LOS PLANOS SON PARALELOS ENTRE SI #PARTE DE LAS GRAFICAS fig=plt.figure() ax=fig.add_subplot(111,projection = '3d') ax.plot_surface(X,Y,Z1,alpha=0.5,cmap=cm.Accent,rstride = 100, cstride = 100) ax.plot_surface(X,Y,Z2,alpha=0.5,cmap=cm.Paired,rstride = 100, cstride = 100) ax.plot_surface(X,Y,Z3,alpha=0.5,cmap=cm.Pastel1,rstride = 100, cstride = 100) ax.plot((sol[0],),(sol[1],),(sol[2],),lw=2,c='k',marker='o',markersize=7,markeredgecolor='g',markerfacecolor='white') #NOMBRES A LOS EJES ax.set_xlabel('X');ax.set_ylabel('Y');ax.set_zlabel('Z') plt.show() print("GRACIAS")
080dfdb53414e98dfa01d547f4a744750934c8d7
liu-yuxin98/Python
/chapter3/3-3.py
518
3.984375
4
#coding:utf-8 # 出现中文的时候用 import turtle print(format(57.89283091280,"5.2e")) #控制小数格式 print(format(8989.98090,"10.2%")) print(format(7,"b")) s=str(3.4)# convert number to string t=str(2.6) print(s+t) # 字符串加减 print(id(s)," ", id(t)) print(" \"hello world \" ") #转义 print("aaa",end='') #换行 print("bbb", end='') print(ord('B')) #字符串的 ASC码 print(chr(98)) #ASC码对应字符 s=" WelcoMe " print(s.lower()) print(s.upper()) print(s.strip()) # 去除两边空格
258f9dc9200adefe74f919b75101265a1549609c
zingpython/kungFuShifu
/day_one/10.py
279
4.15625
4
#For every value of X do 1 to 10 as y for x in range(1, 11): for y in range(1, 11): #multiply x*y and put a tab space at the end of the print statement for formatting print(x*y, end="\t") #Once a row in the multiplication table is finished move to the next line print()
af7ccace5fc8b88a7469864c9bfae226f505e059
SureshNamitha/python-programs
/namroll.py
170
3.859375
4
import random while True: r = input("press 'r' to roll and press 'q' to quit the game:") if r =="r": print(random.randint(1,6)) if r =="q": print("bye!") exit(0)
7d4120cda6a1260cf7b4b24b2add8345a12e72fb
ngocyen3006/learn-python
/leetcode.com/728_selfDividingNumbers.py
680
3.515625
4
# 728. Self Dividing Numbers # https://leetcode.com/problems/self-dividing-numbers/ def selfDividingNumbers(left, right): res = [] for i in range(left, right + 1): if isSelfDividingNum(i): res.append(i) return res def isSelfDividingNum(num): if num in range(1, 10): return True digit = str(num) if '0' in digit: return False for d in digit: if d == '1': continue if num % int(d) != 0: return False return True if __name__ == '__main__': left, right = 1, 2000 output = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] print(selfDividingNumbers(left, right))
fb37a9b949e750314d0e68aa3ac01dd76f03372c
karsonk09/CMSC-150
/Sample Programs/variable_samples.py
245
3.828125
4
x = 5 print(x) # constants are always uppercase. x = 5 + 10 print(x) # these functions always round down to keep things simple x = 21 // 10 print(x) # if you want something to happen every x times x = 21 % 10 print(x) x = 3 y = 2 * (3 + x)
e7d82856a0acd6973c8f012a763e108a5f8878c3
Sachin-12/Solved_problems
/Data Structures and Algorithms in Python/delete_nth_node_from_last_in_linked_list.py
1,289
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class Singly_Linked_List: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def deleteNode(self, position): temp1 = self.head temp2 = self.head for i in range(position): if temp2.next == None: if(i==position-1): self.head = self.head.next return self.head temp2 = temp2.next while(temp2.next != None): temp2 = temp2.next temp1 = temp1.next temp1.next = temp1.next.next def display_list(self): temp = self.head while(temp != None): print(" {} ".format(temp.data)) temp = temp.next singly_linked_list = Singly_Linked_List() print("Press \"q\" to stop the list") while(True): temp = input("Enter the number you want to add :") if temp == "q": break singly_linked_list.push(temp) print("Linked List :") singly_linked_list.display_list() del_node = int(input("Enter the node you want to delete from the last in linked list")) singly_linked_list.deleteNode(del_node) print("\nLinked List after deletion of {}th node from last: ".format(del_node)) singly_linked_list.display_list()
ebb925fa2609c2f90c2d113f5883bbfbcab702c0
ellenhan0201/bootcamp
/ex_1.3_b.py
652
4.28125
4
#ex 1.3 b def complement_base(base): """Returns the Watson-Crick complement of a base.""" if base == 'A' or base == 'a': return 'T' elif base == 'T' or base == 't': return 'A' elif base == 'G' or base == 'g': return 'C' else: return 'G' def reverse_complement(seq): """Compute reverse complement of a sequence.""" i=0; while i < len(seq): # Initialize reverse complement rev_seq = '' # Loop through and populate list with reverse complement rev_seq += complement_base(base) return rev_seq #or change all characters to lower case and then use replace function
9151fc823d7007774015eb608e1cea68aa4a8e1c
hellozgy/leetcode
/tree/110.py
1,587
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 方案一:O(n^2) ''' class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if root is None:return True if abs(self.depth(root.left)-self.depth(root.right))>1:return False return self.isBalanced(root.left) and self.isBalanced(root.right) def depth(self, root): if root is None:return 0 depth = 0 t = [root] tt = [] while len(t)>0: depth += 1 for node in t: if node.left:tt.append(node.left) if node.right: tt.append(node.right) t = tt tt = [] return depth ''' #方案二 :O(n) #借鉴题目的解析 class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self.dfsHeight(root)!=-1 def dfsHeight(self, node): ''' 如果节点node是不平衡的,则返回-1,否则返回它的实际深度 ''' if node is None:return 0 lheight = self.dfsHeight(node.left) if lheight==-1:return -1 # 如果子节点不平衡,那么父节点也不平衡 rheight = self.dfsHeight(node.right) if rheight==-1:return -1 if abs(lheight-rheight)>1:return -1 return max(lheight, rheight)+1
45bce827b1394011ac1e7f3207b831b49a6bc559
tianshan/leetcode_py
/58.py
549
3.671875
4
class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): s_len = len(s) if s_len<1: return 0 index = 1 while index<=s_len and s[-index]==' ': index += 1 ans = 0 for i in range(index, s_len+1): if s[-i]==' ': break ans += 1 return ans if __name__=='__main__': s = Solution() data = ['hello world',' ','','hello', 'a '] for d in data: print d,s.lengthOfLastWord(d)
70306573f71137056b8d6f9d6e40f473c7c0c6aa
jhiltonsantos/ADS-Algoritmos-IFPI
/Atividade_Fabio_06_STRING/fabio06_07_conjugar_verbo_regular.py
2,874
4.25
4
def main(): verbo = input('Digite um verbo regular terminado em -ER: ') print('Primeira pessoa do singular: EU %s'%verbo_primeira_singular(verbo)) print('Segunda pessoa do singular: TU %s'%verbo_segunda_singular(verbo)) print('Terceira pessoa do singular: ELE %s'%verbo_terceira_singular(verbo)) print('Primeira pessoa do plural: NÓS %s'%verbo_primeira_plural(verbo)) print('Segunda pessoa do plural: VÓS %s'%verbo_segunda_plural(verbo)) print('Terceira pessoa do plural: ELES %s'%verbo_terceira_plural(verbo)) def verbo_primeira_singular(verbo): i = 0 novo_verbo = '' while i < len(verbo): if (verbo[i]=='e') and (verbo[i+1]=='r'): novo_verbo += 'o' elif (verbo[i]=='r') and (verbo[i-1]=='e'): novo_verbo += '' else: novo_verbo += verbo[i] i += 1 return novo_verbo def verbo_segunda_singular(verbo): i = 0 novo_verbo = '' while i < len(verbo): if (verbo[i]=='r') and (verbo[i-1]=='e'): novo_verbo += 's' else: novo_verbo += verbo[i] i += 1 return novo_verbo def verbo_terceira_singular(verbo): i = 1 novo_verbo = '' anterior = '' while i <= len(verbo): caractere = ord(verbo[i-1]) # 3 pessoa do singular if (caractere==82 or caractere==114) and\ (anterior==69 or anterior==101): novo_verbo = novo_verbo + '' else: str_caractere = chr(caractere) novo_verbo = novo_verbo + str_caractere anterior = caractere i += 1 return novo_verbo def verbo_primeira_plural(verbo): i = 0 novo_verbo = '' while i < len(verbo): if (verbo[i]=='e') and (verbo[i+1]=='r'): novo_verbo += 'emos' elif (verbo[i]=='r') and (verbo[i-1]=='e'): novo_verbo += '' else: novo_verbo += verbo[i] i += 1 return novo_verbo def verbo_segunda_plural(verbo): i = 0 novo_verbo = '' while i < len(verbo): if (verbo[i]=='e') and (verbo[i+1]=='r'): novo_verbo += 'eis' elif (verbo[i]=='r') and (verbo[i-1]=='e'): novo_verbo += '' else: novo_verbo += verbo[i] i += 1 return novo_verbo def verbo_terceira_plural(verbo): i = 0 novo_verbo = '' while i < len(verbo): if (verbo[i]=='e') and (verbo[i+1]=='r'): novo_verbo += 'em' elif (verbo[i]=='r') and (verbo[i-1]=='e'): novo_verbo += '' else: novo_verbo += verbo[i] i += 1 return novo_verbo if __name__ == '__main__': main()
460c6b8c05cf1274ee9d9f5705cd2fb50350911e
ChrisVelasco0312/misionTicUTP_class
/Ciclo_1_fundamentos/Unidad_3/Clase_8/reloj.py
476
3.6875
4
# Se inician la variables en 0 segundos = 0 minutos = 0 # Dada la condicion minutos < 60 # se anida otro ciclo donde se da la condición segundos < 60 while minutos < 60: while segundos < 60: segundos += 1 # Cada ciclo aumenta un segundo minutos += 1 # cuando sale del ciclo se aumenta un minuto segundos = 0 # cuando aumenta un minuto los segundos vuelven a 0 # el ciclo completaría una hora # Este algoritmo solo se ejemplifica bajo el modo debug
4618834d4d3f964451b51f4b907ee904181ec196
sudh29/Tree
/Insert_Del.py
2,342
3.890625
4
# Insert and Delete in tree class Node: def __init__(self, data): self.left = None self.right = None self.val = data def printLevelOrder(root): if not root: return q = [] q.append(root) while len(q) > 0: node = q.pop(0) print(node.val, end=" ") if node.left is not None: q.append(node.left) if node.right is not None: q.append(node.right) def insert(root, data): if not root: root = Node(data) return q = [] q.append(root) while len(q): root = q.pop(0) if not root.left: root.left = Node(data) break else: q.append(root.left) if not root.right: root.right = Node(data) break else: q.append(root.right) def deleteDeepest(root, data): q = [] q.append(root) while len(q): temp = q.pop(0) if temp is data: temp = None return if temp.right: if temp.right is data: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is data: temp.left = None return else: q.append(temp.left) # function to delete element in binary tree def deletion(root, data): if root == None: return None if root.left == None and root.right == None: if root.val == data: return None else: return root key_node = None q = [] q.append(root) while len(q): temp = q.pop(0) if temp.val == data: key_node = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if key_node: x = temp.val deleteDeepest(root, temp) key_node.val = x return root if __name__ == "__main__": root = Node(10) root.left = Node(11) root.left.left = Node(7) root.right = Node(9) root.right.left = Node(15) root.right.right = Node(8) key = 12 insert(root, key) printLevelOrder(root) print() key = 11 root = deletion(root, key) printLevelOrder(root) print()
f64282aa00334a0bb823efe766c6cbb7fe8b7f3c
rojcewiczj/Javascript-Python-practice
/Python-Practice/AlgoExpert3/AlgoExpert3/15second.py
247
3.9375
4
def binarySearch(array, target): left = 0 right = len(array) -1 while (left <= right): mid = (left + right) // 2 if array[mid] == target: return mid if target > array[mid]: left = mid + 1 else: right = mid -1 return -1
4b2523f67cb5ceec9dbcaee027f95f65d6514b49
kshirsagarsiddharth/Algorithms_and_Data_Structures
/Tree/binary_tree/find_maximum_element_in_a_tree.py
1,123
4.15625
4
# python recursive code to find the maximum element in a binary tree class newNode: def __init__(self,data): self.data = data self.right = None self.left = None def find_max_iteratively(root): queue = [] queue.append(root) max_val = 0 while(len(queue) > 0): temp = queue.pop(0) if temp.data > max_val: max_val = temp.data if temp.left is not None: queue.append(temp.left) if temp.right is not None: queue.append(temp.right) return max_val max_data = float("-inf") def find_max_recursively(root): global max_data if not root: return max_data if root.data > max_data: max_data = root.data find_max_recursively(root.left) find_max_recursively(root.right) return max_data root = newNode(2) root.left = newNode(7) root.right = newNode(5) root.left.right = newNode(6) root.left.right.left=newNode(1) root.left.right.right=newNode(11) root.right.right=newNode(9) root.right.right.left=newNode(4) find_max_recursively(root)
05b323ee012db05e55da42194deeb8436cad1c22
igorprati/python_modulo
/codelabs01/exercicio01.py
646
4.09375
4
# Crie um código em Python que pede qual tabuada o usuário quer ver, em # seguida imprima essa tabuada. n = int(input("Digite qual tabuada você quer ver: ")) print("------ soma -------") for i in range(1, 11): soma = n + i print(f"{n} + {i} = {soma}") print("\n------ multiplicação -------") for i in range(1, 11): multiplicacao = n * i print(f"{n} * {i} = {multiplicacao}") print("\n------ divisão -------") for i in range(1, 11): divisao = n / i print(f"{n} / {i} = {divisao:.2f}") print("\n------ subtração -------") for i in range(1, 11): subtracao = n - i print(f"{n} - {i} = {subtracao}")
aa86ac4f5d91c20aae0a013d63fb7c00a2dca183
GuptaAman08/CompetitiveCoding
/Hacker Rank/Tree/vlsd.py
1,185
3.8125
4
# Vertical level sum difference # Link : https://www.hackerrank.com/contests/rtech-april-18-01/challenges/vertical-level-sum-differences/problem from collections import defaultdict class Node: def __init__(self, key): self.data = key self.left = None self.right = None # Find minimum and maximum horizontal distance from root def FindMinMax(node, d, hd): if node is None: return if hd % 2 == 0: d['even'] += node.data else: d['odd'] += node.data FindMinMax(node.left, d, hd-1) FindMinMax(node.right, d, hd+1) def verticalOrder(root): if root is None: return d = defaultdict(int) d['odd'] = 0 d['even'] = 0 FindMinMax(root, d, 0) # print(d) print(d['even'] - d['odd']) def createTree(a, root, i, n): if i < n and a[i] != -1: temp = Node(a[i]) root = temp root.left = createTree(a, root.left, 2*i + 1, n) root.right = createTree(a, root.right, 2*i + 2, n) return root n = int(input()) a = [int(x) for x in input().split()] root = None root = createTree(a, root, 0, n) verticalOrder(root)
ce9897fda94e7c26bc1462b142a3f037f8b06e02
WilbertHo/hackerrank
/challenges/algorithms/dynamic_programming/candies/py/candies.py
1,462
3.84375
4
#!/usr/bin/env python import fileinput def candies(ratings): """ Return the minimum number of candies. Scan the ratings from left to right. If the current rating is larger than the previous, the current candies is the previous candies + 1. If the current rating is equal to or less than the previous rating, set candies to 1. Scan the ratings from right to left. If the current rating is larger than the previous, [and the current candies is less than the previous candies?], increment the candies. If the current is equal to or less than the previous, continue. :params ratings: list of ints representing rating per child :returns list of ints representing the number of candies per child """ candies = [1 for child in range(0, len(ratings))] # scan left to right for i, rating in enumerate(ratings[1:], start=1): if rating > ratings[i - 1]: candies[i] = candies[i - 1] + 1 # scan right to left for i, rating in reversed(list(enumerate(ratings[:-1]))): if rating > ratings[i + 1] and candies[i] <= candies[i + 1]: candies[i] = candies[i + 1] + 1 return candies def main(): input = [line.strip() for line in fileinput.input()] # first line is number of test cases input.pop(0) print sum(candies(map(int, input))) if __name__ == '__main__': main()
db08920be9ca4f85b504779bfdfbb61e5cb00eea
guillermospindola/python
/08argumentosbasicosscripts.py
759
3.734375
4
""" Aqui se explica como añadir funcionalidad a los scripts """ #los imports se añaden al principio de un script import sys #Un modulo no es más que un archivo con extension .py from modulo_importable import saludar_modulo def parsear_argumentos_basicos(): argumentos = sys.argv[1:] return argumentos def main(argumentos): """ Aqui ponemos la funcionalidad principal de nuestro script """ if argumentos[0] == "saludar": nombre = argumentos[1] saludar_modulo(nombre) if __name__ == "__main__": #Este codigo solo se ejecutara si ejecutamos este script directamente argumentos = parsear_argumentos_basicos() print("Argumentos pasados al script: ", argumentos) main(argumentos)
fb4537451bce8f63a8af2a3c2acd6861efd96bd8
ONLY-LIVE-CODE/Algoritms_on_Stepik
/2. Введение: теория и задачи/2.2 Числа Фибоначчи/2.2.3.py
1,015
3.8125
4
""" Задача на программирование повышенной сложности: огромное число Фибоначчи по модулю. Даны целые числа (1 <= n <= 10^18) и (2 <= m <= 10^5), необходимо найти остаток от деления n-го числа Фибоначчи на m. Time Limit: 3 секунды Memory Limit: 256 MB """ import time def fib_mod(n, m): k = 0 lst = [0, 1] # Период Пизано всегда начинается с 0, 1 # Заполняем период Пизано остатками от деления на "m" for i in range(2, 6*m): lst.append((lst[i - 1] + lst[i - 2]) % m) k += 1 if (lst[i] == 1) and (lst[i-1] == 0): break return lst[(n % k)] def main(): n, m = map(int, input().split()) start_time = time.time() print(fib_mod(n, m)) print("Time: %s seconds" % (time.time() - start_time)) if __name__ == "__main__": main()
80a015fa1791e00d4cd00711caefd3b5b080b8c1
OlegMeleshin/Nonsense1
/Тренировка 1.py
3,540
4.1875
4
a = 10 b = 15 print(f"Переменная a = {a}, b = {b}") # #a = int(input("Введите переменную a: ")) #b = int(input("Введите переменную b: ")) #print(f"a = {a}, b = {b}") #АРИФМЕТИКА #one = int(input("INSERT FIRST PARAMETER: ")) #two = int(input("INSERT SECOND PARAMETER: ")) #print(f"Произведение {one} на {two} = {one * two}") #print(f"Сумма {one} и {two} = {one + two}") #print(f"Разность {one} и {two} = {one - two}") #print(f"Целоисчисленное деление {two} на {one} = {two // one}") #СЛОЖЕНИЕ, УМНОЖЕНИЕ НА 2 #p = int(input("Введите первую переменную: ")) #m = int(input("Введите вторую переменную: ")) #sum = (p + m)*2 #print(f"Сумма p и m, умноженная на 2: {sum}") #ПРИБАВИТЬ, УМНОЖИТЬ, ВОЗВЕСТИ В СТЕПЕНЬ #a = int(input("Введите значение: ")) #a += int(input("Прибавить: ")) #print(a) #a *= int(input("Умножить на: ")) #print(a) #a **= int(input("Возвести в степень: ")) #print(f"Результат: {a}") #УМНОЖЕНИЕ #one = 5 #two = 10 #three = 15 #print(5 * 10 *15) #ПЕРЕВОЗКА МЕБЕЛИ #Ch = int(input("Введите количество кресел: ")) #A = float(input(f"Укажите вес кресла, кг: ")) #Tab = int(input("Введите количество столов: ")) #B = float(input(f"Укажите вес стола, кг: ")) #Cargo = int(input("Введите вместимость грузовика, кг: ")) # #a = Ch * A + Tab * B < Cargo # #if a : # print("Ok") # print(f"Осталось места {Cargo - (Ch * A + Tab * B)} килограмм") #else: # print("NotOK") # print(f"Перегрузка составит {(Ch * A + Tab * B) - Cargo} килограмм") #РАЗНЫЕ ВЫЧИСЛЕНИЯ #a = int(input("Введите переменную a: ")) #b = int(input("Введите переменную b: ")) #print(f"a * b = {a * b}") #print(f"a / b = {a / b}") #print(f"b / a = {b / a}") #print(f"a + b = {a + b}") #print(f"a - b = {a - b}") #print(f"b - a = {b - a}") #СИСТЕМЫ СЧИСЛЕНИЯ ПЕРЕВОД #a = int(input("Введите число: ")) #print(bin(a)) #print(oct(a)) #print(hex(a)) #a = "Вторник" #b = "Понедельник" #print(b, ", ", a) #BRACKET_CALC #a = int(input("Insert a: ")) #b = int(input("Insert b: ")) #c = int(input("Insert c: ")) #f = (((a * b) + (a * c))**3) / 2 #print(f) #HELLO! #username = input("Type your name: ") #print(f"Hello, {username}!") #АНКЕТА #username = input("Type your name: ") #age = int(input("Type your age: ")) #adress = input("Type your adress: ") #country = input("Type your country: ") #birthyear = 2020 - age #print(f"{username}! You are living in {country}, your adress is {adress}, you were born in {2020 - age}") #???????????name, age, adress, country = input("Insert your name, age, adress, counry: ") #print(name, age, adress, counry) #ЁЛОЧКА #s = "*" #print(" " * 9, s) #print(" " * 8, s * 3) #print(" " * 7, s * 5) #print(" " * 8, s * 3) #print(" " * 7, s * 5) #print(" " * 6, s * 7) #print(" " * 5, s * 9)
f70be9e1e56de575ec91aacb8b2d634092c3d85d
Girum-Haile/PythonStudy
/dbConnect.py
2,958
3.96875
4
import sqlite3 class DBConnect: def __init__(self): self.db = sqlite3.connect("personalInformation.db") self.db.row_factory = sqlite3.Row self.db.execute("create table if not exists Info(Name text, Sex text, Age int)") self.db.commit() def saverecord(self, name, sex, age): self.db.execute("insert into Info(Name, Sex, Age) values(?,?,?)", (name, sex, age)) self.db.commit() print("Info added successfully") def showdetail(self): show = self.db.execute("select * from Info") for row in show: print("Name:{},\tSex:{},\tAge: {}".format(row[0], row[1], row[2])) def deleterecord(self, name): try: cursor = self.db.cursor() print("Connected to SQLite") sql_update_query = """DELETE from Info where name = ?""" cursor.execute(sql_update_query, (name,)) self.db.commit() print("Record deleted successfully") cursor.close() except sqlite3.Error as error: print("Failed to delete record from a sqlite table", error) def updaterecord(self, age, name): try: cursor = self.db.cursor() print("Connected to SQLite") sql_update_query = """update Info set age=? where name = ?""" data = (age, name) cursor.execute(sql_update_query, data) self.db.commit() print("Record updated successfully") cursor.close() except sqlite3.Error as error: print("Failed to update record from a sqlite table", error) def main(): dbc = DBConnect() print("------------main menu-------------") index = int(input("\n1/ to add info\n2/ to see detail\n3/ delete info\n4/update info\n>>")) if index == 1: name = input("enter your name: ") sex = input("enter your sex: ") age = int(input("enter your age: ")) dbc.saverecord(name, sex, age) again = int(input("choose: press 4 to add another info or 5 to exit: ")) if again == 4: main() else: print("done") elif index == 2: dbc.showdetail() again = int(input("choose: press 4 to move to main menu or 5 to exit: ")) if again == 4: main() else: print("done") elif index == 3: name = input("enter name to delete") dbc.deleterecord(name) again = int(input("choose: press 4 to add another info or 5 to exit: ")) if again == 4: main() else: print("done") elif index == 4: name = input("enter name to update") age = int(input("enter the new age")) dbc.updaterecord(age,name) again = int(input("choose: press 4 to add another info or 5 to exit: ")) if again == 4: main() else: print("done") else: print("wrong input") if __name__ == '__main__':main()
4458fa1b9f0a62898c1040a8b76c249d2526040f
Thirumurugan-12/Python-programs-11th
/comparision.py
183
3.96875
4
t1=eval(input("Enter the tuple")) t2=eval(input("Enter the tuple 2")) if t1 == t2 : print("Every element in t1 are present in t2") else: print("Tuples doesn't match")
c5830f39c88ef83167b43d7b9e7596cd2cf1bd64
aditp928/cyber-secruitiy-
/1-Lesson-Plans/Unit03-Python/1/Activities/03-Stu_MyFirstVariable/Solved/Myvariables.py
266
4.09375
4
# Create a variable called "name". Store your name as its value. name = "Ahmed" # Create a variable called "city_count". Store the number of cities you've lived in. city_count = "6" # Print the name variable and city_count variable. print(name) print(city_count)
0a7f8b985fb307ddb14bcb004a8109c9ce5076ae
gulsahyildiz/Color-To-Grayscale
/ColorToGray_yildiz.py
997
3.875
4
# Import Libraries from PIL import Image import matplotlib.pyplot as plt # Get Image Input path = input("Enter the exact path to the image: ") # Size of the Image img = Image.open(path) width = img.size[0] height = img.size[1] # Get the Pixels def pixels(img, x, y): if x > width or y > height: return None pixel = img.getpixel((x, y)) return pixel # Convert RGB Pixels to Gray def rgb2gray(img): gray_scale = img pixel = gray_scale.load() for x in range (0, width): for y in range (0, height): rgbpixels = pixels(img, x, y) red = rgbpixels[0] green = rgbpixels[1] blue = rgbpixels[2] gray = (red*0.299 + green*0.587 + blue*0.114) pixel[x,y] = (int(gray), int(gray), int(gray)) return gray_scale # Display Both the Original and the Gray Image image1 = plt.figure(1) plt.imshow(img) image2 = plt.figure(2) grayImage = rgb2gray(img) plt.imshow(grayImage) plt.show()
ea1168fa716277aab83ea05d36ef3ad17fdb6be7
camitt/PracticePython_org
/PP_Exercise_2.py
1,421
4.25
4
# Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? # # Extras: # # If the number is a multiple of 4, print out a different message. # Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. def isEven(number): if number % 4 == 0: return "4" elif number % 2 == 0: return True else: return False def inputsDivisible(number, number2): if number % number2 == 0: return True else: return False def returnStatement(state, number, number2): if state == True: print("The first number you gave is even") elif state == "4": print("The first number you gave is evenly divisible by 4") else: print("The first number you gave is odd") if inputsDivisible(number, number2): print("The second number evenly divides into the first number given.") else: print("The second number does not evenly divide into the first number given.") def main(): number = int(input("Enter a number: ")) number2 = int(input("Enter a second number: ")) state = isEven(number) returnStatement(state, number, number2) main()
08990afcb231943825944719024138ddd172e09a
shreyaskshastry/Basic_Algoritms
/PowerSet.py
451
3.8125
4
import math def powerSet(arr): powers = [] total = int(math.pow(2, len(arr))) for i in range(0, total): tempSet = [] num = "{0:b}".format(i) while len(num) < len(arr): num = '0' + num for b in range(0, len(num)): if num[b] == '1': tempSet.append(arr[b]) powers.append(tempSet) return powers print(powerSet([1, 2, 3]))
15ee3a0d5c3231bb1258b50ac8e010610cca5279
CSCI3106/Fall2020KattisSolutions-BrianChalfant
/twostones.py
64
3.703125
4
n = int(input()) print("bob") if n % 2 == 0 else print("alice")
d7b90828d995122103ee8414e370ffe9c45e9a0e
leeanna96/Python
/Chap04/구구단 출력_도전문제.py
91
3.609375
4
i=1 num=int(input("정수 입력: ")) while i<10: print(num,"*",i,"=",num*i) i+=1
c1e0f9e5e8ecd4ff8058d6c5c9e492e922ae4a42
Alba126/Laba9
/individual1.py
560
3.84375
4
#!/usr/bin/env python3 # -*- config: utf-8 -*- # Вариант 1. Написать программу, которая считывает из текстового файла три предложения и выводит их # в обратном порядке if __name__ == '__main__': with open('individual1.txt', 'r') as f: text = f.read() text = text.replace("!", ".") text = text.replace("?", ".") sentence = text.split(".") reverse_sentence = '. '.join(reversed(sentence)) print(reverse_sentence)
c7e168c61ccf0600d6878a568305286c3ac40766
marinakuschenko/STP
/ЛР_6.py
649
3.78125
4
import math a=float(input("a=")) b=float(input("b=")) c=float(input("c=")) if a!=0 and b!=0 and c!=0: D=b*b-4*a*c if D>0: x1=(-b+math.sqrt(D))/2*a x2=(-b-math.sqrt(D))/2*a print(x1,x2) if D==0: x1=-b/2*a print(x1) if D<0: print("Корней нет") if b!=0 and c==0: #a*math.pow(x)+b*x==0 x1=0 x2=b print(x1,x2) if a!=0 and b==0 and c!=0: if c<0: x1=math.sqrt(c/a) x2=-math.sqrt(c/a) print(x1,x2) if c>0: print("Корней нет") if b==0 and c==0: print(x1=0) if a==0 and b!=0 and c!=0: x=-c/b print(x)
3aa681a79dfc32b1df98283102389d1364554a02
remnantdochi/exersize
/190921.py
875
3.640625
4
def solution(emails): answer = 0 for item in emails: i1 = item.find('@') print('i1',i1) if i1 == -1: continue name = ''.join(item[:i1]) if name.lower() != name: print(name.lower()) print(item[:i1]) print('test1') continue if '@' in item[i1+1:]: print('test2') continue i2 = item[i1+1:].find('.') if i2 == -1: continue print(item[i2+i1+1:]) if item[i2+i1+1:] == 'com' or item[i2+2+len(name):] != 'net' and item[i2+2+len(name):] != 'org': print('test3') print(item[i2+2+len(name):] != 'com') domain = ''.join(item[i2+1+len(name):]) print(domain) print(domain != 'com') continue answer +=1 return answer print(solution(["a@abc.com"]))
f0419e2a69d1701f352578d88d2503ee1bfc1d73
Sunshine168/algorithm
/python/subSets.py
965
4.0625
4
#解决subSets模板 # 先判断输入的list是否存在与长度是否大于0 # 使用一个subSetsHelper # params依次 是字符串本身,起始坐标,深度遍历临时存储的temp_list ret是结果 # https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73049 class Solution: """ @param S: The set of numbers. @return: A list of lists. See example. """ def subsets(self, S): result = [] if(S is None ): return result def subSetsHelper(nums,startIndex,temp_list,ret): #生成新对象 ret.append([]+temp_list) for i in range(startIndex,len(nums)): #先添加,再移除 temp_list.append(nums[i]) subSetsHelper(nums,i+1,temp_list,ret) temp_list.pop() S.sort() subSetsHelper(S,0,[],result) return result solution = Solution() b=solution.subsets([1,2,3]) print(b)
2060c4d9be009cf550d1344fed863ee85ba8f7a4
Ng-ethe/SCAMP-Assesment
/fibbonacci.py
446
3.984375
4
def fibbonacci (number): fibb_seq=[] for n in range (number+1): if n==0: fibb_seq.append(n) continue elif n ==1: fibb_seq.append(1) continue else: next_num = fibb_seq[n-2] + fibb_seq[n-1] fibb_seq.append(next_num) for l in fibb_seq: print (l) number= int(input("Enter any interger: ")) fibbonacci (number)
d975d46ea7bdea559ebeee7f3d7f03a8bb4f49ba
src8655/python_ch2.2
/unpacking.py
1,028
3.8125
4
# packing : tuple만 가능하다 t = 10, 20, 30, 'python' print(t, type(t)) # unpacking : tuple을 각 변수로 변환 a, b, c, d = t print(a, b, c, d) print(type(a), type(b), type(c), type(d)) # 에러 : 개수를 안맞추면 에러가 날 수 있음 # a, b, c = t # a, b, c, d, e, f = t # unpacking extended : 언패킹 확장 # 개수를 안맞춰도 되게 잔처리(*) t = (1, 2, 3, 4, 5) a, *b = t # a에 하나만 받고 b에 나머지를 다 받는다 print(a, b) print(type(a), type(b)) # 잔처리(*)는 list로 받는다 *a, b = t print(a, b) # b에 하나만 받고 나머지는 a에 다 받는다 print(type(a), type(b)) a, b, *c = t print(a, b, c) a, *b, c = t print(a, b, c) # cf. 여러개 파라미터를 받는 함수 def mysum(*num): s = 0 for i in num: s += i return s print(mysum(1, 2)) print(mysum(1, 2, 3)) print(mysum(1, 2, 3, 4, 5, 6)) # c의 printf 만들어보기 # printf("name: %s, age: %d", "둘리", 10) # 결과 # name: 둘리, age: 10
238100d453e2b18fc1bac43766290dcc03fe72b3
Gi1ia/TechNoteBook
/Algorithm/015_3sum.py
3,348
3.828125
4
""" Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) """ class Solution(object): def threeSum_no_deDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] :Note: This solution will contain duplicated answer. """ nums.sort() # if we change res to a set: res = set() # and return the set in list format, the de-dup problem will be solved. # 1. return list(res) # 2. return map(list, res) res = [] for i in range (0, len(nums) - 2): # exclude last two indexes if i > 0 and nums[i] == nums[i - 1]: # first index(x) should be identical; [x, y, z] continue left = i + 1 right = len(nums) - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum < 0: left += 1 elif current_sum > 0: right -= 1 else: res.append((nums[i], nums[left], nums[right])) left += 1 right -= 1 return res def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] This is faster then the one below. """ nums.sort() res = [] for i in range (0, len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue left = i + 1 right = len(nums) - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum < 0: left += 1 elif current_sum > 0: right -= 1 else: res.append((nums[i], nums[left], nums[right])) # by checking the next index value to solve de-dup. while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right -1] == nums[right]: right -= 1 # Note: Following code is for normal cases. # Without the following line, the loop will be infinite. left, right = left + 1, right - 1 return res def threeSum_naive_approach(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = set() for i in range(0, len(nums) - 2): left = i + 1 right = len(nums) - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum < 0: left += 1 elif current_sum > 0: right -= 1 else: res.add((nums[i], nums[left], nums[right])) left += 1 right -= 1 return map(list, res) s = Solution() print (s.threeSum([-2,0,0,2,2])) print (s.threeSum_no_deDup([-2,0,0,2,2])) input("Press Enter")
af2fdb098592774023eb26b1bce051e8174089e4
VaishnavJois/python_ws
/day3/armstrong_number.py
364
4.03125
4
#armstrong number def armstrong_num(num): res = 0 num_1 = num while num!=0: r = num%10 res = res + r**3 num //= 10 return num_1 == res inp = int(input('Enter a number: ')) if armstrong_num(inp): print(f'Given number {inp} is an armstrong number') else: print(f'Given number {inp} is Neil armstrong')
07a0ec117ce87a66d9a6d9c6eedb3942ef663ffd
jerseymec/Orapy
/FantasyG.py
579
3.78125
4
stuff = {'rope': 1,'torch':6,'gold coin':42,'dagger':1,'arrow':12} dragonloot= ['gold coin','dagger','gold coin','gold coin','ruby'] def displayInventory(inventory): print("Inventory:") item_total = 0 for k,v in inventory.items(): item_total +=v print("Total number of items: " + str(item_total)) def addToInventory(inventory,addedItems): for Aitem in addedItems: inventory.setdefault(Aitem,0) inventory[Aitem] +=1 displayInventory(stuff) addToInventory(stuff,dragonloot) displayInventory(stuff) print(stuff)
ae002c1cb1c5ba0673e60cd4929fd11cfa85f2d9
feliperromao/curso-python-cod3r
/poo/Carro.py
771
3.734375
4
class Carro: def __init__(self, velocidadeMaxima=0): self.velocidadeMaxima = velocidadeMaxima self.velocidadeAtual = 0 def acelerar(self, delta=5): if self.velocidadeMaxima >= self.velocidadeAtual + delta: self.velocidadeAtual += delta else: self.velocidadeAtual = self.velocidadeMaxima return self.velocidadeAtual def frear(self, delta=5): if self.velocidadeAtual - delta > 0: self.velocidadeAtual -= delta else: self.velocidadeAtual = 0 return self.velocidadeAtual if __name__ == "__main__": carro = Carro(180) for _ in range(20): print(carro.acelerar(20)) for _ in range(20): print(carro.frear(20))
45c7a26d28e6c9dd9f340548ada4b54eaf2e513d
crishonsou/modern_python3_bootcamp
/calculo_fatorial_utilizando_função.py
319
3.984375
4
def calculaFatorial(numero): fatorial = 1 contador = 1 while contador <= numero: fatorial = fatorial * contador contador += 1 return fatorial num = int(input('Digite um numero: ')) resultado = calculaFatorial(num) print(f'O fatorial de {num} é {resultado}')
bcd009c655d2973c03f46b992a12bb7e48a4a7af
esharma22/Python_Practice
/ifelse.py
155
3.984375
4
#!/usr/bin/python a = 10 b = 15 c = a + b if (a < b): print "a is less than b" elif (b < c): print "b is less than c" else: print "c is the greatest"
1421fcdbf10923756d372ffaf7b8f599a63b8729
reyllama/leetcode
/Python/#1476.py
1,311
3.65625
4
""" 1476. Subrectangle Queries Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods: 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2). 2. getValue(int row, int col) Returns the current value of the coordinate (row,col) from the rectangle. """ import numpy as np class SubrectangleQueries: def __init__(self, rectangle: List[List[int]]): self.rectangle = np.array(rectangle) def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None: self.rectangle[row1:row2+1, col1:col2+1] = newValue def getValue(self, row: int, col: int) -> int: return self.rectangle[row][col] # Your SubrectangleQueries object will be instantiated and called as such: # obj = SubrectangleQueries(rectangle) # obj.updateSubrectangle(row1,col1,row2,col2,newValue) # param_2 = obj.getValue(row,col) """ Runtime: 200 ms, faster than 71.23% of Python3 online submissions for Subrectangle Queries. Memory Usage: 32.7 MB, less than 6.85% of Python3 online submissions for Subrectangle Queries. """
b207aab12369beaab9be5103ca0d41e435430f4d
CristinaCallejo/Classroom-Materials
/Labs Solutions/Module 1/lab-data_cleaning/your-code/weather.py
2,409
3.671875
4
#!/usr/bin/env python # coding: utf-8 # ## Global Historical Climatology Network Dataset # Variables are stored in both rows and columns # This dataset represents the daily weather records for a weather station (MX17004) in Mexico for five months in 2010. # In[1]: import os # se importan librerias import numpy as np import pandas as pd import matplotlib.pyplot as plt # In[2]: datos=pd.read_csv(os.path.join('../weather-raw.csv')) # se cargan los datos print (datos.head()) # In[3]: #print (datos.info()) # informacion de no nulos print (datos.describe()) # descripcion estadistica # In[4]: null=datos.isna().sum() # se miran los valores nulos null[null>0] # In[5]: # me quedo solo con los datos de los sensores y pongo a cero los NaN para bucle datos=datos.fillna(0) datos=datos.iloc[:,4::] # todas las columnas desde la 5ª datos=datos.transpose() print (datos) # ahora cada columna es t_max o t_min de cada mes, falta septiembre # In[12]: # extraigo los datos de temperatura lista=[datos[c] for c in datos] # lista de cada columna de los datos t_Max=[np.mean([e for e in lista[i] if e!=0]) for i in range(len(lista)) if i%2==0] # temperatura maxima t_min=[np.mean([e for e in lista[i] if e!=0]) for i in range(len(lista)) if i%2==1] # temperatura minima # septiembre falta, hago la media de los meses adyacentes y luego las inserto en la lista sep_M=(t_Max[7]+t_Max[8])/2 sep_m=(t_min[7]+t_min[8])/2 t_Max.insert(8, sep_M) t_min.insert(8, sep_m) # In[13]: print (t_Max) print (t_min) # In[16]: plt.plot([i for i in range(12)], t_Max, linestyle='-', marker='.',color = 'r') # plot rojo temp Max plt.plot([i for i in range(12)], t_min, linestyle='-', marker='.',color = 'b') # plot azul temp min plt.xlabel('Meses',size=13) plt.ylabel('Temperatura',size=13) plt.title('MX17004',size=14,fontweight='bold') plt.savefig('temperaturas_MX17004.png', format='png') # guarda imagen plt.show() # In[20]: # construyo el dataframe completamente limpiado Meses=['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'] weather=pd.DataFrame(columns=Meses) weather=weather.transpose() weather['T_Max']=t_Max weather['T_min']=t_min weather.to_csv('weather.csv') # se guarda el nuevo dataframe print (weather) # In[ ]: # ##
be7604df227006c9de4075194f0cbda22a23fc61
clairejaja/project-euler
/src/main/python/problem2/even_fibonacci_numbers.py
871
4.125
4
# Claire Jaja # 11/1/2014 # # Project Euler # Problem 2 # Even Fibonacci numbers # # Each new term in the Fibonacci sequence is generated by adding # the previous two terms. # By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence # whose values do not exceed four million, # find the sum of the even-valued terms. def main(): max_value = 4000000 # set up first three terms previous_previous_term = 1 previous_term = 1 current_term = 2 my_sum = 0 while current_term < max_value: if current_term % 2 == 0: my_sum += current_term previous_previous_term = previous_term previous_term = current_term current_term = previous_term + previous_previous_term print(my_sum) if __name__ == "__main__": main()
c9a74ad5885ea02548dc6f3a664738fb01c990f1
Juryun/programmers_coding_test_practice
/크레인인형뽑기게임/solution.py
647
3.53125
4
def solution(board, moves): answer = 0 stack=[] for i in range(len(moves)): move = moves[i]-1 for j in range(len(board[0])): if board[j][move] !=0: if len(stack)==0 : stack.append(board[j][move]) board[j][move] = 0 break if stack[-1] == board[j][move]: stack.pop() answer = answer +2 else : stack.append(board[j][move]) board[j][move] = 0 break return answer
880c754f44fd11338851891ed5671762064cec7f
pancakewaffles/Stuff-I-learnt
/Python Refresher/Python Math/6 Drawing Geometric Shapes, Animations, Fractals, Barnsley Fern, Sierpinski, Henon, Mandelbrot/sierpinski.py
1,838
3.875
4
#! sierpinski.py # Sierpinski Triangle using probabilities. ''' This is a different method of drawing Sierpinski. We originally drew it in Java using recursion, remember? Here we employ a different method, that of probabilities. Transformation 1: x_(n+1) = 0.5x_n y_(n+1) = 0.5y_n Transformation 2: x_(n+1) = 0.5x_n + 0.5 y_(n+1) = 0.5y_n + 0.5 Transformation 3: x_(n+1) = 0.5x_n + 1 y_(n+1) = 0.5y_n Each of the transformations has an equal probability of being selected - 1/3. If you think about it, not that different from the recursion method, eh? In this case, we draw a point at each coordinate. ''' import random; import matplotlib.pyplot as plt; def transformation_1(p): x = p[0]; y = p[1]; x1 = 0.5*x; y1 = 0.5*y; return x1,y1; def transformation_2(p): x = p[0]; y = p[1]; x1 = 0.5*x + 0.5; y1 = 0.5*y + 0.5; return x1,y1; def transformation_3(p): x = p[0]; y = p[1]; x1 = 0.5*x + 1; y1 = 0.5*y; return x1,y1; def transform(p): transformations_list = [ transformation_1,transformation_2,transformation_3]; r = random.random(); if(r<= 1/3): x1,y1 = transformation_1(p); elif(r<= 2/3): x1,y1 = transformation_2(p); elif(r<= 3/3): x1,y1 = transformation_3(p); return x1,y1; def draw(n): x = [0]; # Start at point (0,0); y = [0]; x_n = 0; y_n = 0; for i in range(n): x_n , y_n = transform( (x_n,y_n) ); x.append(x_n); y.append(y_n); return x,y; if(__name__ == "__main__"): n = int(input("Enter how many points you want to use: ")); x,y = draw(n); # returns list of x and y coordinates plt.plot(x,y,"o"); plt.title("Sierpinski Triangle with {0} points".format(n)); plt.show();
ae4983a362e0dd7182b2ff9d5bb49866a5f51816
pooyasp/ctci
/4/fourDotEight.py
1,232
3.59375
4
def isSubTree(t1, t2): if t1 == None: return False if isSubTree(t1.left, t2) or isSubTree(t1.right, t2): return True if t1.content == t2.content: return treeMatch(t1, t2) return False def treeMatch(t1, t2): if t1 == None and t2 == None: return True if (t1 == None and t2 != None) or (t1 != None and t2 == None): return False return t1.content == t2.content and treeMatch(t1.left, t2.left) and treeMatch(t1.right, t2.right) class BTNode(object): def __init__(self, content = None, left = None, right = None): self.content = content self.left = left self.right = right def __str__(self): return str(self.content) if __name__ == '__main__': pass n1 = BTNode(1) n2 = BTNode(2) n3 = BTNode(3) n4 = BTNode(4) n5 = BTNode(5) n6 = BTNode(6) n7 = BTNode(7) n8 = BTNode(8) n9 = BTNode(9) n10 = BTNode(10) n11 = BTNode(11) n12 = BTNode(12) n13 = BTNode(13) n14 = BTNode(14) n15 = BTNode(15) n16 = BTNode(16) n17 = BTNode(17) n1.left = n8 n2.left = n1 n2.right = n3 n3.left = n10 n4.left = n2 n4.right = n6 n5.right = n9 n6.left = n5 n6.right = n7 n7.right = n12 n9.left = n11 n10.left = n16 n10.right = n15 n12.left = n13 n12.right = n14 print(isSubTree(n4, n4))
21cd920559c6a060353c164a52e928cad3668785
hemanturvyesoftcore/Data-Science-Projects
/PythonPrograms/ArmstrongNumber.py
409
4.09375
4
from math import pow i=input('enter number = ')#string value entered lenght=len(i) j=int(i) temp = j addition=0 while temp>0: #print('while loop ') a=temp%10 addition=int(addition+pow(a,lenght)) temp=temp//10 if (j==addition): print('it is an Armstrong number : '+str(addition)) else: print('it is not an Armstrong Number : ')
25ee8a072cb5c6953a9bb6da7646a2e9175c8520
Georgia-M/Basic_scripts
/files_in_zip.py
248
3.5
4
'''work with files in a zip''' from zipfile import ZipFile import detetime file_name = "C:User/user/Desktop/proteins.zip" with ZipFile(file_name, 'r') as zip: for info in zip.infolist(): print(info) #info = all files inside the zip
cfd97e3d281e60a11f58b3cf06f555797e8339d1
1dataplease/courses
/python-courses/Programming Foundations with Python udacity/scripts/2_rename_files_remove_leading_numbers.py
660
3.671875
4
import os def rename_files(): # Get file names from the folder filelist = os.listdir(r"C:\Users\wainman\Desktop\tw\classes\py foundation\rename") print(filelist) #saves wd, temp uses dir with files in it, sets the wd back after loop saved_path = os.getcwd() print("Current working directory is: " + saved_path) os.chdir(r"C:\Users\wainman\Desktop\tw\classes\py foundation\rename") for filename in filelist: print ("Old name: " + filename) print ("New name: " + filename.translate(None, "0123456789")) os.rename(filename, filename.translate(None, "0123456789")) os.chdir(saved_path) rename_files()
c34f843708b32d04983bc7f24018474765f9fbc9
kalnaasan/university
/Programmieren 1/EPR/Übungen/Übung_03/ALnaasan_Kaddour_0016285.py
1,777
3.765625
4
__author__ = "0016285: Kaddour Alnaasan" # s8362356@stud.uni-frankfurt.de # Aufgabe 1 def loops(): def while_loop(num): num_new = 0 counter = num while counter != 0: num_new = num_new + counter counter = counter - 1 average = num_new / num print("Der Durchschnitt der Zahlen:", str(average)) def for_loop(num): num_new = 0 for counter in range(1, num + 1): num_new = num_new + counter average = num_new / num print("Der Durchschnitt der Zahlen:", str(average)) loop_kind = input("Gaben Sie den Schleifenart (while/for):") if loop_kind == "while": number = int(input("Gaben Sie eine Zahl: ")) while_loop(number) elif loop_kind == "for": number = int(input("Gaben Sie eine Zahl: ")) for_loop(number) else: loops() # loops() # Aufgabe 2 # Aufgabe 3 # Aufgabe 4 def happynumber(): start_number = int(input("Geben Sie eine Zahl: ")) worked_number = start_number mod = 1 new_number = 0 counter = 1 while worked_number != 1: while worked_number != 0: mod = worked_number % 10 worked_number = worked_number // 10 new_number = new_number + (mod * mod) print("Die neue Zahl ist:", new_number) if new_number == 1: print("Die Zahi(", start_number, ") ist fröhlich.") elif new_number == 4 or counter == 100: print("there is a loop!!!") break # if new_number != start_number: worked_number = new_number new_number = 0 counter = counter + 1 play_again = input("Wollen Sie noch mal spielen (ja/nein):") if play_again != "nein": happynumber() happynumber()
35ba90521a4e933a27966833882fb8639364208a
yuqiaoyan/Python
/my_tokenizers.py
1,616
3.796875
4
import re from nltk.corpus import stopwords exception = "\xe2\x80\x99\x93" word_pattern = re.compile(r"[a-zA-Z'-%s]+|[?!]"%exception) def tokenize_sentence(text): #function to tokenize the words word_list = word_pattern.findall(text) tokenized_word_list = [] for word in wordList: word = word.lower() if word not in stopWordsList: tokenized_word_list.append(word) #wordList = [word.lower() for word in wordList \ # if word not in stopWordsList] return(tokenized_word_list) def tokenize_sentence(sentence,unique_stop_words=[]): '''REQUIRES: a sentence unique_stop_words is a list of additional stop words you define e.g. ['wall','street'] RETURNS: a list of tokens split by spaces without stop words ''' words = [] for word in sentence.split(' '): stopwords = stopwords.words('english') stopwords = stopwords + unique_stop_words if not word.lower() in stopwords and len(word) > 2: words.append(word.lower()) return words def tokenize_text_list(text_list,unique_stop_words=[]): #REQUIRES: text_list is a list of sentences; unique_stop_words is a list of additional stopwords you can define #RETURNS: a list of tokens without stop words words = [] for text in text_list: text = text.strip() #words = [word.lower() for word in text.split(' ') if not word.lower() in nltk.corpus.stopwords.words('english')] for word in text.split(' '): stopwords = stopwords.words('english') stopwords = stopwords + unique_stop_words if not word.lower() in stopwords: words.append(word.lower()) return words
fd6afbe189b5fa47ba8b817bac89c1bf97a2c3da
christina57/lc-python
/lc-python/src/lock/246. Strobogrammatic Number.py
955
4.09375
4
""" 246. Strobogrammatic Number A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Write a function to determine if a number is strobogrammatic. The number is represented as a string. For example, the numbers "69", "88", and "818" are all strobogrammatic. """ class Solution(object): def isStrobogrammatic(self, num): """ :type num: str :rtype: bool """ left = 0 right = len(num) - 1 while left < right: if not((num[left] == num[right] and (num[left] == '1' or num[left] == '8' or num[left] == '0')) or (num[left] == '6' and num[right] == '9') or (num[left] == '9' and num[right] == '6')): return False left += 1 right -= 1 if left == right: return (num[left] == '1' or num[left] == '8' or num[left] == '0') return True
6d4017f176748cc0fe40d5e66ad19278d30da333
777aker/Algorithms-class
/Kelley-Kelley-PS7b-Q2.py
2,175
3.75
4
import numpy as np # i. def parti(n): # creates a list and populates it with values # 1 through n and then randomizes it data = [] for i in range(n): data.append(i+1) np.random.shuffle(data) return data # ii. def partii(data): # counts the number of flips in n^2 time flips = 0 for i in range(len(data)-1): for j in range(i+1, len(data)): if data[i] > data[j]: flips += 1 return flips # iii. def partiii(data): # if there is only 1 or less elements then return if len(data) > 1: # this splits the data into two subarrays mid = len(data)//2 left = data[:mid] right = data[mid:] # add to the number of flips the flips counted # by the call on the left subarray and the right subarray # and call recursively on the left and right halves of the array flips = partiii(left) flips += partiii(right) # so for everything in the left half, # if there is anything greater in the right half # then add to the count of flips for i in range(len(left)): for j in range(len(right)): if left[i] > right[j]: flips += 1 # return the number of flips return flips # returns 0 if there is 1 or 0 elements since it needs # a return and there are 0 flips for a single element return 0 # a tester method for easily plugging in # a size and running all the functions def tester(n): # making the data using part i data = parti(n) # printed the data to make sure correct # amount of flips was being counted # but thats a lot for 2^12 so no more # print(data) print("Number of flips counted by n^2 runtime: ", partii(data)) print("Number of flips counted by nlogn runtime: ", partiii(data)) # iv. # this for loop just runs the tester program for # 2^1 through 2^12 for i in range(1,13): size = 2**i print("------------------------------------------------------") print("For size: ", size) tester(size)
edb927e5bc493b144e8ea7c7acaa9a2f4edee5ef
ruszmate33/CS50x-C-and-Python-code
/readability/readability.py
2,234
4.0625
4
# import get_string from cs50 package from cs50 import get_string def main(): # prompt the user for a of text text = get_string("Text: ") # calculate cli value with helper functions cli = calcCLI(countNumLetters(text), countNumWords(text), countSentences(text)) # from 1 to 16: output "Grade X" where X is the grade level computed by the Coleman-Liau formula, rounded to the nearest integer if (cli >= 1 and cli <= 16): print("Grade", cli) # 16 or higher, output "Grade 16+" elif (cli > 16): print("Grade 16+") # If the index number is less than 1, your program should output "Before Grade 1" elif (cli < 1): print("Before Grade 1") # count the number of letters in the text def countNumLetters(text): numLetters = 0 for letter in text: # calculate ascii code only once ascii = ord(letter) # Letters can be any uppercase or lowercase alphabetic characters, but shouldn’t include any punctuation, digits, or other symbols if ((ascii >= 65 and ascii <= 90) or (ascii >= 97 and ascii <= 122)): numLetters += 1 return numLetters # count the number of words in the text def countNumWords(text): numSpaces = 0 for letter in text: # calculate ascii code only once ascii = ord(letter) # words separated by a space if (ascii == 32): numSpaces += 1 # characters separated by spaces should count as a word return numSpaces + 1 # count the number of sentences in the text def countSentences(text): numSentences = 0 for letter in text: # calculate ascii only once ascii = ord(letter) # sequence of characters that ends with a . or a ! or a ? a sentence if (ascii == 46 or ascii == 63 or ascii == 33): numSentences += 1 return numSentences # Coleman-Liau formula, rounded to the nearest integer def calcCLI(letters, words, sentences): # letters and senstences PER 100 words in text l = 100 * float(letters) / float(words) s = 100 * float(sentences) / float(words) index = round(0.0588 * l - 0.296 * s - 15.8) return index # call main function after defining helpers main()
656622027641ecd30c468688f272e00d4e471b72
hvestamila/Python-Orion-basic-
/homeworks/oop_1/hw4_theptinh_oop/school.py
388
3.609375
4
# 5. Create a new class School with get_school_id and number_of_students instance attributes class School: def __init__(self, school_id, number_of_students): self.school_id = school_id self.number_of_students = number_of_students def get_school_id(self): return self.school_id def get_number_of_students(self): return self.number_of_students
32af45a6b15adbe529a2e38a5b6d2a7375552cd7
lestersigauke/assignment1
/DNA_seq_reverse.py
213
4.21875
4
string = raw_input("Please enter your DNA sequence: ") stringlist = [] for i in range(0,(len(string))): stringlist.append(string[i]) stringlist.reverse() print "The reversed DNA sequence is ", stringlist
af69661f0ded6b3657eaeb4862dc742b43f1f79a
Sanjay-Leo/cracking-the-coding-interview
/3. stacks-queues/1. 1-array-3-stacks.py
1,241
3.90625
4
class ThreeStacks: def __init__(self): self.stacks = [] self.top1 = 0 self.top2 = 0 def push(self, stack_id, value): if stack_id == 1: self.stacks.insert(self.top1, value) self.top1 += 1 self.top2 += 1 elif stack_id == 2: self.stacks.insert(self.top2, value) self.top2 += 1 else: # stack_id = 3 self.stacks.append(value) return self def pop(self, stack_id): if stack_id == 1: return_value = self.stacks[self.top1 - 1] del self.stacks[self.top1 - 1] self.top1 -= 1 self.top2 -= 1 return return_value elif stack_id == 2: return_value = self.stacks[self.top2 - 1] del self.stacks[self.top2 - 1] self.top2 -= 1 return return_value else: # stack_id = 3 return self.stacks.pop() def __repr__(self): return str(self.stacks) if __name__ == '__main__': stacks = ThreeStacks() stacks.push(1, 0).push(2, 1).push(3, 2).push(1, 4).push(2, 5).push(3, 6) print(stacks) stacks.pop(1) stacks.pop(2) stacks.pop(3) print(stacks)
db2a8580b84796317728e54597aaecdd10aabeb8
chbauman/MasterThesis
/BatchRL/util/share_data.py
5,687
3.5
4
"""Module for sharing data via Google Drive. Based on the `pydrive` library. It can be pretty slow though, especially if you want to upload multiple files. Therefore you should prefer zipping multiple files and then only uploading the zip file, as does :func:`util.share_data.upload_folder_zipped`. If you just cloned from Github, you will need to setup the Google Drive API and create a `settings.yaml` file in the `BatchRL` folder for the authentication. """ import os import shutil import zipfile from util.util import TEMP_DIR, EULER if not EULER: from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from pydrive.files import GoogleDriveFile else: GoogleAuth = None GoogleDrive = None GoogleDriveFile = None FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" def g_drive_login() -> GoogleDrive: """Login to Google Drive and create and return drive object.""" g_login = GoogleAuth() g_login.LocalWebserverAuth() drive = GoogleDrive(g_login) print("Authentication successful") return drive def upload_folder_zipped(f_path, out_file_name: str = None, remove_existing: bool = False): """Uploads the content of the folder `f_path` to Google Drive. If `out_file_name` is specified, this will be the name of the uploaded file, otherwise the name of the folder will be used. If `remove_existing` is True, existing files with the same name will be removed. """ f_name = os.path.basename(f_path) if out_file_name is None: out_file_name = f_name out_path = os.path.join(TEMP_DIR, out_file_name) shutil.make_archive(out_path, 'zip', f_path) file_zip_path = out_file_name + ".zip" drive = None if remove_existing: f_list, drive = get_root_files() found = [f for f in f_list if f["title"] == file_zip_path] for f in found: f.Delete() upload_file(out_path + ".zip", drive=drive) def download_and_extract_zipped_folder(base_name: str, extract_dir: str, remove_old_files: bool = False): f_name = base_name + ".zip" # Find file on Drive f_list, drive = get_root_files() found = [f for f in f_list if f["title"] == f_name] f = None if len(found) > 1: print("Found multiple files, choosing newest.") sorted_files = sorted(found, key=lambda f: f["modifiedDate"]) f = sorted_files[-1] if remove_old_files: for old_f in sorted_files[:-1]: old_f.Delete() elif len(found) == 0: raise FileNotFoundError(f"No such file found: {f_name}") # Download to Temp folder out_temp_path = os.path.join(TEMP_DIR, f_name) f.GetContentFile(out_temp_path) # Unzip into folder with zipfile.ZipFile(out_temp_path, "r") as zip_ref: zip_ref.extractall(extract_dir) def get_root_files(): drive = g_drive_login() # Auto-iterate through all files in the root folder. file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() return file_list, drive def _rec_list(parent_dir: GoogleDriveFile, drive: GoogleDrive, lvl: int = 0): par_id = parent_dir["id"] ind = " " * 4 * lvl if parent_dir["mimeType"] == FOLDER_MIME_TYPE: # Found folder, recursively iterate over children. print(f"{ind}Folder: {parent_dir['title']}") file_list = drive.ListFile({'q': f"'{par_id}' in parents and trashed=false"}).GetList() for f in file_list: _rec_list(f, drive, lvl + 1) else: # Found file print(f"{ind}File: {parent_dir['title']}") def list_files_recursively() -> None: """Lists the whole content of your Google Drive recursively. This is extremely slow!""" file_list, drive = get_root_files() # Iterate over all found files. for file1 in file_list: _rec_list(parent_dir=file1, drive=drive) def upload_file(file_path, folder: str = None, drive=None): """Uploads a file to Google Drive. If `folder` is not None, a folder with that name will be created and the file will be put into it. """ if drive is None: drive = g_drive_login() if folder is not None: assert type(folder) == str # Create folder. folder_metadata = { 'title': folder, # The mimetype defines this new file as a folder, so don't change this. 'mimeType': FOLDER_MIME_TYPE, } folder = drive.CreateFile(folder_metadata) folder.Upload() print("Uploaded Folder.") # Create file on drive. fn = os.path.basename(file_path) if folder is None: f = drive.CreateFile({'title': fn}) else: assert isinstance(folder, GoogleDriveFile) folder_id = folder["id"] f = drive.CreateFile({"title": fn, "parents": [{"kind": "drive#fileLink", "id": folder_id}]}) # Set and upload content. f.SetContentFile(file_path) f.Upload() print(f"The file: {file_path} has been uploaded") def test_file_upload(): """This is slow and requires user interaction.""" TEST_DATA_DIR = "./tests/data" local_test_file = os.path.join(TEST_DATA_DIR, "test_upload_file.txt") upload_file(local_test_file, folder="test") def test_folder_zip(): """This is slow and requires user interaction.""" TEST_DATA_DIR = "./tests/data" local_test_file = os.path.join(TEST_DATA_DIR, "TestUploadFolder") upload_folder_zipped(local_test_file) download_and_extract_zipped_folder("TestUploadFolder", local_test_file, remove_old_files=True)
b6fe2ff40448126fe14e9eab33ad426508517d30
EL-S/FactorisationObscured
/fast_factorisation.py
554
3.625
4
from math import * t = int(input("number: ")) z = t**(1/2) p = z%1 f = [] e = 3 s = 2 if t%2 == 0: e = 2 s = 1 if p != 0: y = floor(z) else: print("perfect square") y = int(z) + 1 q = int(t/2) + 1 print("1","x",t) for j in range(e,y,s): d = (t/j); if (t%j) != 0: continue for k in range(e,q,s): if j*k == t: print(j,"x",k) h = [j,k] f.append(h) break if not f: f.append([1,t]) print("prime") else: f.append([1,t]) print(f) print("finished")
4468ce49afa3e553304bbf70729f377d4aef4c6f
aakash2602/InterviewBit
/binary search/rotatedArrayMin.py
739
3.53125
4
class Solution: # @param A : tuple of integers # @return an integer def findMin(self, A): start = 0 end = len(A) - 1 while start <= end: mid = int((start + end)/2) # print (mid) left_value = A[mid-1] if mid > 0 else A[mid] - 1 right_value = A[mid+1] if mid < len(A) - 1 else A[mid] + 1 if left_value > A[mid] and A[mid] < right_value: return A[mid] elif A[mid] >= A[0]: start = mid + 1 elif A[mid] <= A[len(A)-1]: end = mid - 1 else: return A[0] return A[0] if __name__ == "__main__": sol = Solution() print (sol.findMin([1]))
e7056a5a71afcf07e024a5030e87b667613502f4
a-gon/problem_solutions
/trees/isUnivalTree.py
302
3.671875
4
from TreeNode import TreeNode def isUnivalTree(root: TreeNode) -> bool: return recurse(root, root.val) def recurse(root, val): if not root: return True if root.val != val: return False else: return recurse(root.left, root.val) and recurse(root.right, root.val)
5b1d46a1c995ea53802f068007287ce76ff067d6
yonaxl/CS50
/mario.py
245
4.03125
4
n = 1 while n < 8: print("Please input a height of 8 or more... type numbers only please...") n = int(input("Height : ")) for i in range(n): nn = i + 1 print((" "*(n-nn)) + ("#"*nn) + " " + ("#"*nn) + (" "*(n-nn)) )
c0d4d000cd882c5e1167fc128329ef40cac4b9cc
nickpetzold/python-mega-course
/beyond-the-basics/while_loop.py
67
3.515625
4
x = 0 while x < 100: print(f'{x} is less than 100') x += 1