blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
83e6b633fd2211936992e151d7eecb8a352a837a
yavaralikhan/proj
/3Feb B.py
908
3.65625
4
class Order: id = 1 def __init__(self, name, address, price): self.oid = Order.id self.name = name self.address = address self.price = price Order.id += 1 def showOrderDetails(self): print("{}, {}, {}, {}".format(self.oid, self.name, self.address, self.price)) def toCSV(self): return "{},{},{},{}\n".format(self.oid, self.name, self.address, self.price) def saveOrder(self): file = open("orders.csv", "a") orderData = self.toCSV() file.write(orderData) file.close() print(">> Order[{}] Saved :)".format(self.oid)) order1 = Order("Yavar", " Malerkotla", 8560) order2 = Order("Gagan", "Ludhiana", 9631) order3 = Order("Ahmed", "Chandigarh ", 7856) order1.showOrderDetails() order2.showOrderDetails() order3.showOrderDetails() order1.saveOrder() order2.saveOrder() order3.saveOrder()
edc15ed0464ab17627e99b30c4c9edf5a5fa23b3
SerpentChris/PyShapes
/shapes.py
7,103
4.28125
4
import tkinter import math from math import sin, cos from random import randrange as r from typing import List, Tuple Vec3D = Tuple[float, float, float] class Shape3D: """A class for representing 3D shapes. The x-axis goes through the screen, with the positive end infront of the screen and the negative end behind. The y-axis is horizontal, with the negative end being the left side of the screen and the positive end on the right. The z-axis is vertical, the the negative end at the bottom of the screen and the positive end at the top. """ def __init__(self, points: List[float]): assert len(points)%3 == 0 self.points = points def rotate(self, angle: float, direction: Vec3D, point: Vec3D): """Rotates the points of the Shape around the axis given by the point and direction.""" #http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ points = self.points a = point[0] b = point[1] c = point[2] u = direction[0] v = direction[1] w = direction[2] s = sin(angle) c0 = cos(angle) c1 = 1 - c0 u2 = u*u v2 = v*v w2 = w*w x1 = c1*(a*(v2 + w2) - u*(b*v + c*w)) + s*(b*w - c*v) x2 = u*c1 y1 = c1*(b*(w2 + u2) - v*(c*w + a*u)) + s*(c*u - a*w) y2 = v*c1 z1 = c1*(c*(u2 + v2) - w*(a*u + b*v)) + s*(a*v - b*u) z2 = w*c1 for i in range(0, len(points), 3): x = points[i] y = points[i + 1] z = points[i + 2] dotp = u*x + v*y + w*z points[i] = x1 + x2*dotp + x*c0 + s*(v*z - w*y) points[i + 1] = y1 + y2*dotp + y*c0 + s*(w*x - u*z) points[i + 2] = z1 + z2*dotp + z*c0 + s*(u*y - v*x) def apply_perspective(self, camera_pos: Vec3D, viewer_pos: Vec3D) -> List[float]: """Creates an array of perspective projected (onto the y/z plane) points.""" #http://en.wikipedia.org/wiki/3D_projection#Perspective_projection points = self.points projected = (2*len(points)//3) * [0] ptr = 0 a, b, c = viewer_pos d, e, f = camera_pos for i in range(0, len(points), 3): x = points[i] - d y = points[i + 1] - e z = points[i + 2] - f projected[ptr] = b - a*y/x projected[ptr + 1] = c - a*z/x ptr += 2 return projected class Cube(Shape3D): def __init__(self, front_right_top: Vec3D, side_length: float): x, y, z = front_right_top xs, ys, zs = x - side_length, y - side_length, z - side_length super().__init__([ x, y, z, x, y, zs, x, ys, zs, x, ys, z, xs, ys, z, xs, ys, zs, xs, y, zs, xs, y, z]) self.colors = ['#%2X%2X%2X' % (r(256), r(256), r(256)) for i in range(6)] self.side_length = side_length def draw(self, camera: Vec3D, viewer: Vec3D, canvas: tkinter.Canvas, width: int, height: int) -> List[int]: points = self.points colors = self.colors hw = width//2 hh = height//2 a = camera[0] b = camera[1] c = camera[2] faces = [[0, 2, 4, 6], [0, 14, 8, 6], [0, 2, 12, 14], [4, 10, 8, 6], [2, 4, 10, 12], [10, 12, 14, 8]] face_indices = [0, 1, 2, 3, 4, 5] distances = [0]*8 distances[0] = ((a - points[0])**2 + (b - points[1])**2 + (c - points[2])**2)**0.5 distances[1] = ((a - points[3])**2 + (b - points[4])**2 + (c - points[5])**2)**0.5 distances[2] = ((a - points[6])**2 + (b - points[7])**2 + (c - points[8])**2)**0.5 distances[3] = ((a - points[9])**2 + (b - points[10])**2 + (c - points[11])**2)**0.5 distances[4] = ((a - points[12])**2 + (b - points[13])**2 + (c - points[14])**2)**0.5 distances[5] = ((a - points[15])**2 + (b - points[16])**2 + (c - points[17])**2)**0.5 distances[6] = ((a - points[18])**2 + (b - points[19])**2 + (c - points[20])**2)**0.5 distances[7] = ((a - points[21])**2 + (b - points[22])**2 + (c - points[23])**2)**0.5 def key(i): return (distances[faces[i][0]//2] + distances[faces[i][1]//2] + distances[faces[i][2]//2] + distances[faces[i][3]//2])/4 # sort the faces of the cube by the average distance of their vertices from the camera. # those furthest from the camera are drawn first, which is why reverse=True. face_indices.sort(key=key, reverse=True) ppoints = self.apply_perspective(camera, viewer) polygons = [0]*6 for i in face_indices: color = colors[i] face = faces[i] polygons[i] = canvas.create_polygon(hw + ppoints[face[0]], hh - ppoints[face[0]+1], hw + ppoints[face[1]], hh - ppoints[face[1]+1], hw + ppoints[face[2]], hh - ppoints[face[2]+1], hw + ppoints[face[3]], hh - ppoints[face[3]+1], fill=color) return polygons class Animation: def __init__(self, width: int = 1280, height: int = 720, max_fps: float = 60.0, rotation_speed: float = 2*math.pi/3, camera: Vec3D = (500.0,0.0,0.0), viewer: Vec3D = (550.0,0.0,0.0), axis: Vec3D = (3**0.5/3,3**0.5/3,3**0.5/3), point: Vec3D = (0.0,0.0,0.0)): self.frame_delay = int(1000/max_fps) # milliseconds between frames self.angle_delta = rotation_speed*self.frame_delay/1000 self.camera = camera self.viewer = viewer self.axis = axis self.point = point self.width = width self.height = height self.master = tkinter.Tk() self.canvas = tkinter.Canvas(self.master, width=width, height=height) self.canvas.pack() self.shapes = [] # type: List[Shape3D] self.master.after(0, self._animate) def add_shape(self, shape: Shape3D): self.shapes.append(shape) def _animate(self): angle = self.angle_delta direction = self.axis point = self.point canvas = self.canvas camera = self.camera viewer = self.viewer width = self.width height = self.height canvas.delete('all') for shape in self.shapes: shape.rotate(angle, direction, point) shape.draw(camera, viewer, canvas, width, height) self.master.update_idletasks() self.master.after(self.frame_delay, self._animate) def run(self): self.master.mainloop() if __name__ == '__main__': cube = Cube((100.0,100.0,100.0), 200.0) animation = Animation() animation.add_shape(cube) animation.run()
477181b2f07c2268cd5ec9197a07eeb1db26c857
AroopN/Design-2
/Problem2.py
1,690
3.828125
4
# // Time Complexity: O(1) for all operations # // Space Complexity:O(n) as it is directly proportional to the size of input # // Did this code successfully run on Leetcode: Yes # // Any problem you faced while coding this: No # Used separate chaining and double hashing using 2 lists to attain O(1) in operations such as # add remove and contain. class MyHashSet: def __init__(self): """ Initialize your data structure here. """ self.bucket = 1000 self.bucketItems = 1000 self.hashset = [None for _ in range(self.bucket)] def bucketIndex(self, key): return key % self.bucket def bucketItemIndex(self, key): return key//self.bucketItems def add(self, key: int) -> None: index1 = self.bucketIndex(key) index2 = self.bucketItemIndex(key) if not self.hashset[index1]: self.hashset[index1] = [False for _ in range(self.bucketItems)] self.hashset[index1][index2] = True def remove(self, key: int) -> None: index1 = self.bucketIndex(key) index2 = self.bucketItemIndex(key) if not self.hashset[index1]: return self.hashset[index1][index2] = False def contains(self, key: int) -> bool: """ Returns true if this set contains the specified element """ index1 = self.bucketIndex(key) index2 = self.bucketItemIndex(key) if not self.hashset[index1]: return False return self.hashset[index1][index2] # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)
9359605ee32c25c7221cacd1b5a6f1f801e29a34
jm1224k/algorithm_since2020
/algorithm/programmers/jj_디스크컨트롤러.py
567
3.5
4
import heapq def solution(jobs): answer = 0 start,now = -1,0 wait = [] cnt = 0 n = len(jobs) while cnt<n: for job in jobs: if start < job[0] <= now: #작업 중 answer +=(now-job[0]) # 대기시간 더하기 heapq.heappush(wait,job[1]) if len(wait)>0: answer += len(wait)*wait[0] # 대기시간 더하기 start =now now+=heapq.heappop(wait) # 작업이 끝난 시간 갱신 cnt+=1 else: now+=1 return answer//n
52c90d6620ead87e7525b2ad6e1f186133cfc26f
SirishaRella/CSEE5590_Python_DL
/LAB's/LAB-1/list_operation.py
611
4.1875
4
p = input("Enter list of students in python ") list_p = p.split() w = input("Enter list of students in web ") list_w = w.split() set_p = set(list_p) set_w = set(list_w) print("Students in Python class", list_p) print("Students in Web class", list_w) #set operation intersection to find the common records common = set_p & set_w print("Students common in both classes", list(common)) # perfrom union operation to get all the records and remove the records which are common using the difference (set) union_p_w = set_p | set_w print("Students not common in both the classes ", list(union_p_w.difference(common)))
44ffceab7ee9f9ad1660f0286df783d06657c090
guerrerocarlos/epdtext
/screens/sensors.py
1,184
3.609375
4
"""Sensors screen""" from libs import system from screens import AbstractScreen class Screen(AbstractScreen): """ This class provides the screen methods needed by epdtext """ system = system.get_system() def handle_btn_press(self, button_number: int = 1): """ This method receives the button presses """ # Buttons 0 and 3 are used to switch screens if button_number == 1: pass elif button_number == 2: pass def reload(self): """ This method should draw the contents of the screen to self.image """ self.blank() self.draw_titlebar("Sensors") text = "Temperature:\t" + str(round(self.system.temperature)) + '°\n' text += "Voltage: \t" + str(self.system.voltage) self.text(text, font_size=16, position=(5, 30)) def iterate_loop(self): """ This method is optional, and will be run once per cycle """ # Do whatever you need to do, but try to make sure it doesn't take too long # This line is very important, it keeps the auto reload working super().iterate_loop()
11b9dc8365ae11cb17fdb2088b5e2c6c4a5c5c08
noelfonseca/Test_project_1
/archive/collatz.py
176
3.984375
4
number = int(input()) while number > 1: if number % 2 == 0: number = int(number) // 2 print(number) elif number % 2 == 1: number = 3 * int(number) + 1 print(number)
d7fb987dc00906824701b93beb702fc4c054c3f1
cpiggott/python-class
/day1/Complete/ex2.py
359
3.71875
4
# A comment, this is so you can read your program later. # Anthing after the # sign is ignored by python. print "I could have code like this" # and the comment after is ignored # You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print "This will run." print "Like my refridgerator..." print "My favorite #42"
da33346c91c26e6479555c0dd2ced1d7bf1e49ee
425776024/Learn
/pythonlearn/Class/Patterns/2.1.Structural.Adapter.py
1,536
3.734375
4
# -*- encoding: utf-8 -*- class Computer(object): def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): """ call by client code """ return 'execute a program' class Synthesizer(object): def __init__(self, name): self.name = name def __str__(self): return 'the {} synthesizer'.format(self.name) def play(self): return 'is playing an electroinc song' class Human(object): def __init__(self, name): self.name = name def __str__(self): return 'the {} human'.format(self.name) def speak(self): return 'says hello' class Adapter(object): def __init__(self, obj, adapted_methods): """ 不使用继承,使用__dict__属性实现适配器模式 """ self.obj = obj self.__dict__.update(adapted_methods) def __str__(self): return str(self.obj) # 适配器使用示例 def main(): objs = [Computer('Asus')] synth = Synthesizer('moog') objs.append(Adapter(synth, dict(execute=synth.play))) human = Human('Wnn') objs.append(Adapter(human, dict(execute=human.speak))) for o in objs: # 用统一的execute适配不同对象的方法,这样在无需修改源对象的情况下就实现了不同对象方法的适配 print('{} {}'.format(str(o), o.execute())) if __name__ == "__main__": main()
3cf5aed327c497094640ce2c2e6d88d3bee755dd
vedantbarbhaya/Competitive-programming-prob-codes
/max_product_subarray.py
1,598
4.40625
4
""" Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray """ """ APPROACH: As the subarrays have to be continuous, the intuition here is that when we traverse the array, at any given position, we have to maintain a max and min number where max is the max product of the elements before the current position and min is the minimum product of the elements before the current position. If the current position is a negative number, and min product is also a negative number, there are high chances that their product will be a very large positive number so we maintain min product. Now the output can also be a single number, meaning a single element of the array so we need to take the max of ele at curr pos, (ele at curr pos * max_prod), and (ele at curr pos * min_prod). """ def maxProduct(l1): r = l1[0] print("intially r = " + str(r)) imax = r imin = r for i in range(1,len(l1)): print("imax = " + str(imax)) print("imin = " + str(imin)) if(l1[i] < 0): imax,imin = imin,imax imax = max(l1[i], imax * l1[i]) imin = min(l1[i], imin * l1[i]) print("after upd imax = " + str(imax)) print("after upd imin = " + str(imin)) r = max(r, imax); print("global r = " + str(r)) print(r)
5eff6552b51562455ae920fafd685e76fa1b9245
up1/course-basic-python
/demo/loop_for.py
255
4.125
4
datas = range(0, 9) print(datas) print(list(datas)) for data in datas: print(data) for letter in "Somkiat": print(letter) names = ["Tom", "Mike", "Ko"] for name in names: print(name) for index in range(len(names)): print(names[index])
eee87f95efc91fcbe969bbac6cea1b4da7c05452
BeatsBassBoom/LP3THW
/ex38-DoingThingsToLists.py
944
3.875
4
ten_things = "Apples Oranges Crows Telephone Light Sugar" print("Wait there are not 10 things in that list. Let's fix that.") # Splt the list ten things on a single space. stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: # Pop one item off the more_stuff list from the last value next_one = more_stuff.pop() print("Adding: ", next_one) # Append next_one to the end of stuff. stuff.append(next_one) # prints the length of stuff one item at a time through the list. print(f"There are {len(stuff)} items now.") print("There we go: ", stuff) print("Let's do some things with stuff.") print(stuff[1]) print(stuff[-1]) # whoa! fancy print(stuff.pop()) # Join the list into one line seperating each item by a space. print(' '.join(stuff)) # what? cool! # Takes elements 3 to 4 not 5. print('#'.join(stuff[3:5])) # super stellar!
2dd5761a1f160ce07f4a257c887e16abd5e9c8ae
lakshmisravyasaripella/20A91A05I3_Sravya_CSEC
/while3.py
246
3.78125
4
i=int(input("Enter start value")) n=int(input("Enter end value")) s=int(input("Enter step count")) while i<=n: print(i,end="\t") i=i+s ''' Output: Enter start value2 Enter end value10 Enter step count2 2 4 6 8 10 '''
9155a5eced6ff332beea717427d0984d03b88115
mainka1f/PythonUtilities
/Yaml loads and dumps/codes/yaml_dump_variable_is_list.py
456
3.609375
4
#!/usr/bin/python # filename: yaml_dump_variable_is_list.py import yaml # -------- example: lists and yaml ---------- # 'lists' in Python look like var = ['line 1','line 2','line 3','last line'] # what happens when we write the data using YAML? print '\nExample 1: LISTS AND YAML' # what happens when we dump the data using YAML? print '\n\nWRITING (yaml.dump) ...' print '\nyaml.dump(var) =\n\n', yaml.dump(var) print '' print '==========' print ''
15d9421e5347bff15014a590f89ad96708dcf298
manmohitgrewal1/CS50X
/pset6:Python/readability/readability.py
511
3.9375
4
import math # Take user input text= input("Text: ") letters =0 words =0 sentences= 0 for run in text: # print(run) if run == " ": words+=1 elif run == "!" or run == "?" or run == ".": sentences+=1 else: letters+=1 words+=1 L= (letters / words)*100 S= (sentences / words)*100 index= 0.0588 * L - 0.296 * S - 15.8; grade= math.floor(index) if grade >16: print("Grade 16+\n") if grade<1: print("Before Grade 1\n") else: print("Grade {}".format(grade))
81412d08e1bf6cc7d1578c99f4dbd598289c64f3
leungcc/pythonLxf
/FunctionalProgramming/reduce/str2Int.py
656
3.8125
4
from functools import reduce from collections import Iterator from collections import Iterable DIGITS = { '0':0, '1':1, '2':2, '3':3,'4':4, '5':5, '6':6, '7':7, '8':8, '9':9 } def str2int(s): def fn(x, y): return x*10+y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s)) def char2num(s): return DIGITS[s] print('map函数返回', map(char2num, '12345')) print('list(map函数返回)', list(map(char2num, '12345'))) print('isinstance(map(char2num, "12345"), (Iterable))', isinstance(map(char2num, '12345'), (Iterable))) print('isinstance(map(char2num, "12345"), (Iterator))', isinstance(map(char2num, '12345'), (Iterator)))
faa5fe323c6af2e7032b54743ebec974f58673b8
MidnightCoke/come103-hku-lab-2019
/Laboratory 4 Programs/calories_burned.py
183
3.640625
4
print("Minutes\t Calories Burned") print("---------------------------") TREADMILL_CAL = 4.2 for min in range(5, 61, 5): print(min, "\t\t", format(min*TREADMILL_CAL, '.2f'))
59b53ac89244ce82dc9cc2f392631bc8790d1dc9
VineetAhujaX/Team-Automated-Chatbot
/programming.py
582
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 01:42:46 2021 @author: USER """ from googlesearch import search # to search #query = "Which programming language to begin with" #for j in search(query, tld="co.in", num=10, stop=10, pause=2): # print(j) def TopResult(query): result="Here are the best solutions for your query: \n\n" counter=1 for j in search(query, tld="co.in", num=3, stop=3, pause=2): result+=str(counter) result+=") " result+=j result+='\n\n' counter+=1 return result
220eac18503a3d9ff5542e0a716bd89e9eab8dfa
chydrio/PythonExamples
/dict.py
505
4.28125
4
ages = { "Peter": 10, "Isabel": 11, "Anna": 9, "Thomas": 10, "Bob": 10, "Joseph": 11, "Maria": 12, "Gabriel": 10, } for name, age in ages.items(): print (name, age) students = { "Peter": {"age": 10, "address": "Lisbon"}, "Isabel": {"age": 11, "address": "Sesimbra"}, "Anna": {"age": 9, "address": "Lisbon"}, } #nested dict for p_id, p_info in students.items(): print("\nPerson Name:", p_id) for key in p_info: print(key + ':', p_info[key])
ba8393089e445328db3c3c6bcc46d1b4da056547
milesaturpin/CoopsWhoCode
/Lunch Lottos/lunchlottos.py
1,682
3.59375
4
import random import os.path while True: prompt = raw_input("Is this an official run? That is, should I mark off the pairs you are about to generate so they are not generated again? Type 'y' for yes or 'n' for no:\n") if prompt == 'y': official_run = True f = open('past_partners.txt','a') f.write('\n') break elif prompt == 'n': official_run = False break else: print "Just type 'y' or 'n'!" f = open('past_partners.txt','r') past_pairs = list() for line in f: past_pair = set(line.split(',')) past_pairs.append(past_pair) f.close() def checkOff(group): f = open('past_partners.txt','a') group = group.split(',') group = [person.strip() for person in group] for i in range(len(group) - 1): f.write(group[i] + ",") f.write(group[-1] + "\n") f.close() if os.path.isfile('names.txt') and os.access('names.txt', os.R_OK): f = open('names.txt','r') names = [line[:-1] for line in f if line[0] != "*"] if len(names) < 2: ValueError("Here's the thing: there's not enough people in Lunch Lottos") while len(names) != 0: if len(names) == 3: trio = random.sample(names, 3) if set(trio) not in past_pairs: names.remove(trio[0]) names.remove(trio[1]) names.remove(trio[2]) s = str(trio[0] + ",", trio[1] + ", " + trio[2]) if official_run: checkOff(s) print s break pair = random.sample(names, 2) if set(pair) not in past_pairs: names.remove(pair[0]) names.remove(pair[1]) s = str(pair[0] + ", " + pair[1]) if official_run: checkOff(s) print s else: Exception("Here's the thing: File doesn't exist. Make a file names.txt and add all the names of people in lunch lottos, formatted one name per line.")
6b4ff64cad9858dd0afd9e69fcaeb43aa35706ff
ngvinay/python-projects
/PythonAdvanced/src/ml/ml_utils.py
6,951
3.71875
4
import math import csv import random from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt ''' Load a CSV file ''' def load_csv(filename): lines = csv.reader(open(filename, "rb")) dataset = list(lines) return dataset ''' Convert string column to integer dataset and column position are inputs To convert multiple columns, it has to be called multiple times ''' def cat_str_column_to_int(dataset, column): class_values = [row[column] for row in dataset] unique = set(class_values) lookup = dict() for i, value in enumerate(unique): lookup[value] = i #print 'lookup:\n', lookup for row in dataset: row[column] = lookup[row[column]] #print 'dataset after looked up : \n', dataset return lookup, dataset ''' Convert all the columns to float Use str_column_to_int(dataset, column) method to convert any categorical variable to numerical before applying this method ''' def str_columns_to_float(dataset, col_start=0, col_end=999): #Following code will produce a dataset where the first col will start from specified col_start #for i in range(len(dataset)): # dataset[i] = [float(dataset[i][j]) for j in range(col_start, len(dataset[i]))] for i in range(len(dataset)): dataset[i] = [float(x) for x in dataset[i]] return dataset ''' Find the min and max values for each column ''' def dataset_minmax(dataset): print 'Find min and max for each column in dataset' minmax = list() for i in range(len(dataset[0])): col_values = [row[i] for row in dataset] value_min = min(col_values) value_max = max(col_values) minmax.append([value_min, value_max]) return minmax ''' Rescale dataset columns to the range 0-1 Avoid devide by zero situation ''' def normalize_dataset(dataset, minmax): print 'Perform normalization\n' for row in dataset: for i in range(len(row)): if minmax[i][1] != 0: row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0]) return dataset ''' Rescale dataset columns to the range 0-1 Avoid devide by zero situation ''' def normalize_dataset_skip_last_col(dataset, minmax): print 'Perform normalization\n' for row in dataset: for i in range(len(row)-1): if minmax[i][1] != 0: row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0]) return dataset ''' Split Dataset into two sets - training and test - based on ratio given ''' def split_dataset(dataset, split_ratio): train_size = int(len(dataset) * split_ratio) train_set = [] test_set = list(dataset) while len(train_set) < train_size: index = random.randrange(len(test_set)) train_set.append(test_set.pop(index)) return train_set, test_set ''' Split a dataset into k folds ''' def cross_validation_split(dataset, n_folds): dataset_split = list() dataset_copy = list(dataset) fold_size = len(dataset) / n_folds for i in range(n_folds): fold = list() while len(fold) < fold_size: index = random.randrange(len(dataset_copy)) fold.append(dataset_copy.pop(index)) dataset_split.append(fold) return dataset_split ''' Group the records based on available classes in Y It will return a dict - key will be class values and value for this key will the records ''' def group_by_class(dataset): separated = {} for i in range(len(dataset)): vector = dataset[i] if (vector[-1] not in separated): separated[vector[-1]] = [] separated[vector[-1]].append(vector) return separated ''' Calculate mean of numbers in a vector ''' def mean(numbers): return sum(numbers)/float(len(numbers)) ''' Calculate Standard Deviation of numbers in a vector ''' def stdev(numbers): avg = mean(numbers) variance = sum([pow(x - avg,2) for x in numbers])/float(len(numbers) - 1) return math.sqrt(variance) ''' calculate the Euclidean distance between two vectors ''' def euclidean_distance(row1, row2): distance = 0.0 for i in range(len(row1)-1): distance += (row1[i] - row2[i]) ** 2 return math.sqrt(distance) ''' calculate the Euclidean distance between two vectors ''' def euclidean_distance_skip_last_col(row1, row2): distance = 0.0 for i in range(len(row1)-2): distance += (row1[i] - row2[i]) ** 2 return math.sqrt(distance) ''' Calculate accuracy percentage Input expected to be two vector - actual class and predicted class ''' def accuracy_metric(actual, predicted): correct = 0 for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / float(len(actual)) * 100.0 ''' Calculate a confusion matrix It will work for n dimention ''' def confusion_matrix(actual, predicted): #print 'actual : ', actual #print 'predicted : ', predicted unique = set(actual) matrix = [list() for x in range(len(unique))] for i in range(len(unique)): matrix[i] = [0 for x in range(len(unique))] lookup = dict() for i, value in enumerate(unique): lookup[value] = i #lookup[i] = value #print 'lookup : ', lookup for i in range(len(actual)): x = lookup[actual[i]] #print 'x : ', str(x) y = lookup[predicted[i]] matrix[x][y] += 1 return unique, matrix ''' pretty print a confusion matrix ''' def print_confusion_matrix(unique, matrix): print('(P)' + ' '.join(str(x) for x in unique)) print('(A)---') for i, x in enumerate(unique): print("%s| %s" % (x, ' '.join(str(x) for x in matrix[i]))) ''' Generate ROC Curve ''' def roc(actual, predicted): #print 'actual : ', actual #print 'predicted : ', predicted unique = set(actual) matrix = [list() for x in range(len(unique))] for i in range(len(unique)): matrix[i] = [0 for x in range(len(unique))] lookup = dict() #(1,2) #lookup[1]=0 #lookup[2]=1 for i, value in enumerate(unique): lookup[value] = i #lookup[i] = value #print 'lookup : ', lookup #(1,1,0,1,0,1) #len=6 #First iteration : x = lookup[actual[1]] #First iteration : x = lookup[actual[2]] # 1 2 # 1 # 2 for i in range(len(actual)): x = lookup[actual[i]] #print 'x : ', str(x) y = lookup[predicted[i]] matrix[x][y] += 1 return unique, matrix def generate_results(y_test, y_score): fpr, tpr, _ = roc_curve(y_test, y_score) roc_auc = auc(fpr, tpr) plt.figure() plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.05]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic curve') plt.show() print('AUC: %f' % roc_auc)
556d1c2e3de4ccbc4120dba528437ceaa3149d0f
mateusz713/Programowanie_w_GIS
/cw2_zad1_Mateusz_Migon.py
372
3.84375
4
''' Created on 22-10-2014 @author: Latino ''' def FizzBuzz(n): a=1 while a<n: if a%3==0 and a%5==0: print "Fizz Buzz" a+=1 elif a%5==0: print "Buzz" a+=1 elif a%3==0: print "Fizz" a+=1 else: print str(a) a+=1 FizzBuzz(20)
97157706e5055da0fb8b74d0d7be13d9847d61da
oktaran/LPTHW
/ex33.py
760
4.15625
4
i = 0 numbers = [] # while i < 6: # # print(f"At the top i is {i}") # numbers.append(i) # # i = i + 1 # print("Numbers now: ", numbers) # print(f"At the bottom i is {i}") # # def loop(number, incr): # i = 0 # num_lst = [] # # while i < number: # print(f"At the top i is {i}") # num_lst.append(i) # # i = i + incr # print("Numbers now: ", num_lst) # print(f"At the bottom i is {i}") # # loop(10, 2) def for_loop(number, incr): for i in range(number, incr): print(f"At the top i is {i}") numbers.append(i) print("Numbers now: ", numbers) print(f"At the bottom i is {i}") for_loop(0, 10) print("The numbers: ") for num in numbers: print(num)
a2f278e0bea5778989de1a5050c606f08a9a09f4
GhostSK11/pentagon
/Project Euler Problem 15.py
867
3.59375
4
""" Julius Pazitka Project Euler Problem 15 Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ import math as m # in this solution, we use a standard math library (We need this library, for working with mathematical formula) # as m # We use math as m to give a library a short alias while importing it. a = 20 # represent 20x20 grid result = m.factorial(2*a)//(m.factorial(a)**2) # formula print("There are", result, "routes in 20x20 grid.") """ To compute the solution, we use binomial distribution. We think, that is the easiest way.""" input("Press any key") # The result is 137846528820 # https://github.com/nayuki/Project-Euler-solutions/blob/master/Answers.txt (just for control)
2daaf7a66815b9268be2d14967f5c2b5f69a3d60
Suman-Dutta/Suman
/Python practice/problem_solve14.py
1,103
4
4
#The following iterative sequence is defined for the set of positive integers: #n → n/2 (n is even) #n → 3n + 1 (n is odd) #Using the rule above and starting with 13, we generate the following sequence: #13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 #It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. #Which starting number, under one million, produces the longest chain? num=[] longseq=0 count=0 i=2 num1=1000000 for i in range(2,1000000,1): while(num1>1): if num1==1: break elif num1%2==0: num1=num1/2 num.append(num1) count=count+1 else: num1=num1*3+1 num.append(num1) count=count+1 if(longseq<count): longseq=count else: print(longseq) for i in range(1,1000000,1): print('Enter longest chain= ',end='') print(num[i]) break num1-=1
4f44be8b93bdd613c4a6e7186c5a32ac9f6d1d83
fedeSantana/Cuadernos-Jupyter
/Asys/mathAnimation/mathAnimation.py
2,982
4.0625
4
""" Basado en: Matplotlib Animation Example author: Jake Vanderplas email: vanderplas@astro.washington.edu website: http://jakevdp.github.com license: BSD """ import matplotlib import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from matplotlib.widgets import Slider, Button, RadioButtons plt.style.use('dark_background') class Plot: def __init__(self, fig, ax): self.endPoint = 1000 self.currentFrame = 0 self.fig = fig self.ax = ax self.line, = ax.plot([], [], lw=2) self.point, = ax.plot([], [], color='xkcd:lightish blue', marker='o', linestyle='dashed') self.x = np.linspace(0, 10, self.endPoint) self.y = 2/3 * pow(np.e, (-1/2)*self.x) * np.cos((pow(3, 0.5)/2) * self.x) - (2/3) * pow(np.e, -2*self.x) self.animation = animation.FuncAnimation(self.fig, self.update,self.endPoint - self.currentFrame - 2, interval=10, repeat_delay=5000, repeat=False, blit=False) def set_value (self, frame=0): frame = int(frame) self.currentFrame = frame ## el valor del slider al de la animación print("entre") self.animation.event_source.stop() self.animation = animation.FuncAnimation(self.fig, self.update, self.endPoint - self.currentFrame - 2, interval=10, repeat_delay=5000, repeat=False, blit=False) def update(self, frame): frame = self.currentFrame self.line.set_data(self.x[0:frame], self.y[0:frame]) # Grafico linea desde 0 hasta frame self.point.set_data(self.x[frame],self.y[frame]) # Grafico punto en frame self.slider.eventson = False # Que no me reconozca más el evento del slider, para que así no entre en un bucle infinito de doble entrada. self.slider.set_val(frame) # actualizo la posición del slider al frame actual self.slider.eventson = True # Que los vuelva a reconocer self.currentFrame += 1 # Continuar hasta que termine o alguien toque el slider print("currentFrame", self.currentFrame) print("Despues", frame) return self.line, self.point def animateSlider(self): slider_ax = self.fig.add_axes((0.1, 0.025, 0.5, 0.04)) self.slider = Slider(slider_ax, label='Time', valmin=0, valmax=self.endPoint, valinit=0.0) self.slider.on_changed(self.set_value) ## listener, cuando cambie el slider plt.show() def save(self): self.animation.save('animation.gif', writer='imagemagick', fps=60) # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) ax.spines['left'].set_position(('data', 0)) ax.spines['bottom'].set_position(('data', 0)) plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) myPlot = Plot (fig, ax) myPlot.animateSlider() myPlot.save()
797ab148b5d8d36e312b6a2de67a6f8671b9a22b
Porrumentzio/python-ariketak
/eposta.py
391
3.703125
4
badu_abil=False badu_punt=False helbidea=input("Sartu zure e-posta helbidea: ") # for i in helbidea: # if(i=="@"): # badu_abil=True # if(i=="."): # badu_punt=True if "." in helbidea: badu_abil=True if "@" in helbidea: badu_punt=True if badu_abil and badu_punt: print("Ados, aurrera egin dezakezu.") else: print("Hori ez da e-posta helbide bat.")
132c325e3285a43268ed3e96cd73bb14dbc881bf
mohitsinha/dsa
/queue/sliding_window_max.py
468
3.5625
4
# https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/ from collections import deque arr, k = [8, 5, 10, 7, 9, 4, 15, 12, 90, 13], 4 q = deque() n = len(arr) for i in range(k): while q and arr[i] >= arr[q[-1]]: q.pop() q.append(i) for i in range(k,n): print(arr[q[0]]) while q and q[0]<=i-k: q.popleft() while q and arr[i]>=arr[q[-1]]: q.pop() q.append(i) print(arr[q[0]])
916321d3972764999c517820de5cae078b43c367
YuZhangIsCoding/Algorithms_python
/Classic_problems/linkedList.py
23,395
4.0625
4
import operator class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): ans = [] while self: ans.append(str(self.val)) self = self.next return 'SL-list ['+', '.join(ans)+']' def cast_list(mylist): ''' This is a function to convert a list into single linked lists. ''' if not mylist: return ListNode(None) ans = temp = ListNode(mylist[0]) for item in mylist[1:]: temp.next = ListNode(item) temp = temp.next return ans class sol(object): def addTwoNumbers(self, l1, l2): ''' Given two none-empty linked lists representing 2 non-negative integers. Add the two numbers and return it as a linked list (2, 4, 3)+(4, 6, 4) = (6, 0, 8) 122 ms, 85.33% Follow up the previous question. What if the numbers are stored in non-reverse order? Probably need to go over the whole lists first to determine the digits. (2, 4, 3)+(4, 6, 4) = (7, 0, 7) ''' up = 0 ans = temp = ListNode(0) while l1 or l2 or up: if l1: v1 = l1.val l1 = l1.next else: v1 = 0 if l2: v2 = l2.val l2 = l2.next else: v2 = 0 temp.next = ListNode((v1+v2+up)%10) temp = temp.next up = (v1+v2+up)/10 return ans.next def addTwoNumbers_2(self, l1, l2): ''' Much more concise one. ''' carry = 0 addend = l1, l2 dummy = temp = ListNode(0) while addend or carry: carry += sum(item.val for item in addend) addend = [item.next for item in addend if item.next] ## This line here is quite interesting does equal to ## temp.next = ListNode(); temp = temp.next temp.next = temp = ListNode(carry%10) carry = carry/10 return dummy.next ####### remove Nth Node From End of list ########## def removeNthFromEnd(self, head, n): ''' Given a linked list, remove the nth node from the list and return its head 46ms, 79% 42ms, 95.34% ''' ans = head p1 = p2 = 0 while head: p2 += 1 if p2-p1 == n: if p1 == 1: pre = ans track = pre.next elif p1 > 1: pre = track track = track.next p1 += 1 head = head.next if p1 == 1: return ans.next pre.next = pre.next.next return ans def removeNthFromEnd_2(self, head, n): ''' Instead of judging whether the element to be removed is the first node. We could first add a dummy node to the head of the list. This reduces the corner cases. 46 ms, 79% ''' dummy = ListNode(0) dummy.next = head p1 = p2 = 0 pre = dummy while head: p2 += 1 if p2-p1 == n: if p1 > 0: pre = pre.next p1 += 1 head = head.next pre.next = pre.next.next return dummy.next def removeNthFromEnd_3(self, head, n): ''' Rewrite the previous one using 2 loop, could save some variables. 42 ms, 95.34% ''' dummy = ListNode(0) dummy.next = head pre = dummy for count in range(n): head = head.next while head: pre = pre.next head = head.next pre.next = pre.next.next return dummy.next ###### Merge two sorted linked lists ######## def mergeTwoLists(self, l1, l2): ''' 52 ms, 75.55% ''' dummy = temp = ListNode(0) while l1 and l2: if l1.val < l2.val: temp.next = ListNode(l1.val) l1 = l1.next else: temp.next = ListNode(l2.val) l2 = l2.next temp = temp.next temp.next = l1 or l2 return dummy.next ## This following code can be further reduced by temp.next = l1 or l2 # if l1: # temp.next = l1 # if l2: # temp.next = l2 # return dummy.next ## Actually we do not need to append that again, we just need to ## append the remaining list to the temp.next. ## The following content was commentted out. # while l1: # temp.next = ListNode(l1.val) # temp = temp.next # l1 = l1.next # while l2: # temp.next = ListNode(l2.val) # temp = temp.next # l2 = l2.next # return dummy.next def mergeTwoLists_2(self, l1, l2): ''' Try to be concise. The list method need to consider duplicates. ''' dummy = temp = ListNode(0) com = [l1, l2] while com: val = [item.val for item in com if item.val] for item in val: if item == min(val): temp.next = ListNode(item) temp = temp.next com = [item.next if item.val == min(val) else item for item in com if item.next] return dummy def mergeTwoLists_3(self, l1, l2): ''' Recursive way. No additional variable defined. quote "But may be a terrible solution from a practical point of view because the stack size would be equal to the length of the merged list, and may result in overflow for relatively small lists." But that's basically the problem for many recursive algorithms. 49 ms, 90.70%. The actual test speed is fast. ''' if not l1: return l2 if not l2: return l1 if l1.val < l2.val: l1.next = self.mergeTwoLists_3(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists_3(l1, l2.next) return l2 ######## merge k sorted lists ######## def mergeKLists(self, lists): ''' Merge k sorted linked lists and return it as one sorted list. The time complexity is O(m^2*n) n is the length of list, m is the length of lists. ''' dummy = temp = ListNode(0) while lists: vals = [] for nl in lists: if nl and nl.val != None: vals.append(nl.val) if not vals: break mv = min(vals) empty = [] for nl in lists: if nl and nl.val == mv: temp.next = ListNode(mv) temp = temp.next empty.append(nl.next) elif nl: empty.append(nl) lists = empty return dummy.next def mergeKLists_2(self, lists): ''' Utilized the previous merge two lists functions. Timelimit exceed for this case. Merge m-1 times. ''' temp = ListNode(None) for nl in lists: if nl and nl.val != None: if temp.val == None: temp.next = nl temp = temp.next else: temp = self.mergeTwoLists_3(temp, nl) if temp.val != None: return temp else: return None def mergeKLists_3(self, lists): ''' The idea is to keep the lists sorted by the node's val. Each time pop out the lowest value and append the next node. Reorgize the list and repeat the process until the list only contain one node. 139 ms, 77.93%, first try 132 ms, 82.86%, check mylist ''' dummy = temp = ListNode(0) mylist = [nl for nl in lists if nl and nl.val != None] mylist = sorted(mylist, key = operator.attrgetter('val')) while mylist: empty = mylist.pop(0) temp.next = empty temp = temp.next if mylist and empty.next and empty.next.val != None: mylist = self.sort_KList(mylist, empty.next) return dummy.next def sort_KList(self, mylist, target): ''' This is a helper function for mergeKLists_3 to sort out the list. The first n-1 items already sorted, need to insert the last item into the list using binary search. ''' low, high = 0, len(mylist)-1 while low <= high: mid = (low+high)/2 if mylist[mid].val == target.val: return mylist[:mid]+[target]+mylist[mid:] if mylist[mid].val < target.val: low = mid+1 else: high = mid-1 return mylist[:low]+[target]+mylist[low:] ######## swap nodes ######## def swapPairs(self, head): ''' Given a linked list, swap every two adjacent nodes and return its head Do not modify values in the list, only the node itself. Use constant space. The idea is to use keep track of 3 nodes and swap when a pair is found. 39 ms, 80.82% ''' dummy = ListNode(0) dummy.next = head pre = dummy count = 0 while head: count += 1 if count == 1: cur1 = head head = head.next else: cur1.next = head.next pre.next = head head.next = cur1 head = cur1.next pre = cur1 count = 0 return dummy.next def swapPairs_2(self, head): ''' To be more concise and less care about the order of swap. We can just swap then all at once. From pre -> a -> b -> b.next to pre -> b -> a -> b.next ''' pre = dummy = ListNode(0) dummy.next = head while pre.next and pre.next.next: a = pre.next b = a.next pre.next, a.next, b.next = b, b.next, a pre = a return dummy.next def swapPairs_3(self, head): ''' Same idea, but recursive way. ''' if not head or not head.next: return head temp = head.next head.next, temp.next = self.swapPairs_3(temp.next), head return temp ####### rotate list ####### def rotateRight(self, head, k): ''' Given a list, rotate the list to the right by k places, where k is non-negative 1-2-3-4-5, k=2 -> 4-5-1-2-3 Note that k could be larger than the length of the list. The idea is to go over the list, keep track of the last k node. If k is larger than the list len, use mod operation to find the least number needed to rotate right, and then do the iteration from the start again. This one achieves 100% performance. ''' if not head: return head dummy = ListNode(0) dummy.next = head pre = dummy p1 = p2 = 0 while head.next: p2 += 1 if p2-p1 == k: pre = pre.next p1 += 1 head = head.next if not p1: k = k%(p2+1) head = dummy.next p1 = p2 = 0 while head.next: p2 += 1 if p2-p1 == k: pre = pre.next p1 += 1 head = head.next if p1: head.next = dummy.next dummy.next = pre.next pre.next = None return dummy.next def rotateRight_2(self, head, k): ''' Same idea but make the code more simplified by adding a helper function that can be used twice. ''' if not head: return head dummy = ListNode(0) dummy.next = head pre = dummy p1, p2, pre, head = self.rotate_helper(head, k, pre) if not p1: p1, p2, pre, head = self.rotate_helper(dummy.next, k%(p2+1), pre) if p1: head.next = dummy.next dummy.next = pre.next pre.next = None return dummy.next def rotate_helper(self, head, k, pre): p1 = p2 = 0 while head.next: p2 += 1 if p2-p1 == k: pre = pre.next p1 += 1 head = head.next return (p1, p2, pre, head) def rotateRight_3(self, head, k): ''' From the other discussions. The idea is the same, first count the length of the list, connect the tail to the head. Then break the n-k node. Could get rid of the dummy node though. This saves a lot of coding, but not as fast as the previous code. ''' if not head: return head tail = head n = 1 while tail.next: tail = tail.next n +=1 tail.next = head for i in range(n-k%n): tail = tail.next ans = tail.next tail.next = None return ans ####### Remove duplicates from sorted list ####### def deleteDuplicates(self, head): '''Given a sorted linked list, deleted all duplicates sun that each element appear only once. 46 ms, 100% ''' if not head: return head ans = head slow = head while head.next: head = head.next if slow.val != head.val: slow.next = head slow = slow.next slow.next = None return ans def deleteDuplicates_2(self, head): ''' The previous code can be simplified to be more concise and use less variables and code. ''' current = head ## The current just check for the case when head == None ## Or just use a if statement at the beginning while current and current.next: if current.val == current.next.val: ## using this line could save the code to append None in the end current.next = current.next.next else: current = current.next return head def deleteDuplicates_3(self, head): ''' Could use recursion to save code. ''' if not head or not head.next: return head head.next = self.deleteDuplicates_3(head.next) return head.next if head.val == head.next.val else head ####### Delete duplicates from sorted list ####### def deleteDuplicates_all(self, head): ''' Follow up the previous question of removing duplicates, now we want to delete all duplicate numbers, only leaving distinct numbers from the list. The idea is that a node will be append to ans only when it does not match previous element and next element. Be aware of the corner cases, especially the endding node. 55 ms, 84.58%. ''' if not head or not head.next: return head ref = ListNode(None) dummy = ListNode(0) ans = dummy while head.next: if head.val != ref.val and head.val != head.next.val: ans.next = head ans = ans.next ref = head head= head.next if head and head.val != ref.val: ans.next = head else: ans.next = None return dummy.next def deleteDuplicates_all_2(self, head): ''' The idea is to use while loop to skip all the duplicates, then append the new node to the end. In each iteration, it checks whether the node is duplicated by the following node, but it will decide to append it to ans until next iteration. ''' if not head: return head dummy = ListNode(0) dummy.next = head cur = head pre = dummy while cur: while cur.next and cur.val == cur.next.val: cur = cur.next ## brilliant if statement here, it append assign cur.next ## pre.next as the candidate, and check if this candidate is ## duplicated in the next iteraction. If not, formally move on ## with the pre = pre.next if pre.next == cur: pre = pre.next else: pre.next = cur.next cur = cur.next return dummy.next def deleteDuplicates_all_3(self, head): ''' A recursive solution. ''' if not head: return head if head.next and head.val == head.next.val: while head.next and head.val == head.next.val: head = head.next return self.deleteDuplicates_all_3(head.next) else: head.next = self.deleteDuplicates_all_3(head.next) return head ######### partitioin list ######### def partition(self, head, x): ''' Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. Preserve the original relative order. The idea is to build two lists separately and combined them together in the end. Be aware to append None to the last node. 42 ms, 87.77% ''' l1 = dummy1 = ListNode(0) l2 = dummy2 = ListNode(0) while head: if head.val < x: l1.next = head l1 = l1.next else: l2.next = head l2 = l2.next head = head.next l2.next = None l1.next = dummy2.next return dummy1.next ######### reverse linked list ######### def reverseList(self, head): '''Reverse a singly linked list. The idea is that at each step, link back to previous node. Need to use extra memory to first save the next node before relink. Time complexity O(n), space complexity O(1) 45 ms, 89.11% ''' pre = None while head: temp = head.next head.next = pre pre = head head = temp return pre def reverseList_2(self, head): ''' The same idea with previous one but in a recursive way. ''' if not head: return head temp = self.reverseList(head) head.next = None return temp def reverse_helper(self, head): if head and head.next: temp = head.next head.next.next = head return self.reserse_helper(temp) return head def reverseList_3(self, head): ''' Simplified recursion using back tracking. Each step links back and breaks a link. Time complexity O(n), space complexity O(n) comes from implicit stack space due to recursion. ''' if not head or not head.next: return head temp = self.reverseList_3(head.next) head.next.next = head head.next = None return temp ######### reverse linked list ii ######### def reverseBetween(self, head, m, n): '''Reverse a linked list from position m to n. Do it in-place and in one-pass. Assume position (starts from 1): 1 <= m <= n <= length of list The idea to reverse is the same as the previous code. Just added some code select the starting and ending position. Not very concise to handle the corner cases. 35 ms, 94.54% ''' dummy = ListNode(None) dummy.next = head count = 1 while count < m: dummy = dummy.next count += 1 top = dummy tail = top.next if count == m: pre = dummy.next dummy = dummy.next.next count += 2 while count <= n+1: temp = dummy.next dummy.next = pre pre = dummy dummy = temp count += 1 tail.next = dummy top.next = pre if m == 1: return top.next else: return head def reverseBetween_2(self, head, m, n): ''' Uses for loop and clean up the code a bit. The idea is the same, but the key point here is to assign reverse == none, which acts as pre in previous code, where I initialized it to be a node when count == m. But this is acutally not neccessary, as long as we reassign a node to reverse, it will be fine. What following code did is first assign pre as None, and at last, cut the link to none and point to the tail of the list. This saves all the code I have for the corner cases in previous code. ''' dummy = ListNode(None) dummy.next = head pre = dummy for i in range(m-1): pre = pre.next reverse = None cur = pre.next for i in range(n-m+1): temp = cur.next cur.next = reverse reverse = cur cur = temp pre.next.next = cur pre.next = reverse return dummy.next ######### testing ######### mysol = sol() ## add two numbers #nums1 = [2,4,3] #nums2 = [5,6,4] #print mysol.addTwoNumbers_2(cast_list(nums1), cast_list(nums2)) ## remove nth from the end #nums = range(3) #print nums #print mysol.removeNthFromEnd_3(cast_list(nums), 2) ## merge two lists #nums1 = [1, 3, 6] #nums2 = [2, 3, 5, 8] #print mysol.mergeTwoLists(cast_list(nums1), cast_list(nums2)) ## merge k lists #nums = [ range(1, i) for i in range(3, 8)] #nums = [[1,3,5], [2,4,6],[1,2,6]] #nums = [[0,2,4], []] #nums = [[]] #for item in map(cast_list, nums): # print item #print nums #print 'merged as' #print mysol.mergeKLists_3(map(cast_list, nums)) ## swap nodes in pairs #nums = range(6) #print mysol.swapPairs_3(cast_list(nums)) ## rotate list ##nums = range(5) ##k = 5 ##print mysol.rotateRight_3(cast_list(nums), k) ## Remove duplicates ##import random ##nums = sorted([random.randint(0, 5) for _ in range(10)]) ##print nums ##print mysol.deleteDuplicates(cast_list(nums)) ##print mysol.deleteDuplicates_2(cast_list(nums)) ##print mysol.deleteDuplicates_3(cast_list(nums)) ## Delete duplicates ##import random ##nums = sorted([random.randint(0, 5) for _ in range(10)]) ##print nums ##print mysol.deleteDuplicates_all(cast_list(nums)) ##print mysol.deleteDuplicates_all_2(cast_list(nums)) ##print mysol.deleteDuplicates_all_3(cast_list(nums)) ## Partition list ##import random ##nums = sorted([random.randint(0, 5) for _ in range(10)]) ##x = 3 ##print nums ##print mysol.partition(cast_list(nums), x) ## Reverse list ##nums = range(5) ##print mysol.reverseList(cast_list(nums)) ##print mysol.reverseList_2(cast_list(nums)) ## Reverse list II nums = range(10) print nums print mysol.reverseBetween(cast_list(nums), 1, 2) print mysol.reverseBetween_2(cast_list(nums), 2, 2)
a7c1b66b105ef9712ba83be8bd1a9860d9ec5b3d
danielcaballero88/TWT-ML-Tutorial
/02_TF/code/02.py
758
3.984375
4
""" First tutorial video from Tim: Loading & Looking at Data See README.md """ import tensorflow as tf from tensorflow import keras import numpy as np from matplotlib import pyplot as plt # Load keras dataset data = keras.datasets.fashion_mnist # Split the data to train/test subsets (Keras makes it very easy) (train_images, train_labels), (test_images, test_labels) = data.load_data() # Get the label names from the dataset (listed in the website) class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # Let's see what the data actually looks like: print(train_images[7]) # Use pyplot to see some of the images plt.imshow(train_images[7], cmap=plt.cm.binary) plt.show()
fa41b63bbdb58c330e25a4d33ece8b223130ac39
gi-web/Python
/selfstudy/Code02_07_1.py
661
3.53125
4
import turtle import random ## 함수 선언 부분 ## def screenLeftClick(x,y): global r, g, b tSize = random.randrange(1,10) turtle.shapesize(tSize) r = random.random() g = random.random() b = random.random() turtle.pencolor(r, g, b) turtle.pendown() turtle.goto(x,y) def screenRightClick(x,y): turtle.penup() turtle.goto(x,y) ## 변수 선언 부분 ## pSize=10 r, g, b = 0.0, 0.0, 0.0 ## 메인 코드 부분 ## turtle.title(' 거북이로 그림 그리기') turtle.shape('turtle') turtle.pensize(pSize) turtle.onscreenclick(screenLeftClick,1) turtle.onscreenclick(screenRightClick,3) turtle.done()
f10b176057dafe5d5cea1db97e23160e07f1f594
nodin/eulerproject
/2Fibonacci.py
695
3.890625
4
""" 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 fibItem(n): if n<=2: #print n, " ",n return n else: resut = fibItem(n-2)+fibItem(n-1) #print n, ": ",resut return resut result=0 i=1 while True: value = fibItem(i) if value>4000000: break temp = fibItem(i) if temp%2 == 0: result+=temp i+=1 print result
dc19471afe572201d34453338db0354a016752ca
dineshpazani/algorithms
/src/com/python/LRC.py
1,392
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 7 20:25:00 2019 @author: dinesh """ class Lrc: def __init__(self): self.root = None def add(self, key, value): if self.root == None: self.root = Node(key, value) else: cNode = self.root temp = None while cNode.next is not None: if(cNode.key == key): print(key, temp.key) ccNode = cNode ccNode.data = value temp.next = cNode.next self.root = ccNode break temp = cNode cNode = cNode.next cNode.next = Node(key, value) def getAll(self): if self.root is not None: self.printAll(self.root) def printAll(self, cNode): if cNode is not None: print(cNode.data) self.printAll(cNode.next) class Node: def __init__(self, key, data): self.key = key self.data = data self.next = None class App: lrc = Lrc() lrc.add(10, 100) lrc.add(20, 200) lrc.add(30, 300) lrc.add(40, 400) lrc.add(50, 500) lrc.add(30, 600) lrc.getAll()
b687ad32e25e820b53bb519faa4489cb3cf178e5
zastari/Worked_Solutions
/projecteuler/euler_lib/properties.py
3,441
3.65625
4
import numpy as np from math import sqrt from functools32 import lru_cache from euler_lib import factor def amicable_pair(num): """ Determines if num is amicable and returns its copair element if it is :param num: :return: 0 if num is not amicable, num's copair element if it is """ copair = sum(factor.divisors(num)) - num return copair if (sum( factor.divisors(copair)) - copair) == num and copair != num else 0 def is_palindrome(num): """ Determines whether a number is a palindrome. :param num: Input number to check if palindromic :return: boolean """ return str(num) == str(num)[::-1] def is_pandigital(num, lower=1, upper=9): """ Returns True if num is pandigital else False :param num: (int) :kwarg lower: (int) lower limit for pandigital check :kwarg limit: (int) upper limit for pandigital check :return: (bool) """ pan_digits = {str(x) for x in xrange(lower, upper + 1)} num_digits = [str(x) for x in str(num)] return pan_digits.issubset(num_digits) and len(num_digits) == ( upper - lower + 1) @lru_cache(maxsize=1024) def is_prime(num): """ Returns True if num is prime else False :param num: :return: (bool) Primality of num """ if num == 1: return False for i in xrange(2, int(sqrt(num)) + 1): if num % i == 0: return False return True def is_triangular(num): return ((sqrt(8 * num + 1) - 1) / 2).is_integer() def is_pentagonal(num): return ((sqrt(24 * num + 1) + 1) / 6).is_integer() def is_hexagonal(num): return ((sqrt(8 * num + 1) + 1) / 4).is_integer() def max_2array_seq_prod(matrix, seq_len): """ Returns the maximal product of seq_len sequential elements of a matrix. Left -> Right, Up -> Down, and Diagonals are searched :param matrix: numpy matrix to search :param seq_len: number of sequential elements to multiply :return: (maximum product, list of elements that generated the product) """ dim = matrix.shape[0] max_product = 0 max_slice = [] for i in range(0, dim): for j in range(0, dim): # Right if j <= dim - seq_len: cur_slice = matrix[i, j:j + seq_len] cur_product = cur_slice.prod() if cur_product > max_product: max_slice, max_product = cur_slice, cur_product # Down if i <= dim - seq_len: cur_slice = matrix[i:i + seq_len, j] cur_product = cur_slice.prod() if cur_product > max_product: max_slice, max_product = cur_slice, cur_product # Down-Right if i <= dim - seq_len and j <= dim - seq_len: cur_slice = np.array( [matrix[i + x, j + x] for x in xrange(0, seq_len)]) cur_product = cur_slice.prod() if cur_product > max_product: max_slice, max_product = cur_slice, cur_product # Up-Right if i >= seq_len and j <= dim - seq_len: cur_slice = np.array( [matrix[i - x, j + x] for x in xrange(0, seq_len)]) cur_product = cur_slice.prod() if cur_product > max_product: max_slice, max_product = cur_slice, cur_product return max_product, max_slice
1ba2cfbf080937cdf11e0948ee4c570ef93e5016
Gaya1858/Algorithms
/file_08_31_2021/interview/array_common.py
416
3.953125
4
''' finding common elements between 2 sorted arrays takes O(N) time ''' def common_element(a,b): p1 =0 p2 =0 result =[] while p1<len(a) and p2 <len(b): if a[p1] == b[p2]: result.append(a[p1]) p1 +=1 p2 +=1 elif a[p1] >b[p2]: p2 +=1 else: p1 +=1 return result print(common_element([1,3,4,6,7,9],[1,2,4,5,9,10]))
7b8216d6598e162190044891a3dd8005a44e4ab7
Heelc/vscode
/interview/interview.py
322
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def format(template, data): res = template for dk in data.keys(): if dk in template: res = res.replace(dk, str(data[dk])) return res str1 = 'name今年age岁了.' dit = { 'name' : '狮子大哥', 'age': 18, } print(format(str1,dit))
cfdb0c4c320e106d3f31af758cea6d749cd2b8d1
Inferno-P/DesignPatterns
/Singleton.py
1,062
3.8125
4
# Using Singleton Pattern # This class is allwed to have only one instance. No matter how many time we call it, it will always return the same instance of the class. # Solves issues relatd to persistence like session transfer, database management, etc. class Singleton_Lazy(object): __instance = None def __init__(self): if not Singleton_Lazy.__instance: print("I have already got an instance.") else: print("I do not have an instance yet.") @classmethod def getInstance(cls): if not cls.__instance: cls.__instance = Singleton_Lazy() return cls.__instance class Singleton_Strict(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(Singleton_Strict, cls).__new__(cls) return cls.instance sL1 = Singleton_Lazy() sL2 = Singleton_Lazy() print("sL1: %s, sL2: %s ",(sL1.getInstance(), sL2.getInstance()) ) sS1 = Singleton_Strict() sS2 = Singleton_Strict() print("sS1: %s, sS2: %s ",(sS1, sS2))
23e666562bbd17ef4967b32208d4c0beb050fe2e
loust/layer8-python
/Python/01-HelloWorld.py
901
4.875
5
# This is a single comment. """ This is a long comment """ print("Hello World\n") # Another way to say hello is the following: hello = "World" print("Hello {}".format(hello)) # Another nice way to repeat similar things print("Hello {0} {0} {0}".format(hello)) # Now, you can see that, with a loop, you can make it so it will output something different when # it reaches the last item in the loop. An example will be shown in the Lists and Loops section. world = "Hello" print("{0} {1}".format(world,hello)) # This is the same as the following print("{} {}".format(world,hello)) # But does not follow the numbering. # {0} is the first paramter and {1} is the second. one = "one" two = "two" three = "three" variable = "four" print("{one}, {two}, {three}, {four}." .format( one=one, two=two, three=three, four=variable ) )
f1cda19f6ee9cc24289d18264ec8982a233603bf
yukaixue/spyder
/输出5个素数.py
500
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 21:36:37 2020 @author: Administrator """ count = 0 pri = [] def prime(m): global count,pri def is_prime(n): for i in range(2,n): if n % i ==0: return False return True if is_prime(m): pri.append(str(m)) count +=1 if count < 5: prime(m+1) return pri n = eval(input()) for item in prime(n): print(item,end=',')
883c82a80fb22bdb069b3ab9da077b65fb329525
mikewolfe/Shen_H-NS_2022
/compare_ishihama_data/fasta.py
8,856
3.8125
4
""" fasta Module to read, write, and manipulate fasta files. """ def complement(sequence): """Complement a nucleotide sequence >>> complement("AGTC") 'TCAG' >>> complement("AGNT") 'TCNA' >>> complement("AG-T") 'TC-A' """ # create a dictionary to act as a mapper comp_dict = {'A': 'T', 'G':'C', 'C':'G', 'T': 'A', 'N':'N', '-':'-', 'a':'t', 'g':'c', 'c':'g', 't':'a', 'n':'n'} # turn the sequence into a list sequence = list(sequence) # remap it to the compelmentary sequence using the mapping dict sequence = [comp_dict[base] for base in sequence] # join the new complemented sequence list into a string sequence = ''.join(sequence) return sequence class FastaEntry(object): """ Stores all the information for a single fasta entry. An example of a fasta entry is below: >somechromosomename AGAGATACACACATATA...ATACAT #typically 50 bases per line Args: header (str): The complete string for the header ">somechromosomename" in the example above. Defaults to ">" seq (str): The complete string for the entire sequence of the entry Attributes: header (str): The complete string for the header ">somechromosomename" in the example above. seq (str): The complete string for the entire sequence of the entry """ def __init__(self, header = ">", seq = ""): self.header = header self.seq = seq self.length = None def __str__(self): return "<FastaEntry>" + self.chrm_name() + ":" + str(len(self)) def __iter__(self): for val in self.seq: yield val def write(self,fhandle): fhandle.write(self.header+"\n") for i in range(0,len(self), 70): try: fhandle.write(self.seq[i:i+70]+"\n") except IndexError: fhandle.write(self.seq[i:-1] + "\n") def set_header(self, header): self.header = header def set_seq(self, seq, rm_na=None): if rm_na: for key in rm_na.keys(): seq = [rm_na[key] if x == key else float(x) for x in seq] self.seq = seq def __len__(self): if self.length: return self.length else: return(len(self.seq)) def pull_seq(self, start, end, circ=False, rc=False): """ Obtain a subsequence from the fasta entry sequence Args: start (int) : A start value for the beginning of the slice. Start coordinates should always be within the fasta entry sequence length. end (int) : An end value for the end of the slice. If circ is True then end coordinates can go beyond the fasta entry length. circ (boolean): Flag to allow the end value to be specified beyond the length of the sequence. Allows one to pull sequences in a circular manner. Returns: A subsequence of the fasta entry as specified by the start and end Raises: ValueError: If start < 0 or >= fasta entry sequence length. ValueError: If circ is False and end > fasta entry sequence length. """ seq_len = len(self) if start < 0 or start >= seq_len: if circ: if start < 0: start = seq_len + start end = seq_len + end elif start >= seq_len: start = start - seq_len end = end - seq_len else: raise ValueError("Start %s is outside the length of the sequence %s"%(start,seq_len)) if end > seq_len: if circ: seq = self.seq[start:seq_len] + self.seq[0:(end-seq_len)] else: raise ValueError("End %s is outside length of sequence %s"%(end,seq_len)) else: seq = self.seq[start:end] if rc: return complement(seq)[::-1] else: return seq def chrm_name(self): """ Pulls the chromosome name from the header attribute. Assumes the header is of the type ">chromosomename" and nothing else is in the header. Returns: chromosome name """ return self.header[1:] class FastaFile(object): """ Stores all the information for a single fasta file. An example of a fasta file is below >somechromosomename AGAGATACACACATATA...ATACAT GGGAGAGAGATCTATAC...AGATAG >anotherchromosomename AGAGATACACACATATA...ATACAT #typically 50 bases per line Attributes: data (dict): where the keys are the chromosome names and the entries are FastaEntry objects for each key """ def __init__(self): self.data = {} self.names = [] def __iter__(self): for name in self.names: yield self.pull_entry(name) def read_whole_file(self, fhandle): """ Read an entire fasta file into memory and store it in the data attribute of FastaFile Args: fhandle (File) : A python file handle set with mode set to read Returns: None Raises: ValueError: If fasta file does not start with a header ">" """ line = fhandle.readline().strip() if line[0] != ">": raise ValueError("File is missing initial header!") else: curr_entry = FastaEntry(header = line.rstrip().split()[0]) line = fhandle.readline().strip() curr_seq = [] while line != '': if line[0] == ">": curr_entry.set_seq(''.join(curr_seq)) self.data[curr_entry.chrm_name()] = curr_entry self.names.append(curr_entry.chrm_name()) curr_seq = [] curr_entry = FastaEntry(line) else: curr_seq.append(line) line = fhandle.readline().strip() curr_entry.set_seq(''.join(curr_seq)) self.data[curr_entry.chrm_name()] = curr_entry self.names.append(curr_entry.chrm_name()) def read_whole_datafile(self, fhandle, delim=","): """ Read an entire fasta file into memory and store it in the data attribute of FastaFile. This handles comma seperated data in place of sequence Args: fhandle (File) : A python file handle set with mode set to read Returns: None Raises: ValueError: If fasta file does not start with a header ">" """ import numpy as np line = fhandle.readline().strip() if line[0] != ">": raise ValueError("File is missing initial header!") else: curr_entry = FastaEntry(header = line.rstrip().split()[0]) line = fhandle.readline().strip() curr_seq = [] while line != '': if line[0] == ">": curr_entry.set_seq(curr_seq, rm_na={"NA":np.nan}) self.data[curr_entry.chrm_name()] = curr_entry self.names.append(curr_entry.chrm_name()) curr_seq = [] curr_entry = FastaEntry(line) else: line = line.split(delim) curr_seq.extend(line) line = fhandle.readline().strip() curr_entry.set_seq(curr_seq, rm_na={"NA":np.nan}) self.data[curr_entry.chrm_name()] = curr_entry self.names.append(curr_entry.chrm_name()) def pull_entry(self, chrm): """ Pull a FastaEntry out of the FastaFile Args: chrm (str): Name of the chromosome that needs pulled Returns: FastaEntry object """ try: return self.data[chrm] except KeyError: raise KeyError("Entry for chromosome %s does not exist in fasta file"%chrm) def add_entry(self, entry): """ Add a FastaEntry to the object Args: entry (FastaEntry): FastaEntry to add Returns: None """ self.data[entry.chrm_name()]= entry self.names.append(entry.chrm_name()) def chrm_names(self): return self.data.keys() def write(self, fhandle): """ Write the contents of self.data into a fasta format Args: fhandle (File) : A python file handle set with mode set to write Returns: None """ for entry in self: entry.write(fhandle)
92b16f6fa02ef861816c082fcbf857e2490e3818
gomtinQQ/algorithm-python
/codeUp/codeUpBasic/1551.py
654
3.546875
4
''' 1551 : [기초-함수작성] 함수로 원하는 값의 위치 리턴하기 1 n 개의 정수를 배열로 입력 받고, 원하는 값 k가 저장되어있는 가장 처음 위치를 출력하시오. (원하는 값 k값이 저장되어있지 않은 경우에는 –1을 출력한다.) 단, 함수형 문제이므로 함수 f()만 작성하시오. ''' def f(lst, myNum): for i in range(len(lst)): lst[i] = int(lst[i]) for i in range(len(lst)): if (myNum == lst[i]): return i+1 if (myNum not in lst): return -1 n = int(input()) lst = input().split() myNum = int(input()) print(f(lst, myNum))
0ed8c03828983bd2b2263fe834ebe1cd55b0c737
young31/Algorithm
/백준/12904.py
237
3.5625
4
s = input() t = input() while 1: if t[-1] == 'B': t = t[:-1] t = t[::-1] else: t = t[:-1] if len(t) == len(s): if t == s: print(1) else: print(0) break
16c2b73aa01db28c0a47d8fa593800fc52c9d1fa
heirsh/smaowl_project_yeet
/project.py
5,749
3.84375
4
print("welcome to heirsh tours and travels for maharashhtra") print("in accosiation with the gretest codinng class SMOWL") print("we offer bus,plane and taxi") so=str(input("what will you choose:")) if(so=="bus"): print("bus offers travel to nashik,bombay,aurangabad,navi mumbai") dodo=str(input("where would you like to go")) if(dodo=="bombay"): print("thats nice dont forget to check the india gate") print("every km is 10 rupees so your total is 1480 rupees") print("after applaying your first time discount your total comes to",90/100*1480,"thank you for choosing us") if(dodo=="nashik"): print("thats nice dont forget to check the pandav leni caves") print("every km is 10 rupees so your total is 2110 rupees") print("after applaying your first time discount your total comes to",90/100*2110,"thank you for choosing us") if(dodo=="aurangabad"): print("thats nice dont forget to check the Bibi Ka Maqbara") print("every km is 10 rupees so your total is 2360 rupees") print("after applaying your first time discount your total comes to",90/100*2360,"thank you for choosing us") if(dodo=="navi mumbai"): print("every km is 10 rupees so your total is 1270 rupees") print("after applaying your first time discount your total comes to",90/100*1270,"thank you for choosing us") if(so=="plane","aeroplane"): print("bus offers travel to nashik,bombay,aurangabad,nagpur") no=str(input("where would you like to go")) if(no=="bombay"): print("thats nice dont forget to check the india gate") print("every km is 100 rupees so your total is 14800 rupees") print("after applaying your first time discount your total comes to",90/100*14800,"thank you for choosing us") if(no=="nashik"): print("thats nice dont forget to check the pandav leni caves") print("every km is 100 rupees so your total is 21100 rupees") print("after applaying your first time discount your total comes to",90/100*21100,"thank you for choosing us") if(no=="aurangabad"): print("thats nice dont forget to check the Bibi Ka Maqbara") print("every km is 100 rupees so your total is 23600 rupees") print("after applaying your first time discount your total comes to",90/100*23600,"thank you for choosing us") if(no=="nagpur"): print("every km is 100 rupees so your total is 71200 rupees","dont forget to visit the swaminarayan temple") print("after applaying your first time discount your total comes to",90/100*71200,"thank you for choosing us") else: print(".") if(so=="taxi","car"): print("taxi offers travel to nashik,bombay,aurangabad,nagpur,navi mumbai") ge=str(input("where would you like to go")) if(ge=="bombay"): print("thats nice dont forget to check the india gate") print("every km is 20 rupees so your total is 2960 rupees") print("after applaying your first time discount your total comes to",90/100*2960,"thank you for choosing us") if(ge=="nashik"): print("thats nice dont forget to check the pandav leni caves") print("every km is 20 rupees so your total is 4220 rupees") print("after applaying your first time discount your total comes to",90/100*4220,"thank you for choosing us") if(ge=="aurangabad"): print("thats nice dont forget to check the Bibi Ka Maqbara") print("every km is 20 rupees so your total is 4720 rupees") print("after applaying your first time discount your total comes to",90/100*4720,"thank you for choosing us") if(ge=="nagpur"): print("every km is 20 rupees so your total is 14240 rupees","dont forget to visit the swaminarayan temple") print("after applaying your first time discount your total comes to",90/100*14240,"thank you for choosing us") if(ge=="navi mumbai"): print("every km is 20 rupees so your total is 2540 rupees") print("after applaying your first time discount your total comes to",90/100*2540,"thank you for choosing us") hotel=str(input("would you like to also book a hotel")) else: print("not valid") else: print("we dont have that vehicle access for you") np=str(input("would you also like to pick a package for where you are going")) if(np=="yes"): db=str(input("so where have you picked as a destination")) if(db=="navi mumai"): skrt=str(input("thats great we have a package for 7 grand per head and accomodation at the taj for 4 days so yes or no")) if(skrt=="yes"): print("thats great checkout amount added 7000") if(db=="mumbai"): nope=str(input("thats great we have a package for 7 grand per head and accomodation at the taj for 4 days so yes or no")) if(nope=="yes"): print("thats great checkout amount added 7000") if(db=="nagpur"): memes=str(input("thats great we have a package for 7 grand per head and accomodation at the taj for 4 days so yes or no")) if(memes=="yes"): print("thats great checkout amount added 7000") if(db=="aurangabad"): yeti=str(input("thats great we have a package for 7 grand per head and accomodation at the taj for 4 days so yes or no")) if(yeti=="yes"): print("thats great checkout amount added 7000") if(db=="nashik"): bits=str(input("thats great we have a package for 7 grand per head and accomodation at the taj for 4 days so yes or no")) if(bits=="yes"): print("thats great checkout amount added 7000") else: print("invalid") else: print("not availible")
0bd11abe6ac837c1fa6e725dea8ff7e150115cf4
kapc/problems
/Arrays/rotate_matrix.py
967
3.9375
4
#! /usr/env/python """ Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? """ def rotate_matrix(matrix): """ """ if not matrix: return matrix if len(matrix) == 0 or len(matrix) != len(matrix[0]): return matrix n = len(matrix) for layer in range(0, int(n/2)): first = layer last = n - 1 - layer for i in range(first, last): offset = i - first top = matrix[first][i] print(top) matrix[first][i] = matrix[last - offset][first] matrix[last - offset][first] = matrix[last][last - offset] matrix[last][last - offset] = matrix[i][last] matrix[i][last] = top if __name__ == "__main__": matrix = [[1,2,3,4], [5,6,7,8], [7,8,9,10],[11,12,13,14]] rotate_matrix(matrix) print(matrix)
33a78a73c49e00bdf90ebe058e754fb4e83c8534
AKJAIN786/healthifyme
/init.py
2,112
3.671875
4
import time print("Welcome to Healthy me") class User123: def __init__(self, name, number): self.name = name # self.domain = domain self.number = number @property def form(self): a = self.name.split() global a1, a2 a1 = a[0] a2 = a[1] # email = f"{a1}.{a2}@{self.domain}.com" return \ print(f"your info \n*Name-- {self.name},\n*Number-- {self.number} ") @staticmethod def sound(activity_name): from win32com.client import Dispatch speak = Dispatch("SAPI.spVoice") speak.speak(f"It is time to {activity_name} " f"please get up {m}") time.sleep(30) speak.speak(f"Type 'Done' in CMD if you're done with this ") @staticmethod def entry_system(activity_name): peal = input("Type Done if you have completed ") with open("Time table", 'a+') as f: f.write(f"\n {m} + {activity_name} + {time.asctime()}") f.write(f" Task status {peal}") f.close() while True: m = str(input("Provide your full name ")) o = str(input("Provide Number ")) metre = User123(m, o) print("Enter Time Details in minute") BPE = float(input("Enter exercise(At least 30 min)")) BPW = float(input("Enter Water(Should be more than Quiet more than Exercise)")) joy = float(input("Enter for eye(Should be more than Quiet more than Exercise)")) print(metre.form) g=input(f"{m} Can we start Y/N ") if g == "Y": print("Now minimize Tab \nWe will handle all") x = 0 while x <= 8: time.sleep(30 * BPE) User123.sound(" Exercise") User123.entry_system("exercise") time.sleep(30 * BPW - 30 * BPE) User123.sound("Drink Water") User123.entry_system('water') time.sleep(30 * joy - 30 * BPE) User123.sound("Eyes Exercise") User123.entry_system('eyes exercise') elif g=="N": print("something wrong \n**Maybe yor inputs") else:print("You're done for Today")
e04fa7214ca3434a48d18f33bdd5fe07a6f9f42b
yjyyjyyjyyjy/data_analysis
/data_analysis/Python/53lambda.py
446
3.96875
4
# Press the green button in the gutter to run the script. # list[param1:param2:param3] # # param1,相当于start_index,可以为空,默认是0 # param2,相当于end_index,可以为空,默认是list.size # param3,步长,默认为1。步长为-1时,返回倒序原序列 if __name__ == '__main__': fruits=["apple", "cherry", "peal", "strawberry"] print(sorted(fruits, key=(lambda x: x[::-1]))) print(fruits)
012e62049e4478629662e37613bd293f2a6f582f
bigMeowCoding/dataStructure
/algorithm/sort/insertOPT.py
492
3.828125
4
from algorithm.utils import util class InsertSort: def insertSort(self, arr, n): for i in range(1, n): temp = arr[i] j=i while j>0 and temp < arr[j - 1]: arr[j]=arr[j-1] j-=1 arr[j]=temp def swap(self, arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp sort = InsertSort() arr = util.generateUnsortedArr(0, 10000, 10000) sort.insertSort(arr, len(arr)) print(arr)
a772efe27f17d52858302a6b1aebae01eddf0fa3
karanjadhav2508/fss16iad
/code/3/BirthdayParadox/birthday.py
1,068
3.703125
4
from __future__ import division import random import sys __author__="Karan Jadhav" """ Checks if given list has duplicate elements :lst : list to be checked :return : boolean """ def has_duplicates(lst): for i in range(len(lst)): if lst[i] in lst[i+1:]: return True return False """ Calculates probability of 2 people having the same birthday in a group :num_people : number of people :sample_size : number of times birthdays are sampled """ def birthday_paradox(num_people, sample_size): same_birthdays = 0 for i in range(sample_size): birthdays = [] for i in range(num_people): birthdays.append(random.randint(1,366)) if has_duplicates(birthdays): same_birthdays += 1 print "probability : %s" % (same_birthdays/sample_size) if __name__=="__main__": lst1 = [1,2,3,] lst2 = [3,1,2,2] lst3 = ["abc", "xyz", "abc"] print "Exercise 8.1" print("{} : {} {} : {} {} : {}\n".format(lst1, has_duplicates(lst1), lst2, has_duplicates(lst2), lst3, has_duplicates(lst3))) print "Exercise 8.2" birthday_paradox(23, 100)
6e51ed2280fb78c77eed9f7a92abef75f6de15f6
bingplease/something
/graphingwaves.py
1,781
3.546875
4
from pygame import * from math import * init() width, height = 1000, 1000 w = display.set_mode([width, height]) factor = 100 w.fill((255, 255, 255)) def sinwave(): for i in range(1, width): draw.line(w, (255, 0, 0), (i, -sin(radians(i)) * factor + height/2), (i, -sin(radians(i)) * factor + height/2), 3) display.flip() print(i) def coswave(): for i in range(1, width): draw.line(w, (0, 255, 0), (i, -cos(radians(i)) * factor + height/2), (i, -cos(radians(i)) * factor + height/2), 3) display.flip() print(i) def tanwave(): for x in range(1, int(ceil(width/90))): for i in range(1, 90): draw.line(w, (0, 0, 255), (i + 90*x, -tan(radians(i)) * factor + height/2), (i + 90*x, -tan(radians(i)) * factor + height/2), 3) display.flip() print(i) for i in range(1, 90): draw.line(w, (0, 0, 255), (i + 90*x + 90, -tan(radians(-90+i)) * factor + height/2), (i + 90*x + 90, -tan(radians(-90+i)) * factor + height/2), 3) display.flip() print(i) def tansinwave(): for x in range(1, int(ceil(width/90))): for i in range(1, 90): draw.line(w, (0, 0, 0), (i + 90*x, -tan(sin(radians(i))) * factor + height/2), (i + 90*x, -tan(sin(radians(i))) * factor + height/2), 3) display.flip() print(i) for i in range(1, 90): draw.line(w, (0, 0, 0), (i + 90*x + 90, tan(sin(radians(90-i))) * factor + height/2), (i + 90*x+90, tan(sin(radians(90-i))) * factor + height/2), 3) display.flip() print(i) draw.line(w, (0, 0, 0), (0, height/2), (width, height/2), 3) #sinwave() #coswave() #tanwave() tansinwave() time.wait(30000)
a562e8accb91781230a4ba4056668946d989ed5e
radk0s/ply
/AST.py
10,937
3.671875
4
class Node(object): def accept(self, visitor, table = None): return visitor.visit(self) def setParent(self, parent): self.parent = parent class Program(Node): def __init__(self, declarations, fundefs, instructions): self.declarations = declarations self.fundefs = fundefs self.instructions = instructions self.children = ( declarations, fundefs, instructions ) def toString(self, i): return self.declarations.toString(i) + \ (self.fundefs.toString(i) if("toString" in dir(self.fundefs)) else '')+ \ self.instructions.toString(i) class Declarations(Node): def __init__(self, declarations, declaration): self.declarations = declarations self.declaration = declaration self.children = ( declarations, declaration ) def toString(self, i): return self.declarations.toString(i) + \ self.declaration.toString(i) class Declaration(Node): def __init__(self, type, inits): self.type = type self.inits = inits self.children = ( inits ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'DECL' + '\n' + \ self.inits.toString(i+1) if("toString" in dir(self.inits)) else '<<ERROR HERE>>\n' class Inits(Node): def __init__(self, inits, init): self.inits = inits self.init = init self.children = ( inits, init ) def toString(self, i): return (self.inits.toString(i) if("toString" in dir(self.inits)) else '') + \ (self.init.toString(i) if("toString" in dir(self.init)) else '') class Init(Node): def __init__(self, id, expression): self.id = id self.expression = expression self.children = ( expression ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + '=' + '\n' + pal + '| ' + self.id + '\n' + self.expression.toString(i+1) class Instructions(Node): def __init__(self, instructions, instruction): self.instructions = instructions self.instruction = instruction self.children = ( instructions, instruction ) def toString(self, i): return (self.instructions.toString(i) if("toString" in dir(self.instructions)) else '') + \ (self.instruction.toString(i) if("toString" in dir(self.instruction)) else '') class Instruction(Node): def __init__(self, instruction): self.instruction = instruction self.children = ( instruction ) def toString(self, i): return self.instruction.toString(i) class Print(Node): def __init__(self, expression): self.expression = expression self.children = ( expression ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'PRINT' + '\n'\ + self.expression.toString(i+1) class Labeled(Node): def __init__(self, id, instruction): self.id = id self.instruction = instruction self.children = ( instruction ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.id.upper() + '\n'\ + self.instruction.toString(i+1) class Assignment(Node): def __init__(self, id, expression): self.id = id self.expression = expression self.children = ( expression ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + '=' + '\n' + pal + '| ' + self.id + '\n' + self.expression.toString(i+1) class Choice(Node): def __init__(self, condition, instruction1, instruction2): self.condition = condition self.instruction1 = instruction1 self.instruction2 = instruction2 self.children = ( condition, instruction1, instruction2 ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'IF' + '\n' + \ self.condition.toString(i+1) + \ self.instruction1.toString(i+1) + \ pal + 'ELSE' + '\n' + \ self.instruction2.toString(i+1) class While(Node): def __init__(self, condition, instruction): self.condition = condition self.instruction = instruction self.children = ( condition, instruction ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'WHILE' + '\n' + \ self.condition.toString(i+1) + \ self.instruction.toString(i+1) class Repeat(Node): def __init__(self, instruction, condition): self.instruction = instruction self.condition = condition self.children = ( instruction, condition ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'REPEAT' + '\n' + self.instruction.toString(i+1) + \ pal + 'UNTIL' + '\n' + self.condition.toString(i+1) class Return(Node): def __init__(self, expression): self.expression = expression self.children = ( expression ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'RETURN' + '\n' + \ self.expression.toString(i+1) class Keyword(Node): def __init__(self, keyword): self.keyword = keyword self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.keyword + '\n' class CompoundInstruction(Node): def __init__(self, declarations, instructions): self.declarations = declarations self.instructions = instructions self.children = ( declarations, instructions ) def toString(self, i): return self.declarations.toString(i) + self.instructions.toString(i) class Condition(Node): def __init__(self, expression): self.expression = expression self.children = ( expression ) def toString(self, i): return self.expression.toString(i) class Integer(Node): def __init__(self, value): self.value = value self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.value + '\n' class Float(Node): def __init__(self, value): self.value = value self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.value + '\n' class String(Node): def __init__(self, value): self.value = value self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.value + '\n' class Variable(Node): def __init__(self, name): self.name = name self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.name + '\n' class BinExpression(Node): def __init__(self, expression1, operator, expression2): self.expression1 = expression1 self.operator = operator self.expression2 = expression2 self.children = ( expression1, operator, expression2 ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + self.operator + '\n' + self.expression1.toString(i+1) + self.expression2.toString(i+1) class ExpressionInParentheses(Node): def __init__(self, expression): self.expression = expression self.children = ( expression ) def toString(self, i): return self.expression.toString(i) class Funcall(Node): def __init__(self, id, expressionList): self.id = id self.expressionList = expressionList self.children = ( expressionList ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'FUNCALL\n' + pal + \ '| ' + self.id + '\n' + self.expressionList.toString(i+1) class ExpressionList(Node): def __init__(self, expressionList, expression): self.expressionList = expressionList self.expression = expression self.children = ( expressionList, expression) def toString(self, i): return (self.expressionList.toString(i) if("toString" in dir(self.expressionList)) else '') + \ (self.expression.toString(i) if("toString" in dir(self.expression)) else '') class FunctionDefinitions(Node): def __init__(self, fundef, fundefs): self.fundef = fundef self.fundefs = fundefs self.children = ( fundef, fundefs) def toString(self, i): return self.fundef.toString(i) + self.fundefs.toString(i) class FunctionDefinition(Node): def __init__(self, type, id, argList, compoundInstruction): self.type = type self.id = id self.argList = argList self.compoundInstruction = compoundInstruction self.children = ( argList, compoundInstruction) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' #return pal + self.TYPE + '\n' + pal + self.ID + '\n' + self.first.toString(i+1) + self.second.toString(i+1) return pal + 'FUNDEF' + '\n' + \ pal + '| ' + self.id + '\n' + \ '| ' + 'RET ' + self.type + '\n' + \ self.argList.toString(i+1) + \ self.compoundInstruction.toString(i+1) class ArgumentList(Node): def __init__(self, argList, arg): self.argList = argList self.arg = arg self.children = ( argList, arg ) def toString(self, i): return (self.argList.toString(i) if("toString" in dir(self.argList)) else '') + \ (self.arg.toString(i) if("toString" in dir(self.arg)) else '') class Argument(Node): def __init__(self, type, id): self.type = type self.id = id self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return pal + 'ARG ' + self.id + '\n' class Empty(Node): def __init__(self): self.name = "" self.children = ( ) def toString(self, i): pal = "" for x in range(0, i): pal += '| ' return self.name
58da8589dd62e23a4c9401d36890d7225842ea39
maeveconneely/GWC-python-projects
/dictionaries.py
1,191
4.375
4
# Syntax to create a new dictionary # { key: value } d = {"mom": "Jen", "dad": "Mike", "sister": "orla"} # i gets the reference, so use indexing in for loops for i in d: print(d[i]) # i is now the keys for i in d.keys(): print(i) # i in now the values for i in d.values(): print(i) # prints a list of all of the definitions in the dictionary as tuples print() print(list(d.items())) # add list() so it looks prettier and becomes list item print() # adding new elements d["sister2"] = "aoife" print("aoife" in d) # False print("sister2" in d) # True print() # if you're looking for a value that you are not sure exists, use .get() print(d.get("sister")) # orla print(d.get("brother")) # None Class: NoneType # change the element print() d["sister2"] = "feena" # delete an element in the list del d["sister2"] print(d) print() # get the item back sister = d.pop("sister") # uses key like .pop() in list uses indexes print(sister) print(d) # clears the dictionary d.clear() print() print(d) # Notes: # changing "" to '' doesn't matter, because python parses them the same way # keys can be ints, floats, tuples, strings, or anything that is immutatable
cb6b55524dc2b5bfcd021c7afdd8e68918f3b446
olanguyenvan/advent-of-code19
/day2/main.py
1,972
3.5625
4
import sys from datetime import datetime def solve_puzzle_1(numbers_int, noun = 12, verb = 2): numbers_int[1] = noun numbers_int[2] = verb def run_the_program(index = 0): opcode = numbers_int[index] def add_operation(): numbers_int[numbers_int[index + 3]] = numbers_int[numbers_int[index + 1]] + numbers_int[numbers_int[index + 2]] run_the_program(index + 4) def mult_operation(): numbers_int[numbers_int[index + 3]] = numbers_int[numbers_int[index + 1]] * numbers_int[numbers_int[index + 2]] run_the_program(index + 4) def halt_program(): pass switcher = { 1: add_operation, 2: mult_operation, 99: halt_program, } switcher[opcode]() run_the_program() return numbers_int[0] def solve_puzzle_2(numbers_int): expected_output = 19690720 for noun in range(99): for verb in range(99): numbers_int_copy = numbers_int[:] solve_puzzle_1(numbers_int_copy, noun, verb) if numbers_int_copy[0] == expected_output: print(noun, verb) return 100 * noun + verb if __name__ == "__main__": if len(sys.argv) <= 1: print("No input given. Specify a path to the input file.") print("python main.py path-to-input") else: puzzle_input = open(sys.argv[1]).read() numbers_str = list(filter(lambda line: line != "", puzzle_input.split(","))) numbers_int = list(map(int, numbers_str)) start_ex_1 = datetime.now() solution_1 = solve_puzzle_1(numbers_int[:]) print("Answer for day1, exercise 1: %s" % solution_1) print(datetime.now() - start_ex_1) start_ex_2 = datetime.now() solution_2 = solve_puzzle_2(numbers_int[:]) print("Answer for day1, exercise 2: %s" % solution_2) print(datetime.now() - start_ex_2)
12dc7510c60ae4d79e66e03d12dd820f06267368
Vasilic-Maxim/LeetCode-Problems
/problems/994. Rotting Oranges/1 - DFS.py
1,584
3.859375
4
from collections import deque from typing import List class Solution: """ Time: O(m * n) each cell is visited at least once Space: O(m * n) in the worst case if all the oranges are rotten they will be added to the queue """ def orangesRotting(self, grid: List[List[int]]) -> int: rows = len(grid) if rows == 0: return -1 cols = len(grid[0]) fresh_count = 0 rotten = deque() for r in range(rows): for c in range(cols): if grid[r][c] == 2: rotten.append((r, c)) elif grid[r][c] == 1: fresh_count += 1 minutes_passed = 0 while rotten and fresh_count > 0: # update the number of minutes passed minutes_passed += 1 # process rotten oranges on the current level for _ in range(len(rotten)): x, y = rotten.popleft() # visit all the adjacent cells for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]: xx, yy = x + dx, y + dy if xx < 0 or xx == rows or yy < 0 or yy == cols: continue if grid[xx][yy] == 0 or grid[xx][yy] == 2: continue fresh_count -= 1 grid[xx][yy] = 2 rotten.append((xx, yy)) # return the number of minutes taken to make all the fresh oranges to be rotten return minutes_passed if fresh_count == 0 else -1
42f7430b8608bffe1e566fb3ec1bc47ce79ad129
felipefrmelo/data-structure-and-algorithms
/P1/union-and-intersection/union_and_intersection_test.py
1,268
3.875
4
from union_and_intersection import intersection, union, LinkedList def make_linked_list(elements): linked_list = LinkedList() for i in elements: linked_list.append(i) return linked_list def helper(element_1, element_2, expected_union, expected_intersection): linked_list_1 = make_linked_list(element_1) linked_list_2 = make_linked_list(element_2) result_union = union(linked_list_1, linked_list_2) assert len(expected_union) == result_union.size() for expected in expected_union: assert str(expected) in str(union(linked_list_1, linked_list_2)) result_intersection = intersection(linked_list_1, linked_list_2) assert len(expected_intersection) == result_intersection.size() for expected in expected_intersection: assert str(expected) in str(intersection(linked_list_1, linked_list_2)) def test_union_and_intersection(): helper([1, 2, 3, 4, 5, 6], [6, 7, 8], [ 1, 2, 3, 4, 5, 6, 7, 8, ], [6]) # one list is empty helper([], [1, 2, 3], [1, 2, 3], []) # both lists are empty helper([], [], [], []) # list equals helper([1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]) # list without equal elements helper([1, 2, 3], [4, 5, 6], [1, 2, 3, 4, 5, 6], [])
3fcf616b731fc94380a8a1a1ae99f668077ac0fc
gokuldevp/Test-Typing-Speed-App
/main.py
4,864
3.765625
4
import tkinter as tk from random import choice from datetime import datetime # getting the list of of random words from text.txt with open("text.txt", mode="r") as text: text_list = text.read().split("\n") class TypingSpeedTestApp(tk.Frame): """Class to create Typing Speed Test App""" def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("Typing Speed Test App") # setting screen size self.master.minsize(600, 600) self.master.maxsize(600, 600) # Alpha or Numeric Variables self.number_of_word = 0 self.time = 0 self.start_time = None self.end_time = None self.sample_text = None # Entry Variable self.entry = tk.Entry(font=("Times New Roman", 14), width=65) # Labels self.app_label = tk.Label(text="Typing Speed Test App", font=("Times New Roman", 30)) self.score_label = tk.Label(text=f"High Score: {self.time}", font=("Times New Roman", 22)) # Message self.text_message = tk.Message(justify="left", text=self.sample_text, font=("Times New Roman", 18)) # Button self.start_button = tk.Button(text="Start Typing Test", command=self.start_text, font=("Times New Roman", 30)) self.check_button = tk.Button(text="Check Typing Test", command=self.check_text, font=("Times New Roman", 15)) # Widget Placement self.app_label.place(relx=.23, rely=.2) self.start_button.place(relx=.26, rely=0.5) def start_text(self): """Function to Start the Typing Speed Test""" # removing message widget self.text_message.place(relx=10, rely=10) # Remove entry and score widget self.score_label.place(relx=10, rely=10) self.entry.place(relx=10, rely=10) # Entry self.entry = tk.Entry(font=("Times New Roman", 14), width=65) # get start time self.start_time = datetime.now() # Get sample text self.get_sample_text() # Message self.text_message = tk.Message(justify="left", text=self.sample_text, font=("Times New Roman", 18)) # reset Test self.start_button.config(text="Restart",command=self.start_text, font=("Times New Roman", 15)) # Widget Placement self.app_label.place(relx=10, rely=10) self.start_button.place(relx=.13, rely=.9) self.check_button.place(relx=.63, rely=.9) self.text_message.place(relx=0, rely=0) self.entry.place(relx=0.01, rely=.8) def check_text(self): """Function to Check the result and show the Results""" # get end time self.end_time = datetime.now() wrong_words = 0 right_words = 0 # list of message words and typed words message_words = self.sample_text.split() typed_words = self.entry.get().split() # getting number of words if len(typed_words) <= 100: self.number_of_word = len(typed_words) else: self.number_of_word = 100 # getting count of wrong words and right words for i in range(self.number_of_word): if message_words[i] == typed_words[i]: right_words += 1 else: wrong_words += 1 # calculating typing speed, wrong words and right words per minutes self.time = [float(num) for num in str(self.end_time - self.start_time).split(":")[1:]] wrong_speed = round(wrong_words/round(self.time[0] + self.time[1]/60, 2), 2) right_speed = round(right_words/round(self.time[0] + self.time[1]/60, 2), 2) speed = round(self.number_of_word/round(self.time[0] + self.time[1]/60, 2), 2) # showing the result score_text = f"Right Words : {right_words}\n\nWrong Words: {wrong_words}\n\nTyping Speed: {speed} Words per Minutes\n\nWrong Speed: {wrong_speed} Words per Minutes\n\nRight Speed : {right_speed} Words per Minutes" self.score_label.config(justify="left", text=score_text) # Start Again Button self.start_button.config(text="Start Again", font=("Times New Roman", 30)) # Widget Placement self.score_label.place(relx=.20, rely=0.1) self.start_button.place(relx=.34, rely=0.8) self.text_message.place(relx=10, rely=10) self.check_button.place(relx=10, rely=10) self.entry.place(relx=10, rely=10) def get_sample_text(self): """Function to get Sample text""" self.sample_text = "" for i in range(100): self.sample_text += choice(text_list) + " " root = tk.Tk() app = TypingSpeedTestApp(root) app.mainloop()
2ff921dbb602cb0a051da069e9285001b190af4d
ineed-coffee/PS_source_code
/LeetCode/86. Partition List(Medium).py
1,070
3.6875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: ListNode, x: int) -> ListNode: L_ptr,R_ptr=None,None L_start,R_start=None,None cur=head while cur: if cur.val<x: if L_ptr==None: L_ptr=cur L_start=L_ptr else: L_ptr.next=cur L_ptr=L_ptr.next cur=cur.next L_ptr.next=None else: if R_ptr==None: R_ptr=cur R_start=R_ptr else: R_ptr.next=cur R_ptr=R_ptr.next cur=cur.next R_ptr.next=None if L_ptr and R_ptr: L_ptr.next=R_start return L_start elif not L_ptr: return R_start else: return L_start
b3bdc8bdaf28a06579fa7d83e547b3cb703264e5
JanieTran/SCHOOL_ProgrammingIoT
/W03/Lecture8/4.flask/02_venv_templates/app/routes.py
1,154
3.53125
4
from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = {'username': 'JohnDoe'} return render_template('index.html', title='Home', user=user) """ The operation that converts a template into a complete HTML page is called rendering. To render the template I had to import a function that comes with the Flask framework called render_template(). This function takes a template filename and a variable list of template arguments and returns the same template, but with all the placeholders in it replaced with actual values. The render_template() function invokes the Jinja2 template engine that comes bundled with the Flask framework. Jinja2 substitutes {{ ... }} blocks with the corresponding values, given by the arguments provided in the render_template() call. """ """ Not a good way of coding from app import app @app.route('/') @app.route('/index') def index(): user = {'username': 'Miguel'} return ''' <html> <head> <title>Home Page - Microblog</title> </head> <body> <h1>Hello, ''' + user['username'] + '''!</h1> </body> </html>''' """
2a0f094d3cf02dd34e5ca511d4d1a209c296699a
nitin-test/worldlang
/world.py
15,736
3.5625
4
class World(object): def __init__(self): # ---Object graph--- # Set of all objects: set<str> self.objs = set() # Set of all types: set<str> self.types = set() # Set of all relations: set<str> self.rels = set() # Map from object to types: str->set<str> self.obj_2_types = dict() # Map from type to objects: str->set<str> self.type_2_objs = dict() # Map from relation to objects: str->set<str> self.rel_2_objs = dict() # Map from object+relation to objects: (str,str)->set<str> self.obj_rel_2_objs = dict() # ---Type graph--- # str->set<str> self.sub_types = {} self.super_types = {} def copy(self): world = self.__class__() attrs = ['objs', 'types', 'rels', 'obj_2_types', 'type_2_objs', 'rel_2_objs', 'obj_rel_2_objs'] for attr in attrs: setattr(world, getattr(self, attr).copy()) return world def add_object(self, obj): if obj in self.objs: err = 'Unable to create object {}.'.format(obj) err += ' Antother object with the same name already exists.' raise ValueError(err) elif obj in self.types: err = 'Unable to create object {}.'.format(obj) err += ' A type with the same name already exists.' raise ValueError(err) elif obj in self.rels: err = 'Unable to create object {}.'.format(obj) err += ' A relation with the same name already exists.' raise ValueError(err) self.objs.add(obj) self.obj_2_types[obj] = set() if obj[0] == '$': self.type_object(obj, obj[1:]) def delete_object(self, obj): if obj not in self.objs: err = 'Unable to delete object {}.'.format(obj) err += 'Object not found.' raise ValueError(err) self.objs.remove(obj) del self.obj_2_types[obj] for typ, objs in self.type_2_objs.items(): if obj in objs: objs.remove(obj) for rel, objs in self.rel_2_objs.items(): if obj in objs: objs.remove(obj) keys = list(self.obj_rel_2_objs.keys()) for k in keys: if k[0] == obj: del self.obj_rel_2_objs[k] def add_type(self, typ): if typ in self.types: err = 'Unable to create type {}.'.format(typ) err += ' Antother type with the same name already exists.' raise ValueError(err) elif typ in self.objs: err = 'Unable to create type {}.'.format(typ) err += ' An object with the same name already exists.' raise ValueError(err) elif typ in self.rels: err = 'Unable to create type {}.'.format(typ) err += ' A relation with the same name already exists.' raise ValueError(err) self.types.add(typ) self.type_2_objs[typ] = set() self.sub_types[typ] = set() self.super_types[typ] = set() def type_type(self, sub_type, super_type, inc=False): if super_type not in self.types: raise ValueError('Unknown type {}.'.format(super_type)) if sub_type not in self.types: raise ValueError('Unknown type {}.'.format(sub_type)) self.sub_types[super_type].add(sub_type) if inc: self.super_types[sub_type].add(super_type) else: self.super_types[sub_type] = set([super_type]) def type_object(self, obj, typ, inc=False): if typ not in self.types: raise ValueError('Unknown type {}.'.format(typ)) if obj not in self.objs: self.add_object(obj) if inc: self.obj_2_types[obj].add(typ) self.type_2_objs[typ].add(obj) else: curr_types = self.obj_2_types[obj] for c_type in curr_types: self.type_2_objs[c_type].remove(obj) self.obj_2_types[obj] = set([typ]) self.type_2_objs[typ] = set([obj]) def untype_type(self, sub_type, super_type=None): if sub_type not in self.types: raise ValueError('Unknown type {}.'.format(sub_type)) if super_type is None: curr_sup_types = self.super_types[sub_type] self.super_types[sub_type] = set() for c_type in curr_sup_types: self.sub_types[c_type].remove(sub_type) else: if super_type not in self.types: raise ValueError('Unknown type {}.'.format(super_type)) if super_type not in self.super_types[sub_type]: err = '{} is not a super type of {}.'.format(super_type, sub_type) raise ValueError(err) self.super_types[sub_type].remove(super_type) self.sub_types[super_type].remove(sub_type) def untype_object(self, obj, typ=None): if typ is None: curr_types = self.obj_2_types[obj] self.obj_2_types[obj] = set() for c_type in curr_types: self.type_2_objs[c_type].remove(obj) else: if typ not in self.types: raise ValueError('Unknown type {}.'.format(typ)) if typ not in self.obj_2_types[obj]: err = 'Object {} is does not belong to type {}.'.format(obj, typ) raise ValueError(err) self.obj_2_types[obj].remove(typ) self.type_2_objs[typ].remove(obj) def delete_type(self, typ): if typ not in self.types: err = 'Unable to delete type {}.'.format(typ) err += 'Type not found.' raise ValueError(err) self.types.remove(typ) objs = self.type_2_objs.pop(typ) for obj in objs: self.obj_2_types[obj].remove(typ) del self.sub_types[typ] del self.super_types[typ] def add_relation(self, rel): if rel in self.rels: err = 'Unable to create relation {}.'.format(rel) err += ' Antother relation with the same name already exists.' raise ValueError(err) elif rel in self.objs: err = 'Unable to create relation {}.'.format(rel) err += ' An object with the same name already exists.' raise ValueError(err) elif rel in self.types: err = 'Unable to create relation {}.'.format(rel) err += ' A type with the same name already exists.' raise ValueError(err) self.rels.add(rel) self.rel_2_objs[rel] = set() def relate_objects(self, rel, obj1, obj2, inc=False): if rel not in self.rels: raise ValueError('Unknown relation: {}.'.format(rel)) if obj1 not in self.objs: if obj1 in self.types: obj1 = '$' + obj1 self.add_object(obj1) else: raise ValueError('Unknown object: {}.'.format(obj1)) if obj2 not in self.objs: if obj2 in self.types: obj2 = '$' + obj2 self.add_object(obj2) else: raise ValueError('Unknown object: {}.'.format(obj2)) self.rel_2_objs[rel].add(obj1) k = (obj1, rel) if inc: if k in self.obj_rel_2_objs: self.obj_rel_2_objs[k].add(obj2) else: self.obj_rel_2_objs[k] = set([obj2]) else: self.obj_rel_2_objs[k] = set([obj2]) def unrelate_objects(self, rel, obj1, obj2=None): if rel not in self.rels: raise ValueError('Unknown relation: {}.'.format(rel)) if obj1 not in self.objs: if obj1 in self.types: obj1 = '$' + obj1 else: raise ValueError('Unknown object: {}.'.format(obj1)) if obj2 is None: self.rel_2_objs[rel].remove(obj1) del self.obj_rel_2_objs[(obj1, rel)] else: if obj2 not in self.objs: if obj2 in self.types: obj2 = '$' + obj2 else: raise ValueError('Unknown object: {}.'.format(obj2)) k = (obj1, rel) if k not in self.obj_rel_2_objs: err = '{} and {} are not related by relation {}.'.format( obj1, obj2, rel ) raise ValueError(err) self.obj_rel_2_objs[k].remove(obj2) if not self.obj_rel_2_objs[k]: self.rel_2_objs[rel].remove(obj1) def delete_relation(self, rel): if rel not in self.rels: err = 'Unable to delete relation {}.'.format(rel) err += 'Relation not found.' raise ValueError(err) self.rels.remove(rel) del self.rel_2_objs[rel] keys = list(self.obj_rel_2_objs.keys()) for k in keys: if k[1] == rel: del self.obj_rel_2_objs[k] def get_code(self): code = [] code.append('# Objects') for obj in self.objs: if obj[0] != '$': code.append('obj ' + obj) code.append('\n# Types') for typ in self.types: code.append('type ' + typ) code.append('\n# Relations') for rel in self.rels: code.append('rel ' + rel) code.append('\n# Object types') for obj, types in self.obj_2_types.items(): if len(types) > 1: suff = '+' else: suff = '' for typ in types: code.append(' '.join([typ + suff, obj])) code.append('\n# Object graph') for (obj1, rel), objs in self.obj_rel_2_objs.items(): if len(objs) > 1: rel = rel + '+' for obj2 in objs: code.append(' '.join([rel, obj1, obj2])) code.append('\n# Type graph') for sup, subs in self.sub_types.items(): for sub in subs: code.append(' '.join([sup, sub])) return '\n'.join(code) def serialize(self): config = {} config['objects'] = list(self.objs) config['types'] = list(self.types) config['relations'] = list(self.rels) object_types = {k: list(v) for (k, v) in self.obj_2_types.items()} config['object_types'] = object_types object_graph = [] for (obj1, rel), objs in self.obj_rel_2_objs.items(): object_graph.append((rel, obj1, list(objs))) config['object_graph'] = object_graph type_graph = {k: list(v) for (k, v) in self.sub_types.items()} config['type_graph'] = type_graph return config @classmethod def deserialize(cls, config): world = cls() for obj in config['objects']: world.add_object(obj) for typ in config['types']: world.add_type(typ) for rel in config['relations']: world.add_relation(rel) for obj, types in config['object_types'].items(): for typ in types: world.type_object(obj, typ) for rel, obj1, objs in config['object_graph']: for obj2 in objs: world.relate_objects(rel, obj1, obj2) for sup, sub in config['type_graph'].copy(): world.type_type(sub, sup) return world def run(self, *args): arg0 = args[0] if arg0 == 'obj': assert len(args) == 2 self.add_object(args[1]) elif arg0 == 'type': assert len(args) == 2 self.add_type(args[1]) elif arg0 == 'rel': assert len(args) == 2 self.add_relation(args[1]) elif arg0 == 'del': assert len(args) == 2 arg1 = args[1] if arg1 in self.objs: self.delete_object(arg1) elif arg1 in self.types: self.delete_type(arg1) elif arg1 in self.rels: self.delete_relation(arg1) else: raise ValueError('Undefined token: {}.'.format(arg1)) elif arg0 in self.types: if len(args) == 2: arg1 = args[1] if arg1 in self.types: self.type_type(arg1, arg0) elif arg1 in self.rels or (arg1[-1] == '+' and arg1[:-1] in self.rels): err = 'Only 1 arg provided for relation {}.'.format(arg1) raise ValueError(err) else: self.type_object(arg1, arg0) elif len(args) == 3: arg1 = args[1] arg2 = args[2] if arg1 not in self.rels: raise ValueError('Unknown relation: {}'.format(arg1)) self.relate_objects(arg1, arg0, arg2) else: raise ValueError('Too many arguments.') elif arg0[-1] == '!' and arg0[:-1] in self.types: assert len(args) == 2 arg1 = args[1] if arg1 in self.types: self.untype_type(arg1, arg0[:-1]) elif arg1 in self.objs: self.untype_object(arg1, arg0[:-1]) else: raise ValueError('Undefined token: {}.'.format(arg1)) elif arg0[-1] == '+' and arg0[:-1] in self.types: assert len(args) == 2 arg1 = args[1] if arg1 in self.types: self.type_type(arg1, arg0[:-1], True) elif arg1 in self.objs: self.type_object(arg1, arg0[:-1],True) elif arg0 in self.rels: assert len(args) == 3 self.relate_objects(arg0, args[1], args[2]) elif arg0[-1] == '+' and arg0[:-1] in self.rels: assert len(args) == 3 self.relate_objects(arg0[:-1], args[1], args[2], inc=True) elif arg0[-1] == '!' and arg0[:-1] in self.rels: if len(args) == 2: self.unrelate_objects(arg0[:-1], args[1]) elif len(args) == 3: self.unrelate_objects(arg0[:-1], args[1], args[2]) else: raise ValueError('Too many arguments.') elif arg0 in self.objs: assert len(args) == 3, 'Expected 3 arguments, got {}.'.format(len(args)) arg1 = args[1] inc = False unrelate = False if arg1[-1] == '+': arg1 = arg1[:-1] inc = True elif arg1[-1] == '!': arg1 = arg1[:-1] unrelate = True if arg1 not in self.rels: raise ValueError('Unknown relation: {}.'.format(arg1)) if unrelate: self.unrelate_objects(arg1, arg0, args[2]) else: self.relate_objects(arg1, arg0, args[2], inc=inc) else: raise ValueError('Invalid syntax: ' + ' '.join(args)) def save(self, path): with open(path, 'w') as f: f.write(str(self.get_code())) @classmethod def load(cls, path): world = cls() with open(path, 'r') as f: for line in f: line = line.strip() while ' ' in line: line = line.replace(' ', ' ') args = line.split(' ') if args and args[0] and args[0][0] != '#': world.run(*args) return world def reset(self): self.__init__()
6bf69e75a507bfb142265dde22017b0261ffa6f9
BigEggStudy/LeetCode-Py
/LeetCode.Test/_0051_0100/Test_058_LengthOfLastWord.py
727
3.5625
4
import unittest import sys sys.path.append('LeetCode/_0051_0100') from _058_LengthOfLastWord import Solution class Test_058_LengthOfLastWord(unittest.TestCase): def test_lengthOfLastWord(self): solution = Solution() self.assertEqual(5, solution.lengthOfLastWord('Hello World')) def test_lengthOfLastWord_empty(self): solution = Solution() self.assertEqual(0, solution.lengthOfLastWord('')) def test_lengthOfLastWord_whitespace(self): solution = Solution() self.assertEqual(0, solution.lengthOfLastWord(' ')) def test_lengthOfLastWord_tailSpace(self): solution = Solution() self.assertEqual(5, solution.lengthOfLastWord('Hello World '))
9844e706bf176360ba3787768f153e1d3579e740
Anjali-225/PythonCrashCourse
/Chapter_10/Pg_275_TIY_10_6.py
413
4.125
4
#10-6 = Addition print("Give me two numbers, and I'll add them.") try: first_number = input("\nEnter the first number: ") second_number = input("Enter the second number: ") except ValueError: print("Please type a number!") else: answer = int(first_number) + int(second_number) print(f"The answer is {answer}") #-------------------------------------------------------------------------------
1cb43ce08db45bc46a042b1e5081ad124c635ee6
jozemaria/Logica-de-programacao-com-Python
/Scrips_PY/35° Melhor_nadador_fun.py
598
3.84375
4
def pega_nome_nadador(dic, tempo): nome = "No identificado" for chave, valor in dic.items(): if valor == tempo: nome = chave return nome return nome tempo_nadador = {} for i in range(3): nome = input('Digite o nome do nadador: ') tempo = float(input('Digite o tempo do nadador: ')) tempo_nadador[nome] = tempo melhor_tempo = min(tempo_nadador.values()) pior_tempo = max(tempo_nadador.values()) best = pega_nome_nadador(tempo_nadador, melhor_tempo) worst = pega_nome_nadador(tempo_nadador, pior_tempo) print(best) print(worst)
b4a60d6ba4849defdf84001ded5f8ba3a1235213
Linuturk/Fightboat
/fightboat.py
6,677
4.125
4
#!/usr/bin/python import random DEBUG = 1 # Debug switch PLAYER_SHIPS = 5 # Number of ships for each player MAX_X = 9 # Grid Dimensions MAX_Y = 9 # Grid Dimensions MAX_SHIPS = MAX_X * MAX_Y # Maximum number of ships that can be placed on the grid STATUS = {'empty': 0, 'hit': 1, 'miss': 2, 'ship': 3} # Possible coordinate status def create_grid(): '''Creates a nested list structure full of 0's.''' return [[STATUS['empty']] * MAX_X for x in range(MAX_Y)] def display_grid(grid): '''Takes a nested list structure as created by create_grid() as the argument. Displays the current status of the grid with appropriate labels and legend.''' count = MAX_Y for coordinate in grid: print count, coordinate count = count - 1 xaxis_label() legend() return None def xaxis_label(): '''Label the xaxis of the grid.''' print '\n ', range(1, MAX_X + 1), '\n' return None def legend(): '''Shows the user what the symbols in the grid mean.''' print STATUS['hit'], '= Hit', STATUS['miss'], '= Miss', STATUS['ship'], '= Ship\n' return None def insert_into_grid(grid, x, y, status): '''Inserts the status passed at the x and y coordinates provided into the grid provided.''' message = 'Inserting %s into grid at (%d,%d)' % (status, x+1, y) debug(message) grid[-y][x] = status return None def random_coordinate(): '''Returns a set of random coordinates inside the grid.''' x = random.choice(range(0, MAX_X)) y = random.choice(range(1, MAX_Y + 1)) return x, y def random_ship_placement(grid): '''Places random ships on the grid.''' if PLAYER_SHIPS > MAX_SHIPS: debug('Too many ships are defined.') else: count = PLAYER_SHIPS while count > 0: x, y = random_coordinate() if grid[-y][x] == 0: insert_into_grid(grid, x, y, STATUS['ship']) count = count - 1 else: message = 'Coordinate duplication for ship placement. Trying again.' debug(message) return None def debug(string): '''Pass a string to print as a debug message if debugging is activated.''' if DEBUG == 1: print 'Debug===>', string return None def player_status(player): '''Takes a player dictionary and shows that player's status.''' print '=' * 80 print player['name'] print '=' * 80 display_grid(player['target']) display_grid(player['home']) return None def still_alive(grid): '''Searches through the grid for a ship. If no ships are found, returns False.''' count = 0 for status in grid: count = count + status.count(STATUS['ship']) if count > 0: return True else: return False def random_shot(gunner, target): '''Fire a random shot at target's home grid. Update the gunner's target grid.''' x, y = random_coordinate() if target['home'][-y][x] == STATUS['ship']: # Sink the ship insert_into_grid(target['home'], x, y, STATUS['hit']) # Record the hit insert_into_grid(gunner['target'], x, y, STATUS['hit']) # Tell the user print '%s hit %s!' % (gunner['name'], target['name']) elif target['home'][-y][x] == STATUS['miss']: # Tell the user that coordinate has already been shot print '%s already tried there.' % (gunner['name']) return random_shot(gunner, target) elif target['home'][-y][x] == STATUS['hit']: # Tell the user the ship is already sunk print '%s already sunk the ship there.' % (gunner['name']) return random_shot(gunner, target) elif target['home'][-y][x] == STATUS['empty']: # Record the miss insert_into_grid(gunner['target'], x, y, STATUS['miss']) # Tell the user print '%s missed %s.' % (gunner['name'], target['name']) return None # Introduction print 'Welcome to Fightboat!' print 'Prepare for carnage!' wants_to_play = 'y' first_run = 1 while wants_to_play == 'y': if first_run == 1: # Define empty dictionaries for each player. p1 = {} p2 = {} # Ask the player's their names, and assign their grids. p1['name'] = raw_input('Player 1\'s name: ') p1['home'] = create_grid() p1['target'] = create_grid() p2['name'] = raw_input('Player 2\'s name: ') p2['home'] = create_grid() p2['target'] = create_grid() # Insert random ships into their home grid. random_ship_placement(p1['home']) random_ship_placement(p2['home']) # Deactivate first run first_run = 0 keepgoing = 1 while keepgoing == 1: # Show each player's status #player_status(p1) #raw_input('Enter to continue . . . ') #player_status(p2) #raw_input('Enter to continue . . . ') # Player 1 attacks random_shot(p1,p2) # Player 2 attacks random_shot(p2,p1) # Still alive? keepgoing = 0 if still_alive(p1['home']) == True and still_alive(p2['home']) == False: print p1['name'], 'Wins!' elif still_alive(p1['home']) == False and still_alive(p2['home']) == True: print p2['name'], 'Wins!' elif still_alive(p1['home']) == False and still_alive(p2['home']) == False: print 'Mutually Assured Destruction!' else: keepgoing = 1 # Show each player's status player_status(p1) raw_input('Enter to continue . . . ') player_status(p2) raw_input('Enter to continue . . . ') # Want to play again? wants_to_play = raw_input('Want to play again? (y/n) ') if wants_to_play == 'y': first_run = 1
97fb7554edd5f81a2c0c2c2aae48df3524a521c5
TBBSparks/Python-Challenge
/PyPoll/Main.py
3,032
3.953125
4
# Code will read a comma separated text file containing election data for Voter ID,County,Candidate # and produce the election results printing to the screen and saving to file # operating system import os # Comma Separated Values import csv # Variables CorreyVotes = 0 LiVotes = 0 KhanVotes = 0 OTooleyVotes = 0 TotVotes = 0 # Path setting (This is the path on local Windows 10 machine given the current working folder) path = os.path.join('Python-Challenge', 'PyPoll', 'Resources', 'election_data.csv') # with to open file and ensure it closes with open(path, newline='') as csvfile: # Comma delimited file definition csvreader = csv.reader(csvfile, delimiter=',') # Deal with header csv_header = next(csvreader) row = next(csvreader) for row in csvreader: # Counting total votes TotVotes += 1 # Counting votes for each candidate if (row[2] == "Correy"): CorreyVotes += 1 elif (row[2] == "Li"): LiVotes += 1 elif (row[2] == "Khan"): KhanVotes += 1 else: OTooleyVotes += 1 # Calculating % votes for each candidate CorreyPerc = CorreyVotes / TotVotes LiPerc = LiVotes / TotVotes KhanPerc = KhanVotes / TotVotes OTooleyPerc = OTooleyVotes / TotVotes # Who is the winner, take the max of votes winner = max(CorreyVotes, LiVotes, KhanVotes, OTooleyVotes) if winner == KhanVotes: winner_name = "Khan" elif winner == CorreyVotes: winner_name = "Correy" elif winner == LiVotes: winner_name = "Li" else: winner_name = "O'Tooley" # Print to screen print(f"Election Results") print(f"---------------------------") print(f"Total Votes: {TotVotes}") print(f"---------------------------") print(f"Khan: {KhanPerc:.3%}({KhanVotes})") print(f"Correy: {CorreyPerc:.3%}({CorreyVotes})") print(f"Li: {LiPerc:.3%}({LiVotes})") print(f"O'Tooley: {OTooleyPerc:.3%}({OTooleyVotes})") print(f"---------------------------") print(f"Winner: {winner_name}") print(f"---------------------------") # Path setting in order to write file (This is the path on local Windows 10 machine given the current working folder) ElectionResult = os.path.join('Python-Challenge', 'PyPoll', 'Analysis', 'election_data_revised.text') # write the output with open(ElectionResult, 'w',) as OutPutFile: OutPutFile.write(f"Election Results\n") OutPutFile.write(f"---------------------------\n") OutPutFile.write(f"Total Votes: {TotVotes}\n") OutPutFile.write(f"---------------------------\n") OutPutFile.write(f"Khan: {KhanPerc:.3%}({KhanVotes})\n") OutPutFile.write(f"Correy: {CorreyPerc:.3%}({CorreyVotes})\n") OutPutFile.write(f"Li: {LiPerc:.3%}({LiVotes})\n") OutPutFile.write(f"O'Tooley: {OTooleyPerc:.3%}({OTooleyVotes})\n") OutPutFile.write(f"---------------------------\n") OutPutFile.write(f"Winner: {winner_name}\n") OutPutFile.write(f"---------------------------\n")
56f75f74c594a617c6a66ada4f583e487df48b18
kkorie/coding-practice
/BOJ/7_문자열/B1316_그룹 단어 체커.py
239
3.59375
4
N = int(input()) for _ in range(N): word = input() checked = [] for w in word: if w not in checked: checked.append(w) else: if w == checked[-1]: continue else: N -= 1 break print(N)
8abb924021478855a6be358ee4c365a526f2de99
suyeon-yang/CP1404practicals
/prac_05/word_occurences.py
391
4.15625
4
words_to_counts = {} input_text = input("Enter a string: ") words = input_text.split() for word in words: word_count = (words_to_counts.get(word, 0)) words_to_counts[word] = word_count + 1 words = list(words_to_counts.keys()) words.sort() max_length = max((len(word) for word in words)) for word in words: print("{:{}} : {}".format(word, max_length, words_to_counts[word]))
4dabb905872e63571e73d3f4a301e10138165ffa
hyo-eun-kim/algorithm-study
/ch22/taeuk/ch22_2_taeuk.py
1,100
3.828125
4
''' 84. 괄호를 삽입하는 여러 가지 방법 숫자와 연산자를 입력받아 가능한 모든 조합의 결과를 출력하라. Example 1: Input: "2-1-1" Output: [0, 2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2 Example 2: Input: "2*3-4*5" Output: [-34, -14, -10, -10, 10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 ''' class Solution: def diffWaysToCompute(self, input: str) -> List[int]: if input.isdigit(): return [int(input)] def compute(left, right, op): result = [] for l in left: for r in right: result.append(eval(str(l) + op + str(r))) return result results = [] for i, value in enumerate(input): if value in "-+*": left = self.diffWaysToCompute(input[:i]) right = self.diffWaysToCompute(input[i+1:]) results.extend(compute(left, right, value)) return results # 64 ms
0708d5eafa1efd41b8d25b43f87d9dd51c8dfcb3
abhishekthukaram/Python-Projects
/BitwiseXOR/missing_number.py
403
4.0625
4
""" Given an array of n−1 integers in the range from 1 to n find the one number that is missing from the array. Example: Input: 1, 5, 2, 6, 4 Answer: 3 """ def missing_number(input_array): n = len(input_array)+1 array_sum = 0 for i in range(1 , n+1): array_sum+=i for number in input_array: array_sum-=number return array_sum print(missing_number([1,5,2,6,4]))
791c33fc93b2292b03addfb642596574098f9425
TapeshN/Portfolio
/Python1_CourseWork/HW07_TapeshNagarwal.py
1,995
3.703125
4
#Tapesh Nagarwal CS100H01 """ Question #1 My Answer: C Correct Answer: C Reason: Because there are two if statements and once a condition is met, 'trueCount' get a value added on """ """ Question #2 My Answer:B Correct Answer:B Reason:simple addition of 2, -1, 0 """ """ Question #3 My Answer:C Correct Answer:B Reason: '[]' is a empty set """ """ Question #4 My Answer:C Correct Answer:C Reason:prints indexes till the stop value """ """ Question #5 My Answer: Correct Answer: Reason: """ """ Question #6 My Answer:B Correct Answer:B Reason:Process of elimination answer had to be an INT value """ """ Question #7 My Answer:B Correct Answer:B Reason:First if conditional was true so it printed then the second was false so it went through with the else statement """ """ Question #8 My Answer:A Correct Answer:A Reason: for loop that checks if the 'letter' is in 'circleLetter's and adds it to empty string 'accum' """ """ Question #9 My Answer:A Correct Answer:A Reason:The first item in the list was a empy list and was true for the first if conditional statment """ """ Question #10 My Answer:A Correct Answer:B Reason: NOT SURE """ """ Question #11 """ def dashes(t, numDashes, dashLength): for i in range(numDashes): t.forward(dashLength) t.up() t.forward(dashLength) t.down() import turtle s = turtle.Screen() shelly = turtle.Turtle() dashes(shelly, 10 , 20) """ Question 12 """ def shortest(textList): shortestLen = len(textList[0]) for string in textList: if len(string) < shortestLen: shortestLen = len(string) return shortestLen beatleLine = ['I', 'am', 'the', 'walrus'] print(shortest(beatleLine)) """ Question 13 """ def nameHasLetter(aLetter): name = input("Enter your name: ") if aLetter in name: print("You name contains the letter: " + aLetter) return True else: print("Your name does not contain the letter: " + aLetter) return False print(nameHasLetter('a'))
a944215323f6532793a5aae6761f9fd00832d672
vishalkumarmg1/Competitive_Coding_2
/Problem_1.py
560
3.515625
4
# Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. # Code: class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: mapping = {} for i in range(len(nums)): if target-nums[i] in mapping: return [mapping[target-nums[i]], i] else: mapping[nums[i]] = i return [-1,-1] # Time Complexity = O(N) # Space Complexity = O(N) # Leetcode accepted: YES. # Difficulty faced : No.
dc4f992f1da17acbe9ad829fce121f89e8bdb3bd
geekhub-python/cycles-VaShu
/task06.py
249
3.703125
4
#!/usr/bin/env python3 # задача 6 """ Выведите на экран таблицу умножения для чисел от 1 до 10. """ for i in range(1, 11): for j in range(1, 11): print("%4d" % (i*j), end='') print()
f31d841bb51cf955080397db195273a32f482708
Maureen-1998DEV/WCPO_Visualization
/data/original data/Data_Curation_Ingestion/db_manipulation/wcpo_tblinstance.py
11,968
3.65625
4
""" Modified on 2020-04-17 @author: Njeri Murage wcpo_tblinstance.py: connect to postgreSQL database create wcpo tables access data from shapefiles and csv write records into the respective PostregSQL database table oad request as a JSON object """ import psycopg2 # PostgreSQL database adapter for the Python from psycopg2.extras import RealDictCursor # Access results returned by a cursor import pandas as pd import json # Needed for conversion to json format import requests # A package that allows to access the web. ################################################## # Connection to Database and Authentication ################################################## host = "gip.itc.utwente.nl" port = 5434 user = "" # insert your username password = "" # insert password database = "wcpo" # database name schema = "public" # insert schema name # Connect to PostgreSQL Database pg = psycopg2.connect(("dbname='%s' user='%s' host='%s' password='%s' port=%d") % (database, user, host, password, port)) cursor = pg.cursor(cursor_factory=RealDictCursor) ################################################## # Creation of Database Tables ################################################## def create_beneftable(): """Function used to create country distribution tables in PostgreSQL database and specified schema.""" print("#####Creating Table########") query = "CREATE TABLE IF NOT EXISTS public.beneficiary" \ "(id serial NOT NULL,country_name character varying,country_code character varying," \ "continent_code character varying, perc_resource numeric, resource_catch numeric, resource_value numeric, " \ "perc_fleet numeric, fleet_catch numeric, fleet_vessels integer, perc_processing numeric, " \ "processing_weight numeric,CONSTRAINT pk_id PRIMARY KEY (id))" cursor.execute(query) pg.commit() print("Finished") def create_markettable(): """Function used to create market distribution tables in PostgreSQL database and specified schema.""" print("#####Creating Table########") query = "CREATE TABLE IF NOT EXISTS public.market" \ "(id serial NOT NULL,region character varying, weight numeric, cases integer, " \ "perc_market numeric, continent_code character varying, CONSTRAINT mk_id PRIMARY KEY (id))" cursor.execute(query) pg.commit() print("Finished") def create_ODtable(): """Function used to create origin destination tables in PostgreSQL database and specified schema.""" print("#####Creating Table########") query = "CREATE TABLE IF NOT EXISTS public.flows" \ "(id serial NOT NULL,origin character varying,origin_councode character varying," \ "origin_contcode character varying, destination character varying,dest_councode character varying," \ "dest_contcode character varying, value_share numeric, stepfrom integer, stepto integer, " \ "origin_benef character varying, dest_benef character varying,CONSTRAINT odk_id PRIMARY KEY (id))" cursor.execute(query) pg.commit() print("Finished") def create_flowtable(): """Function used to create origin destination tables in PostgreSQL database and specified schema.""" print("#####Creating Table########") query = "CREATE TABLE IF NOT EXISTS public.flows" \ "(id serial NOT NULL,origin character varying,origin_councode character varying, countrycode integer," \ "origin_contcode character varying, destination character varying,countrydestcode integer, " \ "dest_councode character varying, dest_contcode character varying, value_share numeric, stepfrom integer, stepto integer, " \ "origin_benef character varying, dest_benef character varying,CONSTRAINT flk_id PRIMARY KEY (id))" cursor.execute(query) pg.commit() print("Finished") beneficiary_tbl = create_beneftable() market_tbl = create_markettable() oddata_tbl = create_ODtable() oddata_tbl = create_flowtable() ####################################################### # Reading and Cleaning Data ####################################################### def read_benef_file(file_path): """Function that reads the csv file creates and returns a list of its records.""" beneficiary = pd.read_csv(file_path, encoding="ISO-8859-1") beneficiary.fillna('0', inplace=True) beneficiary[['PercResource','resourceCatch_metricTons','resourceDollar_value ','PercFleet', 'fleetCatch_mT','PercProcessing','processingCatch_mT']].round(2) beneficiary['fleetVessels'].astype('int') return beneficiary def read_market_file(file_path): """Function that reads the csv file creates and returns a list of its records.""" market = pd.read_csv(file_path, encoding="ISO-8859-1") market.fillna('0', inplace=True) market[['Perc_Market','Weight']].round(2) market['Cases'].astype('int') return market def read_od_file(file_path): """Function that reads the csv file creates and returns a list of its records.""" od_data = pd.read_csv(file_path, encoding="ISO-8859-1") od_data.fillna('0', inplace=True) od_data['Value_share'].round(2) od_data[['StepFrom','StepTo']].astype('int') return od_data def read_flow_file(file_path): """Function that reads the csv file creates and returns a list of its records.""" od_data = pd.read_csv(file_path, encoding="ISO-8859-1") od_data.fillna('0', inplace=True) od_data['Value_share'].round(2) od_data[['StepFrom','StepTo','countrycode','countrydestcode']].astype('int') return od_data beneficiary_data = read_benef_file(r'Z:\projects\WCPO\data\Data_Curation\country_distribution.csv') market_data = read_market_file(r'Z:\projects\WCPO\data\Data_Curation\market_data.csv') od_data = read_od_file(r'Z:\projects\WCPO\data\Data_Curation\od_data.csv') flow_data = read_flow_file(r'Z:\projects\WCPO\data\Data_Curation\flow_revised.csv') # Insert correct file locations ####################################################### # Insert records into database table ####################################################### def insert_benefdata(data): """ Function used to retrieve data from dataframes and insert the values in PostgreSQL areas table. """ data = data.sort_values(by = 'Country') for (index_label, row_series) in data.iterrows(): print('Row Index label : ', index_label) country = row_series['Country'] count_code = row_series['Country_code'] cont_code = row_series['Continent_code'] perc_resource = row_series['PercResource'] resource_catch = row_series['resourceCatch_metricTons'] resource_value = row_series['resourceDollar_value '] perc_fleet = row_series['PercFleet'] fleet_catch = row_series['fleetCatch_mT'] fleet_vessel = row_series['fleetVessels'] perc_process = row_series['PercProcessing'] processing = row_series['processingCatch_mT'] print('Row Content as Series : ', country) print(country.replace("'", "\'")) query = '''INSERT INTO public.beneficiary (country_name,country_code,continent_code,perc_resource, resource_catch,resource_value, perc_fleet, fleet_catch, fleet_vessels, perc_processing, processing_weight) VALUES ('{}','{}','{}',{},{},{},{},{},{},{},{})'''\ .format(country.replace("'", "\'"), count_code, cont_code,perc_resource,resource_catch, resource_value, perc_fleet, fleet_catch,int(fleet_vessel),perc_process,processing) cursor.execute(query) pg.commit() print("END") print() def insert_marketdata(data): """ Function used to retrieve data from dataframes and insert the values in PostgreSQL areas table. """ data = data.sort_values(by = 'Region') for (index_label, row_series) in data.iterrows(): print('Row Index label : ', index_label) region = row_series['Region'] weight = row_series['Weight'] cases = row_series['Cases'] perc_market = row_series['Perc_Market'] cont_code = row_series['Cont_code'] print('Row Content as Series : ', region) print(region.replace("'", "\'")) query = '''INSERT INTO public.market (region,weight,cases,perc_market, continent_code) VALUES ('{}',{},{},{},'{}')'''\ .format(region.replace("'", "\'"), weight, int(cases),perc_market,cont_code) cursor.execute(query) pg.commit() print("END") print() def insert_oddata(data): """ Function used to retrieve data from dataframes and insert the values in PostgreSQL areas table. """ data = data.sort_values(by = 'Origin') for (index_label, row_series) in data.iterrows(): print('Row Index label : ', index_label) origin = row_series['Origin'] orig_countrycode = row_series['orig_countCode'] orig_continentcode = row_series['orig_contCode'] destination = row_series['Destination'] dest_countrycode = row_series['dest_countCode'] dest_continentcode = row_series['dest_contCode'] value_share = row_series['Value_share'] stepfrom = row_series['StepFrom'] stepto = row_series['StepTo'] origin_beneficiary = row_series['O'] dest_beneficiary = row_series['D'] print('Row Content as Series : ', origin) print(origin.replace("'", "\'")) query = '''INSERT INTO public.oddata (origin,origin_councode,origin_contcode,destination, dest_councode, dest_contcode,value_share, stepfrom, stepto, origin_benef, dest_benef) VALUES ('{}','{}','{}','{}','{}','{}',{},{},{},'{}','{}')'''\ .format(origin.replace("'", "\'"), orig_countrycode,orig_continentcode, destination, dest_countrycode,dest_continentcode,value_share,int(stepfrom),int(stepto), origin_beneficiary,dest_beneficiary) cursor.execute(query) pg.commit() print("END") print() def insert_flowdata(data): """ Function used to retrieve data from dataframes and insert the values in PostgreSQL areas table. """ data = data.sort_values(by = 'Origin') for (index_label, row_series) in data.iterrows(): print('Row Index label : ', index_label) origin = row_series['Origin'] orig_countrycode = row_series['orig_countCode'] countrycode = row_series['countrycode'] orig_continentcode = row_series['orig_contcode'] destination = row_series['Destination'] countrydestcode = row_series['countrydestcode'] dest_countrycode = row_series['dest_countCode'] dest_continentcode = row_series['dest_contCode'] value_share = row_series['Value_share'] stepfrom = row_series['StepFrom'] stepto = row_series['StepTo'] origin_beneficiary = row_series['O'] dest_beneficiary = row_series['D'] print('Row Content as Series : ', origin) print(origin.replace("'", "\'")) query = '''INSERT INTO public.flows (origin, origin_councode, countrycode, origin_contcode,destination, countrydestcode, dest_councode, dest_contcode,value_share, stepfrom, stepto, origin_benef, dest_benef) VALUES ('{}','{}',{},'{}','{}',{},'{}','{}',{},{},{},'{}','{}')'''\ .format(origin.replace("'", "\'"), orig_countrycode,countrycode,orig_continentcode, destination,countrydestcode, dest_countrycode,dest_continentcode,value_share,int(stepfrom),int(stepto), origin_beneficiary,dest_beneficiary) cursor.execute(query) pg.commit() print("END") print() insert_benefdata(beneficiary_data) insert_marketdata(market_data) insert_oddata(od_data) insert_flowdata(flow_data) #################### End ###########################
a42a6983d92f5774ef39ea996640a28850a2f454
midhunsezhi/Pacman
/search.py
7,115
4
4
""" In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class). You do not need to change anything in this class, ever. """ def getStartState(self): """ Returns the start state for the search problem """ util.raiseNotDefined() def isGoalState(self, state): """ state: Search state Returns True if and only if the state is a valid goal state """ util.raiseNotDefined() def getSuccessors(self, state): """ state: Search state For a given state, this should return a list of triples, (successor, action, stepCost), where 'successor' is a successor to the current state, 'action' is the action required to get there, and 'stepCost' is the incremental cost of expanding to that successor """ util.raiseNotDefined() def getCostOfActions(self, actions): """ actions: A list of actions to take This method returns the total cost of a particular sequence of actions. The sequence must be composed of legal moves """ util.raiseNotDefined() def tinyMazeSearch(problem): """ Returns a sequence of moves that solves tinyMaze. For any other maze, the sequence of moves will be incorrect, so only use this for tinyMaze """ from game import Directions s = Directions.SOUTH w = Directions.WEST return [s,s,w,s,w,w,s,w] def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "dfs" print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ explored = set() frontier = [] start_state = problem.getStartState() frontier.append(start_state) parent_hash = {} parent_hash[start_state] = (None, None) def get_path(state): path_stack = util.Stack() actions = [] current = state while parent_hash[current][0] is not None: path_stack.push(parent_hash[current][0]) current = parent_hash[current][1] while not path_stack.isEmpty(): actions.append(path_stack.pop()) return actions while len(frontier): node = frontier.pop() if problem.isGoalState(node): return get_path(node) explored.add(node) for state, action, _ in problem.getSuccessors(node): if state not in explored and state not in frontier: parent_hash[state] = (action, node) frontier.append(state) def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. [2nd Edition: p 73, 3rd Edition: p 82] """ explored = set() frontier = util.Queue() start_state = problem.getStartState() frontier.push(start_state) parent_hash = {} parent_hash[start_state] = (None, None) def get_path(state): path_stack = util.Stack() actions = [] current = state while parent_hash[current][0] is not None: path_stack.push(parent_hash[current][0]) current = parent_hash[current][1] while not path_stack.isEmpty(): actions.append(path_stack.pop()) return actions while not frontier.isEmpty(): node = frontier.pop() if problem.isGoalState(node): return get_path(node) explored.add(node) for state, action, _ in problem.getSuccessors(node): if state not in explored and state not in frontier.list: parent_hash[state] = (action, node) frontier.push(state) def uniformCostSearch(problem): "Search the node of least total cost first. " start_state = problem.getStartState() parent_hash = {} parent_hash[start_state] = (None, None, 0) def get_priority(state): return parent_hash[state][2] def get_path(state): path_stack = util.Stack() actions = [] current = state while parent_hash[current][0] is not None: path_stack.push(parent_hash[current][0]) current = parent_hash[current][1] while not path_stack.isEmpty(): actions.append(path_stack.pop()) return actions explored = set() frontier = util.PriorityQueueWithFunction(get_priority) frontier.push(start_state) while not frontier.isEmpty(): node = frontier.pop() if problem.isGoalState(node): return get_path(node) explored.add(node) for state, action, cost in problem.getSuccessors(node): if state not in explored and state not in frontier.heap: parent_hash[state] = (action, node, parent_hash[node][2] + cost) frontier.push(state) def nullHeuristic(state, problem=None): """ A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. """ return 0 def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" start_state = problem.getStartState() parent_hash = {} parent_hash[start_state] = (None, None, 0) #goal = problem.goal def get_priority(state): return parent_hash[state][2] + heuristic(state, problem) def get_path(state): path_stack = util.Stack() actions = [] current = state while parent_hash[current][0] is not None: path_stack.push(parent_hash[current][0]) current = parent_hash[current][1] while not path_stack.isEmpty(): actions.append(path_stack.pop()) return actions explored = set() frontier = util.PriorityQueueWithFunction(get_priority) frontier.push(start_state) while not frontier.isEmpty(): node = frontier.pop() if problem.isGoalState(node): return get_path(node) explored.add(node) for state, action, cost in problem.getSuccessors(node): if state not in explored and state not in frontier.heap: parent_hash[state] = (action, node, parent_hash[node][2] + cost) frontier.push(state) # Abbreviations bfs = breadthFirstSearch dfs = depthFirstSearch astar = aStarSearch ucs = uniformCostSearch
e5a3bd3b9fa4eb0c3412230c44e00890d43a7a63
ConorJamesLeahy/ISE172---Lab2
/exercise1.py
2,275
4.5625
5
""" Create a display surface and caption it. Download an image of a small ball and import that image into your program. Create a horizontal ground of some thickness (something similar to what we saw in the aliens game). Let the initial position of this ball be on this ground. Write code such that the ball bounces between this ground and the top boundary of your display surface. That is, the ball keeps bouncing up and down and up and down and (you guessed it ;-)) Note: Try to play around with colors as well. Also play with the frame speed. Hint: Recall that any action can be performed by writing code for various events. How to bounce the ball once it hits the ground or the boundary? """ import pygame def main(): #Write your pygame code (the "while" loop) in this "main" function. #initializa the pygagme pygame.init() #create the screen screen = pygame.display.set_mode((800,500)) #Title and Icon pygame.display.set_caption("Ball Bounce") icon= pygame.image.load('invader.png') pygame.display.set_icon(icon) #Not sure if this works for macs :( #player ballImg = pygame.image.load('ball.png') ballX = 300 ballY = 100 ballY_change = 5 orange = (255, 140 , 0) def ball(x,y): screen.blit(ballImg, (x, y)) #Game Loop running = True while running: # Needs to be called after screen fill because it would overwrite screen.fill((255, 255, 255)) #Arguments are red, green, blue pygame.draw.rect(screen, orange, [0, 0, 20, 600], 0) #left side pygame.draw.rect(screen, orange, [0, 0, 800, 20], 0) #ceiling pygame.draw.rect(screen, orange, [0, 480, 800, 20], 0) #ground pygame.draw.rect(screen, orange, [780, 0, 20, 1000], 0) # right side for event in pygame.event.get(): #print(event) if event.type == pygame.QUIT: running = False ballY += ballY_change if ballY <= 20: ballY = 20 ballY_change = 5 elif ballY >= 290: ballY = 290 ballY_change = -5 ball(ballX, ballY) pygame.display.update() if __name__ == '__main__': main()
e471be8621d19a7854ed267a6159a6c82dca9fb6
SSevenTwo/alieninvasion_game
/alien_invasion/button.py
1,424
3.84375
4
import pygame.font class Button(): """Class for creating buttons""" def __init__(self,settings,screen,message): """Initializes button attributes""" self.screen = screen self.settings = settings self.screen_rect = screen.get_rect() #Dimensions of the buttton self.width = 200 self.height = 50 self.button_color = (0,0,0) self.text_color = (255,255,255) self.font = pygame.font.SysFont(None,48) #Button's rect self.rect = pygame.Rect(0,0,self.width,self.height) self.rect.center = self.screen_rect.center #Creating the button image self.prep_msg(message) def prep_msg(self, msg): """Turns message into a rendered image""" #The true is for anti aliasing. Can add an extra argument after for highlight color. self.image = self.font.render(msg,True,self.text_color) #We must first create a rect for the image, then we modify it self.image_rect = self.image.get_rect() self.image_rect.center = self.rect.center def draw_button(self): """Draws the button on the screen""" #The first line is to make the square of the button. self.screen.fill(self.button_color,self.rect) self.screen.blit(self.image,self.image_rect)
e17712faf55f986791c1e5ff828698fb750bb205
RahatIbnRafiq/leetcodeProblems
/Hash Table Problems/648. Replace Words.py
619
3.703125
4
class Solution(object): def replaceWords(self, roots, sentence): _trie = lambda: collections.defaultdict(_trie) trie = _trie() END = True for root in roots: cur = trie for letter in root: cur = cur[letter] cur[END] = root def replace(word): cur = trie for letter in word: if letter not in cur: break cur = cur[letter] if END in cur: return cur[END] return word return " ".join(map(replace, sentence.split()))
1f913f51a2649820350c2d5ecee0973fff896cc3
eshlykov/junk
/school-31/coding/ifmo/ifmo11-2013-2.py
851
3.78125
4
# def coffee(line, a, b, c): # return line == a or line == b or line == c # ans = 1000 # for a in range(1, 20): # for b in range(a + 1, 20): # for c in range(b + 1, 20): # n = 1 # увеличение на каждую строчку # t = 0 # прошло времени # tc = 1 # строка перед последней чашкой # for line in range(1, 21): # t += 1 + n * (line - tc) # if coffee(line, a, b, c): # n += 1 # tc = line + 1 # t += 5 # ans = min(t, ans) # print(t, a, b, c) # print(ans) def print_answer(n): for a in range(1, 101): for b in range(1, 101): c = (a ** n + b ** n) ** (1.0 / n) if int(c) == c and a != b and a != c and b!= c: print(a, b, int(c)) return print(-1) n = int(input()) print_answer(n)
7d609ad7966d1497ed729d7baf40e90c6ea3ee42
sujitdhamale/Python
/0903_regex_replace.py
669
3.671875
4
#!/usr/bin/python #0903_regex_replace.py by Sujit Dhamale #to Understanding regular expression and Replacing with regular expressions import re def main(): fh=open("0903_data.txt") print("\n###############Search and replace using re.sub()") for line in fh.readlines(): print(re.sub('python', '#python3#',line)) print("\n###############Search and replace using re.search() and re.repalce() ") fh.seek(0) for line in fh.readlines(): match=re.search('python', line) if(match): print(line.replace(match.group(),'#python3#')) if __name__ == "__main__": main()
a5b9947fffd29d60361634458d45bae2b9fb23de
UthejKumar/PythonExamples
/Bank Application/bank_operations.py
1,379
4.09375
4
''' "Bank Operations" module ~ by Uthej Kumar ''' import transaction as trans #Taking the user's action choice and performing the corresponding bank operation. def bank_operations(acc_balance): print("\nPlease choose an action to perform:") print("""1. Check Balance 2. Deposit Amount into Account 3. Withdraw Money from Account 4. Close Your Account 5. Exit""") while True: actn_chosen = int(input(">")) if 1 <= actn_chosen <= 5: if actn_chosen == 1: acc_balance = trans.balance_func(acc_balance) print("\nYour ACCOUNT BALANCE is: Rs.%.2f" % acc_balance) bank_operations(acc_balance) elif actn_chosen == 2: acc_balance = trans.deposit_func(acc_balance) print("\nYour UPDATED BALANCE is Rs.%.2f" % acc_balance) bank_operations(acc_balance) elif actn_chosen == 3: acc_balance = trans.withdraw_func(acc_balance) print("UPDATED ACCOUNT BALANCE: Rs.%.2f" % acc_balance) bank_operations(acc_balance) elif actn_chosen == 4: boolean = trans.close_func() if boolean == True: bank_operations(acc_balance) elif actn_chosen == 5: exit() break
42398714bcced1685c8da9e244cdc845057f2755
souravs17031999/100dayscodingchallenge
/binary trees/Max_path_sum_any_node.py
2,563
4.34375
4
# Program to compute maximum path sum through any two node in the binary tree. # Approach : # IDEA: First, we have to think about three possibilities that may occur in a binary tree, like max sum # may go through root, or may not go through root, now if not going through root, then it may be there, # that max sum is formed using only left subtree or it may be there max sum may be formed using right subtree # Now, it maybe possible that the sum we choose for going through the root maybe max of following four options: # * root # * root + root.left # * root + root.right # * root + left + right # The above four cases result from the observation that the binary tree consists of negative numbers also, # so, let' say that left subtree contains negative numbers and so we basically will not consider left branch # anymore, and choose from remaining any three of them, similarly for other three options for this category. # Now, this is for first case when we consider going through root, now similary we can consider for left subtree and right subtree and get the overall max from the main three options we discovered. # NOTE : since we have to find maximum distance between any two give node, then we follow # bottom up approach postorder type approach. # We recur for left first, then recur right and now node pair is processed and we update # pair tuple with (branchsum, maxsum). # ------------------------------- # 1 # / \ # 2 3 # / \ # 4 5 # -------------------------------- # IT CAN BE ALSO BE SOLVED USING DP IN 0(N) WHICH IS DISCUSSED IN DP SECTION # ---------------------------------- class Node: def __init__(self, data): self.left = None self.right = None self.data = data class Pair: def __init__(self): self.branchsum = 0 self.maxsum = 0 def maxSumPath(root): p = Pair() if root == None: return p left = maxSumPath(root.left) right = maxSumPath(root.right) op1, op2, op3, op4 = root.data, left.branchsum + root.data, right.branchsum + root.data, root.data + left.branchsum + right.branchsum current_ans_through_root = max(op1, max(op2, max(op3, op4))) p.branchsum = max(left.branchsum, max(right.branchsum, 0)) + root.data p.maxsum = max(left.maxsum, max(right.maxsum, current_ans_through_root)) return p if __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(maxSumPath(root).maxsum)
48176be4999d80238a5dcc511517f507149ecc22
Rmj009/Flask-API
/utils/ctest.py
164
3.65625
4
def sum1(n_input): #n = [int(eval(i)) for i in input()] # print((n+1)*n/2) n = eval(n_input) total = (n+1)*n/2 # print(round(total)) return round(total)
0aa489d3f0991b5327cdf0eee5aeb3785ac4f1df
Rhange/BOJ_PS
/01.IO/2445.py
333
3.671875
4
def amazing_star_shape(n, init_n): stars = '*'*(init_n-n+1) blank = ' '*(n-1)*2 if n == 1: print(f"{stars}{blank}{stars}") return 0 else: print(f"{stars}{blank}{stars}") amazing_star_shape(n-1, init_n) print(f"{stars}{blank}{stars}") return 0 n = int(input()) init_n = n amazing_star_shape(n, init_n)
221dc61f2adfe2f886cfc0b598dcb0feb67eb4ea
Leejieun3001/python_study
/workspace/example20_class.py
607
4.0625
4
""" static(정적) 함수: java 처럼 많이 사용하지 않는다. 클래스 안에서 선언하지만 메모리 영역이 달라서 객체명으로 접근하지 않고 클래스 명으로 접근하지 않고 클래스 명으로 접근. """ class Yonsan: def plus(self,a,b): return a+b @staticmethod def minus(a,b): return a-b def multiply(self, a,b): return a*b @staticmethod def divde(a,b): return a/b yonsan = Yonsan() print("plus", yonsan.plus(10,20)) print("minus:" , Yonsan.minus(77,1)) print("plus", yonsan.multiply(1,2)) print("plus", yonsan.divde(1,2))
35ff2f9b7a42cd586fc72a408d4ba7b01d5f4b33
lavrinovu4/image_sort
/test/file_attribute/sort_by_name.py
746
3.625
4
#!/usr/bin/python3 import os # format name: "YYYYMMDD_XXXXXX" def parse(file_split_name): if (file_split_name[1] == "jpg"): print("Parsing...") field_name = file_split_name[0].split("_") date = field_name[0] if (len(date) == 8): year = date[0:4] month = date[4:6] day = date[6:8] return [year, month, day] else: return 0 for filename in os.listdir('.'): print(filename) if(len(filename) == 19): file_split_name = filename.split('.') # is file? if (len(file_split_name) > 1): res = parse(file_split_name) if (res != 0): print(res)
876d200018f861ee82891891c222ad552fd9f40e
IuryBRIGNOLI/tarefas130921
/p3.py
738
3.90625
4
contador = int(0) um = input("Você telefonou para vitíma ? ") if(um =="sim" or "Sim" or "SIM"): (contador+1) dois = input("Esteve no local do crime ?") if(dois == "Sim " or "sim " or "SIM"): (contador+1) tres = input("Mora perto da vítima ?") if(tres == "sim " or "SIM " or "Sim"): (contador+1) quatro = input("Devia para a vítima ?") if(quatro == "sim" or "SIM" or "Sim" ): (contador+1) cinco = input("Já trabalhou com a vítima ?") if(cinco == "sim " or "Sim" or "SIM"): (contador+1) if(contador>=2): print("Você é suspeita ") if (contador>=3 and contador<=4): print("Você é cúmplice") if (contador>=5): print("Você é o assassino") if (contador<1): print("Você é inocente")
e32ee66f21f26f525685a70fab92b9ef4f3e5b59
b97822302002/Leetcode_ValidSudoku
/main.py
2,093
3.6875
4
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ for i in range (0, 9): if self.row(board, i) == False: return False for j in range (0, 9): if self.col(board, j) == False: return False for i in range(0, len(board), 3): for j in range(0, len(board[i]), 3): if self.squ(board, i, i+3, j, j+3) == False: return False return True def row(self, board, i): checkList = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] for j in range(0, 9): if board[i][j] == ".": continue elif board[i][j] in checkList: checkList.remove(board[i][j]) else: return False return True def col(self, board, j): checkList = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] for i in range(0, 9): if board[i][j] == ".": continue elif board[i][j] in checkList: checkList.remove(board[i][j]) else: return False return True def squ( self, board, istart, iend, jstart, jend ): checkList = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] for i in range(istart, iend): for j in range(jstart, jend): if board[i][j] == ".": continue elif board[i][j] in checkList: checkList.remove(board[i][j]) else: return False return True print(Solution().isValidSudoku([ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ]))
44e9bc05462364425e2cd9a8c55ef4e7b16c06f7
Ayeeta/python_pep8_tyr
/shop.py
1,917
4.15625
4
'''Shopping Cart class has methods to add, remove items from shopping cart and also check balance ''' class ShoppingCart(object): '''class contains methods to add, remove from cart and check bal''' def __init__(self): self.total = 0 self.items = {} def add_item(self, item_name, quantity, price): '''Adds item to the shopping cart''' if quantity > 0 and price > 0: cost = price * quantity self.total += cost self.items[item_name] = quantity def remove_item(self, item_name, quantity, price): '''Removes items from the shopping cart''' if item_name in self.items: cost = quantity * price if quantity < self.items[item_name]: self.total -= cost self.items[item_name] = self.items[item_name] - quantity elif quantity == self.items[item_name]: del self.items[item_name] self.total -= cost elif quantity > self.items[item_name]: real_cost = self.items[item_name] * price del self.items[item_name] self.total -= real_cost def checkout(self, cash_paid): '''method to check available balance''' if isinstance(cash_paid, int): balance = 0 if cash_paid > self.total: balance = cash_paid - self.total return balance else: return "Cash paid not enough" else: raise TypeError("Check your values entered") class Shop(ShoppingCart): '''this class reduces items from the shop''' def __init__(self): ShoppingCart.__init__(self) self.quantity = 100 def remove_item(self, item_name=False, quantity=False, price=False): '''method reduces quantity of an item in the shop''' self.quantity -= 1
ecd25c667a954311681f18b7dac803b28d3349ac
MU-Enigma/Hacktoberfest_2021
/Problems/Level-1/Problem_1/LikithGannarapu_Problem1.py
247
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 29 21:56:36 2021 @author: likhitgannarapu """ n = int(input()) for i in range(n): t = input() swap_t = t.swapcase() rev_swap_t= swap_t[::-1] print(rev_swap_t)
7ce11d6e7c36460818ac45f0b9b1eca59982ed5f
ebushi/my_leetcode
/ValidParentheses.py
1,492
3.625
4
class Solution(object): def isValid(self, s): def filte(s): if s == '(' or s == ')' or s == '[' or s == ']' or s == '{' or s == '}': return True else: return False filted_s = list(filter(filte, s)) print(filted_s) s1 = [] while len(filted_s) != 0: if filted_s[0] == '{' or filted_s[0] == '[' or filted_s[0] == '(': s1.append(filted_s.pop(0)) else: if len(s1) == 0: return False else: if filted_s[0] == '}': if s1[-1] == '{': s1.pop() filted_s.pop(0) continue else: return False if filted_s[0] == ']': if s1[-1] == '[': s1.pop() filted_s.pop(0) continue else: return False if filted_s[0] == ')': if s1[-1] == '(': s1.pop() filted_s.pop(0) continue else: return False if len(s1) != 0: return False else: return True
33ffd087f3698b8e719d3973dbbccefd18243623
deepaksng29/computer-science-a2
/Worsheet Task/fishTask4.py
579
3.65625
4
class car: def __init__(self, s, n): self.mileage = 0 self.registration = s self.make = n self.dateOfInspection = '' def getReg(self): return self.registration def getMake(self): return self.make def getMileage(self): return self.mileage def getDateOfInspection(self): return self.dateofinspection def setDateOfInspection(self, mileage, dateofinspection): self.mileage = mileage self.dateOfInspection = dateofinspection car1 = car("DAS", "BMW") print(car1.getReg)
218fa87beb8fcc2c9192cb38e99158c2d0d6f65b
joncoop/password-storage
/login.py
2,632
3.625
4
import hashlib import random import time #import getpass # Settings DATA_FILE = 'users.txt' USE_SALT = True SALT_LENGTH = 32 UNSUCCESSFUL_LOGIN_DELAY = 2 def menu(): while True: print("1. Create account") print("2. Login") print("3. Quit") choice = input("> ") if choice in ['1', '2', '3']: return choice def get_user_info(user_name): with open(DATA_FILE, 'r') as f: for line in f: line = line.strip() user_info = line.split(',') name = user_info[0] if user_name == name: return user_info return None def login(): user_name = input('Username: ') password = input('Password: ') #password = getpass.getpass('Password: ') user_info = get_user_info(user_name) if user_info is not None: salt = user_info[1] hashed_pw = user_info[2] if generate_hash(password + salt) == hashed_pw: return True, user_info else: return False, None def generate_salt(): hex_chars = '0123456789abcdef' salt = '' for i in range(SALT_LENGTH): salt += random.choice(hex_chars) return salt def generate_hash(string): result = hashlib.sha256(string.encode()) return result.hexdigest() def create_account(): user_name = input('Username: ') password = input('Password: ') salt = '' if USE_SALT: salt = generate_salt() password += salt hashed_pass = generate_hash(password) with open('users.txt', 'a') as f: f.write(user_name + ',' + salt + ',' + hashed_pass + '\n') def do_secret_stuff(user_info): name = user_info[0] print('You can type anything here, ' + name + ' When your done, type \'logout\'.') logged_in = True while logged_in: command = input('> ') if command == 'logout': logged_in = False def run(): running = True while running: choice = menu() if choice == '1': create_account() elif choice == '2': success, user_info = login() if success: print('Access Granted!') do_secret_stuff(user_info) else: time.sleep(UNSUCCESSFUL_LOGIN_DELAY) print('Access Denied!') elif choice == '3': running = False if __name__ == "__main__": run()
313cfaba59dee11fc5905681d73ec4930783b71c
guilhermefreitas3/IA
/ep01_aventureiro.py
5,590
3.84375
4
from random import * import numpy as np import math #------------------------------------------------Entrada do Usuario m = int(input("Digite a largura do mapa:")) n = int(input("Digite a altura do mapa:")) print ("\n") #------------------------------------------------Constantes _BARREIRA = 0 _AGUA = 3 _TERRA = 1 _MOVEDICA = 6 #------------------------------------------------Classes class Estado: def __init__(self,x,y,estadoPai=None,movimento=None,nivel=0,mapa=None): self.x = x #posicao x self.y = y #posicao y mapa.calcDistancia(x,y) self.a = mapa.getCusto(x,y)+mapa.getH(x,y) #valor heuristica self.estadoPai = estadoPai self.nivel = nivel if estadoPai: self.acumulado = estadoPai.acumulado+self.a #self.mapa = estadoPai.mapa else: self.acumulado = self.a self.visitado = False def movimentar(self,movimento,mapa,nivel): x = self.x + (movimento.x) y = self.y + (movimento.y) #print("mov("+str(movimento.x)+","+str(movimento.y)+")") #validar fronteiras if x < 0 or x >=m or y < 0 or y >=n: #print("Invalido - Fronteiras") return None a = mapa.getCusto(x,y)+mapa.getH(x,y) #validar barreiras if mapa.getCusto(x,y)==_BARREIRA: #print("Invalido - Barreira") return None #verificar se já existe um caminho para este ponto com menor acumulo for ponto in fila: if ponto.x == x and ponto.y == y: if ponto.acumulado > self.acumulado+a: fila[fila.index(ponto)]=self #print("Invalido - repetido") return None estado_temp = Estado(x,y,self,movimento,nivel,mapa) return estado_temp def imprimir(self,completo=False): saida="["+str(self.nivel)+"::("+str(self.x)+","+str(self.y)+")::"+str(self.a)+"/"+str(self.acumulado)+"::"+str(self.visitado)+"]" if self.estadoPai and completo: saida = self.estadoPai.imprimir(True)+" > "+saida return saida def igual(self,x,y): if self.x == x and self.y == y: return 1 else: return 0 class Movimento: def __init__(self,x,y): self.x = x self.y = y def imprimir(self): return str(self.x)+str(self.y) class Mapa: def __init__(self,m,n): self.m = m self.n = n #self.objetivo = None #self.objetivo = Estado(m-1,n-1,None,None,None,self) tipos = [_BARREIRA,_AGUA,_MOVEDICA,_TERRA] lista = [] for i in range(m): for j in range(n): codPosicao = m*i+j if codPosicao==0 or codPosicao==m*n-1: lista.append(_TERRA) else: lista.append(tipos[randrange(0,4)]) #distancia = math.sqrt(pow(m-1-i,2)+pow(n-1-j,2)) #print("distancia("+str(i)+","+str(j)+")="+str(distancia)) #lista.append(distancia) self.posicao = np.array(lista) self.posicao = self.posicao.reshape(m,n) def getCusto(self,x,y): return self.posicao[x,y] def calcDistancia(self,x,y): #print("calc("+str(x)+","+str(y)+")") catetox = pow(m-1-x,2) catetoy = pow(n-1-y,2) #print("catetos("+str(x)+","+str(y)+") = "+str(catetox)+","+str(catetoy)) distancia = math.sqrt(catetox+catetoy) self.h = distancia #print("distancia("+str(x)+","+str(y)+")="+str(distancia)) #return self.getCusto+distancia def getH(self,x,y): return self.h def criterioClassificacao(e): return e.acumulado def imprimirFila(nivel): s="" for a in fila: #if a.nivel == nivel: s+=a.imprimir() print("Fila="+s) def popFila(nivel): for a in fila: if a.nivel == nivel and a.visitado == False: a.visitado = True return a return None mapa = Mapa(m,n) estadoInicial = Estado(0,0,None,None,0,mapa) fila = [] #gerar movimentos possiveis movimentosPossiveis = [ Movimento(0,1)#norte ,Movimento(1,1)#nordeste ,Movimento(1,0)#leste ,Movimento(1,-1)#sudeste ,Movimento(0,-1)#sul ,Movimento(-1,-1)#sudoeste ,Movimento(-1,0)#oeste ,Movimento(-1,1)#noroeste ] def busca(estado,mapa): print("---------------"+estado.imprimir(True)) #print(mapa.posicao) for movimento in movimentosPossiveis: estado_temp = estado.movimentar(movimento,mapa,estado.nivel+1) if estado_temp == None: continue if estado_temp.igual(m-1,n-1): print("Resultado:"+estado_temp.imprimir(True)) return estado_temp print(str(estado.x)+","+str(estado.y)+">>>"+str(movimento.x)+","+str(movimento.y)+"="+str(estado_temp.x)+","+str(estado_temp.y)) #fila.insert(0,estado_temp) fila.append(estado_temp) fila.sort(key=criterioClassificacao) imprimirFila(estado.nivel+1) r = None while r == None: estado=popFila(estado.nivel+1) if not(estado): return None r = busca(estado,mapa) return r print(mapa.posicao) busca(estadoInicial,mapa) print(mapa.posicao)
ba3d8879550bfbc73aea35f6a692c5c2d5ed3ffd
wherby/SOMEVSProject
/Python Doc/GeneratorSection/itertools/itertools.py
546
3.71875
4
import itertools b1=[1,2,3,4,5,6,7,8,9,10] y=list(itertools.islice(b1,3)) def fib(): x,y=0,1 while True: yield x x,y=y,x+y def peel(iterable,arg_cnt=1): iterator=iter(iterable) for num in range(arg_cnt): yield iterator.next() yield iterator if __name__=="__main__": print y a=fib() print a.next() print list(itertools.islice(a,10)) b,c,d=peel(a,2) print b,c,d # itertools.islice could silce both array and infinite generator # using peel to unpack the iterator
9dfd39e99a66bce5625119505293453c987876b9
pmakukha1989/learn_python
/week_2_homework/str_compare.py
435
3.890625
4
print ('input str_1') input_str_1 = input () print ('intup str_2') input_str_2 = input () def compare_str (str_1, str_2): if type(str_1) == str and type(str_2) ==str : if str_1 == str_2: return '1' elif len (str_1) > len(str_2): return '2' elif str_1 != str_2 and str_2 =='learn': return '3' else: return '0' print (compare_str(input_str_1, input_str_2))
0bb330f1b444a801b20f62645c9bc7a5998559d0
iExad/Pifagor-hex_table
/Pifagor_dec-table.py
106
3.8125
4
for i in range(1,10): for j in range(1,10): print ('{:3}'.format(i * j), end=" ") print()
ec47e5aef504d04ce68968c8ac00e916d5365026
stormvirux/Nim
/Nim.py
3,756
4.03125
4
from random import randint, random from time import sleep board_size = 3 board_bin=[] def show_board(board): columnformat = "{0:5}".format lineformat = "\n{0:10}: {1}".format cols = map(columnformat, range(1, len(board) + 1)) show_text(lineformat("column", ''.join(cols))) cols = map(columnformat, board) show_text(lineformat("pieces", ''.join(cols))) show_text("\n") def show_text(s): print s def calcbest(board_bin,xorsum): newbin=[] for i in range(board_size): newbin.append(board_bin[i]^xorsum) for i in range(board_size): if newbin[i]<board_bin[i]: newbin[i]=1 else: newbin[i]=0 return newbin def user1(board,board_bin,column_size): while True: show_text("User1 Turn") xorsum=None xorsum=board_bin[0]^board_bin[1]^board_bin[2] if (xorsum): print "You have chance of winning" else: print "You will loose unless you a move such that Xor sum of remaining gives non zero" show_text("The best move would be in column:") a=calcbest(board_bin,xorsum) for i in range(len(a)): if(a[i]!=0): show_text(i+1) show_text("The best number to remove is:") show_text(int(str(xorsum),2)) show_text("Please enter the column to decrease(1 to 3)") col=int(raw_input().strip()) show_text("Please enter the amount to be removed") num=int(raw_input().strip()) if 1 <= num <= column_size[col-1] and 1 <= col <= board_size: break show_text("Please enter correct values") return col,num def user2(board,board_bin,column_size): while True: show_text("User2 Turn") xorsum=None xorsum=board_bin[0]^board_bin[1]^board_bin[2] if (xorsum): print "You have chance of winning" else: print "You will loose unless you a move such that Xor sum of remaining gives non zero" show_text("The best move would be in column:") a=calcbest(board_bin,xorsum) for i in range(len(a)): if(a[i]!=0): show_text(i+1) show_text("The best number to remove is:") show_text(int(str(xorsum),2)) show_text("Please enter the column to decrease(1 to 3)") col=int(raw_input().strip()) show_text("Please enter the amount to be removed") num=int(raw_input().strip()) if 1 <= num <= column_size[col-1] and 1 <= col <= board_size : break show_text("Please enter correct values") return col,num def nim(): column_size=[randint(1,7) for i in range(board_size)] board = [column_size[n] for n in range(board_size)] show_board(board) board_bin=["{0:b}".format(column_size[i]) for i in range(board_size)] show_board(board_bin) board_bin=[int(board_bin[i]) for i in range(board_size)] turn,user_turn=(user1,True) if random() < 0.5 else (user2,False) while True: column,num=turn(board,board_bin,column_size) board[column-1]-=num board_bin[column-1]="{0:b}".format(board[column-1]) board_bin[column-1]= int(board_bin[column-1]) show_board(board) if sum(board)==0: break turn = user2 if turn == user1 else user1 show_board(board) show_text("\nThere are no pieces remaining, ") show_text("User 1 wins!\n" if turn == user1 else "User2 Wins win!\n") sleep(0.5) sleep(1.5) show_text("\n\nBye.") if __name__ == '__main__': nim()
5784a46f7b09fd6281e49625eb20b108e38e5f5b
jyash28/Python-practice
/chapter5(lists)/reverse2.py
198
4.03125
4
def reverse_list(l): r_list =[] for i in range(len(l)): popped_item = l.pop() r_list.append(popped_item) return r_list numbers =[1,2,3,4] print(reverse_list(numbers))
d24287daf3d3dc34a5536fa522288c9d8b9198ac
elmo366036/Fundamentals-of-Computing
/Algorithmic Thinking 2/Algorithms/text_alignment.py
8,201
3.890625
4
'''Performs global and local alignment of two text strings Provide an alphabet, diag_score, off_diag_score, dash_score, and two strings to compare diag_score is when the characters are the same off_diag_score is when two characters are not the same dash_score is when where a character maps to a dash Includes a function to generate a null distribution ''' def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score): ''' build scoring matrix as a dictionary of dictionaries ''' scoring_matrix = dict((dummy_a, {}) for dummy_a in alphabet) scoring_matrix["-"] = {} for dummy_a in alphabet: for dummy_b in alphabet: if dummy_a == dummy_b: scoring_matrix[dummy_a][dummy_b] = diag_score else: scoring_matrix[dummy_a][dummy_b] = off_diag_score scoring_matrix["-"][dummy_a] = dash_score scoring_matrix[dummy_a]["-"] = dash_score scoring_matrix["-"]["-"] = dash_score return scoring_matrix def compute_alignment_matrix(seq_x, seq_y, scoring_matrix, global_flag): ''' compute alignment matrix ''' if seq_x == '': return [[0]] alignment_matrix = [ [0] * (len(seq_y) + 1) for _ in range(len(seq_x) + 1)] # initialize 2d matrix to 0 scoring_matrix_copy = scoring_matrix.copy() for dummy_i in range(1,len(seq_x) + 1): alignment_matrix[dummy_i][0] = alignment_matrix[dummy_i - 1][0] + scoring_matrix_copy[seq_x[dummy_i - 1]]["-"] if global_flag == False and alignment_matrix[dummy_i][0] < 0: alignment_matrix[dummy_i][0] = 0 for dummy_j in range(1, len(seq_y) + 1): alignment_matrix[0][dummy_j] = alignment_matrix[0][dummy_j - 1] + scoring_matrix_copy["-"][seq_y[dummy_j - 1]] if global_flag == False and alignment_matrix[0][dummy_j] < 0: alignment_matrix[0][dummy_j] = 0 for dummy_i in range(1,len(seq_x) + 1): for dummy_j in range(1, len(seq_y) + 1): alignment_matrix[dummy_i][dummy_j] = max(alignment_matrix[dummy_i - 1][dummy_j - 1] + scoring_matrix_copy[seq_x[dummy_i - 1]][seq_y[dummy_j - 1]], alignment_matrix[dummy_i - 1][dummy_j] + scoring_matrix_copy[seq_x[dummy_i - 1]]["-"], alignment_matrix[dummy_i][dummy_j - 1] + scoring_matrix_copy["-"][seq_y[dummy_j - 1]] ) if global_flag == False and alignment_matrix[dummy_i][dummy_j] < 0: alignment_matrix[dummy_i][dummy_j] = 0 return alignment_matrix def compute_global_alignment(seq_x,seq_y,scoring_matrix,alignment_matrix): '''global alignment ''' if seq_x == "" or seq_y == "": return (0,"","") x_pos = len(seq_x) y_pos = len(seq_y) x_res = "" y_res = "" while x_pos > 0 and y_pos > 0: if alignment_matrix[x_pos][y_pos] == (alignment_matrix[x_pos - 1][y_pos - 1] + scoring_matrix[seq_x[x_pos - 1]][seq_y[y_pos - 1]]): x_res = seq_x[x_pos - 1] + x_res y_res = seq_y[y_pos - 1] + y_res x_pos -= 1 y_pos -= 1 else: if alignment_matrix[x_pos][y_pos] == (alignment_matrix[x_pos - 1][y_pos] + scoring_matrix[seq_x[x_pos - 1]]["-"]): x_res = seq_x[x_pos - 1] + x_res y_res = "-" + y_res x_pos -= 1 else: x_res = "-" + x_res y_res = seq_y[y_pos - 1] + y_res y_pos -= 1 while x_pos > 0: x_res = seq_x[x_pos - 1] + x_res y_res = "-" + y_res x_pos -= 1 while y_pos > 0: x_res = "-" + x_res y_res = seq_y[y_pos - 1] + y_res y_pos -= 1 return (alignment_matrix[len(alignment_matrix) - 1][len(alignment_matrix[0]) - 1],x_res, y_res) def compute_local_alignment(seq_x,seq_y,scoring_matrix,alignment_matrix): '''compute local alignment ''' # find position of maximum value on alignment_matrix # do the global alg until alignment_matrix = 0 if seq_x == "" or seq_y == "": return (0,"","") # find maximum value in alignment_matrix and its position max_score = float("-inf") start_pos = () for idx_i in range(len(alignment_matrix) - 1, -1, -1): for idx_j in range(len(alignment_matrix[0]) - 1, -1, -1): if alignment_matrix[idx_i][idx_j] > max_score: max_score = alignment_matrix[idx_i][idx_j] start_pos = (idx_i, idx_j) # reuse global alignment code. start at position of max score and run until # alignment_matrix returns 0 x_pos = start_pos[0] y_pos = start_pos[1] x_res = "" y_res = "" while x_pos > 0 and y_pos > 0 and alignment_matrix[x_pos][y_pos] > 0: if alignment_matrix[x_pos][y_pos] == (alignment_matrix[x_pos - 1][y_pos - 1] + scoring_matrix[seq_x[x_pos - 1]][seq_y[y_pos - 1]]): x_res = seq_x[x_pos - 1] + x_res y_res = seq_y[y_pos - 1] + y_res x_pos -= 1 y_pos -= 1 else: if alignment_matrix[x_pos][y_pos] == (alignment_matrix[x_pos - 1][y_pos] + scoring_matrix[seq_x[x_pos - 1]]["-"]): x_res = seq_x[x_pos - 1] + x_res y_res = "-" + y_res x_pos -= 1 else: x_res = "-" + x_res y_res = seq_y[y_pos - 1] + y_res y_pos -= 1 while x_pos > 0 and alignment_matrix[x_pos][0] > 0: x_res = seq_x[x_pos - 1] + x_res y_res = "-" + y_res x_pos -= 1 while y_pos > 0 and alignment_matrix[0][y_pos] > 0: x_res = "-" + x_res y_res = seq_y[y_pos - 1] + y_res y_pos -= 1 return (max_score, x_res, y_res) def generate_null_distribution(seq_x,seq_y,scoring_matrix,num_trials): '''generates a distribution of scores for random permutations of seq_y for num_trials ''' scoring_dictionary = {} # generate a random permutation rand_y of the sequence seq_y using random.shuffle() i = num_trials count = 1 while i != 0: # generate a random permutation rand_y of the sequence seq_y using random.shuffle() rand_y = list(seq_y) random.shuffle(rand_y) rand_y = ''.join(rand_y) #print i, rand_y # compute the maximum value score for the local alignment of seq_x and rand_y local_alignment = student.compute_local_alignment(seq_x, rand_y, PAM50, student.compute_alignment_matrix(seq_x, rand_y, PAM50, False)) if local_alignment[0] not in scoring_dictionary: scoring_dictionary[local_alignment[0]] = 1 else: # increment the entry score in the dictionary by one scoring_dictionary[local_alignment[0]] += 1 i -= 1 return scoring_dictionary def convert_scoring_dictionary_to_list(scoring_dictionary): scores_list = [] for score, count in scoring_dictionary.items(): for i in range(count): scores_list.append(score) return scores_list
f8bd683f3f7762f5b97520608a16070978a633df
aisaraysmagul/1st-course
/python/task6/1.py
745
3.5625
4
ke=dict() ke['алма']='apple' ke['тау']='mountain' ke['шаш']='hair' def kaz_eng(): print('Welcome to Kaz-Eng Dictionary!') print('==============================','\n','Choose one:') print(' 1 - Search','\n','2 - Add','\n','3 - List','\n','4 - Exit') print('-------------------') x=input('Number of option: ') if x=='1': y=input('Search:') for i in ke: if i==y: print(ke[i]) kaz_eng() if x=='2': y=input('Please,add new word in Kazakh: ') z=input('And its translation in English: ') ke[y]=z kaz_eng() if x=='3': print(ke) kaz_eng() if x=='4': print('Good bye!') kaz_eng()
340eecec3eaa495f4eb5b397fed4eae31d22d4c4
Israelgd85/Pycharm
/excript/app-comerciais-kivy/Int.Ciencia_da Computacao_Python/semana-7/fatorial.py
283
4.1875
4
# n = int(input("Digite um número inteiro: ")) n = 0 while n >= 0: n = int(input("Digite um número inteiro: ")) def fat(n): fatorial = 1 while n > 1 and n > 0: fatorial = fatorial * n n = n - 1 print(fatorial) fat(n)
74850d266cd83cd27239d70089d82df1b3dbef06
sgtnourry/Pokemon-Project
/src/Menu/menu_entry.py
809
3.5625
4
class MenuEntry: """ Represents an entry in the menu. Intended to be sub-classed. """ def __init__(self, callback): """ Builds a menu entry with its callback function to call when finished """ self.callback = callback self.selected = False def call(self): """ Calls the function """ self.callback(self) def select(self): """ Select this entry """ self.selected = True def deselect(self): """ Deselect this entry """ self.selected = False def getTextLength(self): """ Return the printable length of the Entry's Text """ return 0 def getText(self): """ Return the text of the Menu Entry """ return ""