blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
9fe2f6b65dd997183979558e6a035ad40b393da6
kpanag-ynwa/da-test
/Package/insured.py
1,356
3.78125
4
# Design a data structure that #- Contains aggregated metrics for all insured people # - Total covered amount for all claims # - Claims per year # - Average age of insured import pandas as pd import numpy as np import uuid # The Insured class allows to store the attributes of an Insured in an insured object class Insured(): # __init__ constructor - lays out the layout of the insured data def __init__(self): self.ID= None self.name = None self.gender = None self.date_of_birth = None self.age = None self.SSN = None # method that adds an insured individual and brdiges the interface to the back-end. Updates the object with the user's input def input_to_attributes_insured(self): self.name = input("What's the name of the insured? ") self.gender = input("What's the gender of the insured? ") self.date_of_birth = input("What's the date of birth of the insured? ") self.age = input("What's the age of the insured? ") self.SSN = input("What's the SSN of the insured? ") return self # method that returns a unique identifier def name_to_ID(self,name): self.ID = '{}-{}'.format(name,uuid.uuid4().hex[:8]) return self.ID
63f4bff3a3132ec2bddb3b8cce6bddb14033054a
cguldner/PythonReplace
/replace.py
4,194
4.46875
4
#!/usr/bin/env python3 import re import sys import argparse if sys.version_info[0] != 3: print("This script requires Python version > 3.0") sys.exit(1) # The delimiter that separates the entries in the regex file DELIMITER = "~" FILE_ENCODING = "utf-8" def replace_from_file(content_filename, replace_filename, output_filename, regex=False): """ For every line in the replace_file, perform a replacement in the content_file The replace_file uses the delimiter |, simply escape the delimiter (\|) if you want to replace that character The last delimited string on a line is the replace word for that replace_list. For example, if one line of the replace file is 1|2|3|4|9 then all instances of 1, 2, 3, or 4 will be replaced with 9 in the content file. :param Union[list, str] content_filename: Name of the file that is having content replaced :param str replace_filename: Definitions of the replace mappings :param str output_filename: Name of the file with replaced contents :param bool regex: Whether to use regex searching or not """ # If content_filename is a single string, put it into a one-element list iterator = (content_filename,) if not isinstance(content_filename, (tuple, list)) else content_filename if len(iterator) > 1: raise TypeError("only supports one input file currently") for filename in iterator: content_file = open(filename, encoding = FILE_ENCODING) replace_file = open(replace_filename, "r+", encoding = FILE_ENCODING) contents = content_file.read() for line in replace_file.readlines(): # Use negative lookbehind to not split on escaped delimiters temp = re.split(r'(?<!\\)' + re.escape(DELIMITER), line.rstrip("\n")) replace_list = temp[:-1] # Now that the list has been split, unescape the delimiter replace_list = [x.replace("\\" + DELIMITER, DELIMITER) for x in replace_list] replace_word = temp[-1] contents = replace_strings(contents, replace_list, replace_word, regex) new_file = open(output_filename, "w", encoding = FILE_ENCODING) new_file.write(contents) content_file.close() replace_file.close() def replace_strings(original, replace_list, replace_word, regex=False): """ Takes a text where replacements are desired, and for each occurrence of a pattern in replace_list, replaces it with the given replace_word. Can be set to regex matching if desired. :param str original: The original text to replace words in :param Union[list, str] replace_list: The list of words to replace :param str replace_word: The word to replace with :param bool regex: Whether to use regex searching or not :return str: The text with the specified characters replaced """ if not isinstance(original, str): raise TypeError('parameter "original" must have type str') if not isinstance(replace_word, str): raise TypeError('parameter "replace_word" must have type str') # Escape any regex characters if script not being run in regex mode escaped = [x if regex else re.escape(x) for x in replace_list] reg = "(" + "|".join(escaped) + ")" return re.sub(reg, replace_word, original) if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Replaces contents of file based on predefined regex patterns.') parser.add_argument('-r', '--regex', action = 'store_true', help = 'Use regex matching') parser.add_argument('content_filename', metavar = 'input_file', nargs = '+', help = 'File to replace contents of') parser.add_argument('replace_filename', metavar = 'regex_file', help = 'File to get the regex patterns from') parser.add_argument('output_filename', metavar = 'output_file', default = 'replaced.txt', nargs = '?', help = 'Name of the file with replaced contents (default: replaced.txt)') args = parser.parse_args() replace_from_file(**vars(args))
e141d27ddd608997abb5304149501a242715e7d8
El-Mohr/Stegano
/src/LSBMain.py
3,437
3.515625
4
import os,sys from PIL import Image import numpy import math import subprocess import datetime def divideData(image,rawData,numberBits): if(numberBits > 8): print "Error: Number of bits should not be larger than 8" div = int(math.ceil(len(rawData) / (len(image)*numberBits*3.0))) blockedData = [[[b'0' for x in range(3)] for y in range(len(image))] for z in range(div)] i=0 for index in range(div): for pixel in range(len(image)): for color in range(3): if(i<len(rawData)): tempData=b'' for bit in range(numberBits): if(i<len(rawData)): tempData = tempData + rawData[i] else: tempData = tempData + b'0' i= i + 1 blockedData[index][pixel][color] = tempData else: return blockedData return blockedData def hideData(image,data,numberBits): if(numberBits > 8): print "Error: Number of bits should not be larger than 8" if(len(data)>(len(image))): print "Error: Too much data to hide!!" for index in range(0,len(image)): tempPixel = list(image[index]) # convert to list to be able to change it tempPixel[0] = (tempPixel[0] & 0xFF << numberBits) | int(data[index][0],2) tempPixel[1] = (tempPixel[1] & 0xFF << numberBits) | int(data[index][1],2) tempPixel[2] = (tempPixel[2] & 0xFF << numberBits) | int(data[index][2],2) image[index] = tuple(tempPixel) #right the data return image def getData(image,numberBits): allData = '' for index in range(0,len(image)): tempPixel = list(image[index]) allData=allData+(format(int(tempPixel[0] & ~(0xFF << numberBits)), '0%db'%numberBits)) allData=allData+(format(int(tempPixel[1] & ~(0xFF << numberBits)), '0%db'%numberBits)) allData=allData+(format(int(tempPixel[2] & ~(0xFF << numberBits)), '0%db'%numberBits)) return allData ############Encoding message in image############### imageSrc = str(sys.argv[1]) #read arguments from terminal stMsg = "hello world\n" #for i in range(200000) : # stMsg = stMsg + 'x' #print stMsg inputData='' for x in stMsg: inputData=inputData+format(ord(x), '08b') if(imageSrc == "Camera"): os.system("avconv -y -f video4linux2 -s 640x480 -i /dev/video0 -loglevel quiet -ss 0:0:0.1 -frames 1 ./../samples/sample1.png") imageMat = Image.open("./../samples/sample1.png") #read the image, 8 bit per pixel print "Using Camera" else: imageMat = Image.open("./../samples/sample1.png") #read the image, 8 bit per pixel print "Using Sample" pixels = list(imageMat.getdata()) #the content of images (list of tupels) blockedData=divideData(pixels,inputData,2)#data is divided to number of block for each image for div in range(len(blockedData)): imageHidden = hideData(pixels,blockedData[div],2) #call the function that merges the data image_out = Image.new(imageMat.mode,imageMat.size) image_out.putdata(imageHidden) image_out.save('../outputs/out%d.png' % div) ##########Decoding modified Image############# modImageMat = Image.open("./../outputs/out0.png") #read the image, 8 bit per pixel modPixels = list(modImageMat.getdata()) #the content of images (list of tupels) imageData = getData(modPixels,2) msg='' for bit in range(0,len(imageData),8): if (chr(int(imageData[bit:bit+8], 2)) != '\n'): msg = msg + chr(int(imageData[bit:bit+8], 2)) else: break #Display output print "The message was : " + msg #p = subprocess.Popen(["display" , "./../outputs/out0.png"]) #p = subprocess.Popen(["display" , "./../samples/sample1.png"])
bb2d826dd1bf2d9afb50d79d6cdedc96a4262309
Rashika258/Myaudiobook
/audiobook.py
1,397
3.765625
4
#python text to speech conversion import pyttsx3 #pdf lib import PyPDF2 #select your book open in read binary mode book = open('CN.pdf', 'rb') #create pdfReader object pdfReader = PyPDF2.PdfFileReader(book) #count the total pages total_pages = pdfReader.numPages print("Total number of pages " +str(total_pages)) #initialise speaker object speaker = pyttsx3.init() # print("Enter your starting page") # start_page = int(input()) print("Menu\n 1. Play a single page\n 2. Play between start and end points\n 3. Play the entire book ") print("Enter your choice") choice = int(input()) if (choice == 1): print("Enter index number") page = int(input()) page = pdfReader.getPage(page) text = page.extractText() speaker.say(text) speaker.runAndWait() elif (choice == 2): print("Enter starting page number") start_page = int(input()) print("Enter ending page number") end_page = int(input()) for page in range(start_page+1, end_page): page = pdfReader.getPage(start_page+1) text = page.extractText() speaker.say(text) speaker.runAndWait() elif (choice == 3): for page in range(total_pages+1): page = pdfReader.getPage(page) text = page.extractText() speaker.say(text) speaker.runAndWait() else: print("Haha!! Please enter valid choice")
520108eaa27e3864ab84624df04fe5810ce74be1
mikhail-dvorkin/competitions
/hackerrank/weekofcode27/zero-move-nim.py
350
3.59375
4
#!/usr/bin/env python3 def solve(a): xor = 0 for x in a: xor ^= ((x - 1) ^ 1) + 1 return "W" if xor else "L" def test(): assert solve([1, 2]) == "W" assert solve([2, 2]) == "L" def read_ints(): return list(map(int, input().split())) if __name__ == '__main__': test() for _ in range(int(input())): input() print(solve(read_ints()))
2c6075e9584c6d21f3d4010ff4480aa08cd53899
vivianlorenaortiz/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
441
4.03125
4
#!/usr/bin/python3 def append_after(filename="", search_string="", new_string=""): """ inserts a line of text to file after each line containing a string """ with open(filename, 'r+', encoding='utf-8') as f: lines = [] for line in f: lines.append(line) if search_string in line: lines.append(new_string) f.seek(0) for line in lines: f.write(line)
868be30cf661c231a4ca0175f0eb1c1b8488a9d9
vivianlorenaortiz/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
1,229
4.09375
4
#!/usr/bin/python3 """ creating “Interactive tests”. For this exercise, you will add Unittests. """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """ unittest for the function max integer function. """ def test_basic_case(self): self.assertEqual(max_integer([1, 2, 3, 6]), 6) self.assertEqual(max_integer([5, 6, 1, 8]), 8) self.assertEqual(max_integer([21, 23, 32, 71]), 71) def text_negative_case(self): self.assertEqual(max_integer([-1, -2, -3, -6]), -6) self.assertEqual(max_integer([-5, -6, -1, -8, -2]), -1) self.assertEqual(max_integer([21, 23, 32, 71]), -71) def test_basic_empty(self): self.assertEqual(max_integer([]), None) def test_basic_float(self): self.assertEqual(max_integer([0.65, 2.4, 3.0]), 3.0) self.assertEqual(max_integer([12.9, 8.1, 8.0]), 12.9) self.assertEqual(max_integer([11.2, 5.6, 20.1, 15.3]), 20.1) def test_basic_oneelement(self): self.assertEqual(max_integer([1]), 1) def test_basic_string(self): self.assertEqual(max_integer(""), None) if __name__ == '__main__': unittest.main()
949b939ef934fb793119900d36b377d7069c1916
vivianlorenaortiz/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
345
4.3125
4
#!/usr/bin/python3 """ Funtion that prints a square with the character #. """ def print_square(size): """ Function print square. """ if type(size) is not int: raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") for i in range(size): print(size * "#")
4a0527d5b5fae707c8fb21b006fcdfdaad6776eb
miao906612/python_learn
/03python/dynamicTyping.py
3,170
3.84375
4
# -*- coding: utf-8 -*- ######################################################################### # File Name: dynamicTyping.py # Author: Shuo Miao # mail: miao906612@163.com # Created Time: 2015年11月24日 13:09:03 ######################################################################### #Dynamic Typing Model #In python,types are determined automatically at runtime, not in response #to declarations in your code. #Variables, Objects and References #Four points for Variables #1 Variables are entries in a system table, with spaces for links to # objetcs #2 Variable creation---A variable( i.e. name) is created when your code # first assigns it to a value. Future assignments change the value of # the already created name. Technically, Python detects some names # before your code runs. #3 Variable types---A variable never has any type information or # constraints associated with it. The notion of type lives with objects. # Variables are generic in nature; they always simply refer to a # particular object at a particular point in time #4 Variable use---When a variable appears in an expression,it is # immediately replaced with the object that it currently refers to, # whatever that may be. Further, all variables must be explicitly # assigned before they can be used; referencing unassigned variables # results in errors a = 3 #1 Create an object to represent the value 3 #2 Create the variable a, if it does not yet exist #3 Link the variable a to the new object 3 #Objects #Objects are pieces of allocated memory, with enough space to represent #the values for which they stand and two standard header fileds:a type #designator used to mark the type of the object(a poniter to an object #called int, the name of the integer type etc) and a reference counter #used to determine when it's OK to reclaim the object which is to say #that the object's space is automatically thrown bakc into the free space #tool, to be reused for a future object. #References #References are automatically followed pointers from variables to objects #Shared References and immutable objects a = 3 print( id(a) ) b = a print( id(b) ) a = 'spam' print( id(a) ) b = b + 2 print( id(b) ) #Shared References and mutable objects import copy #List L1 = [2] temp = [1] L1.append(temp) L2 = L1 # not copy L3 = L1[:] # top-level shallow copy L4 = list(L1) # top-level shallow copy #L5 = L1.copy() # top-level shallow copy and only for Python 3.3 and later L6 = copy.copy(L1) # top-level shallow copy L7 = copy.deepcopy(L1) # deep copy #result =( L1,L2,L3,L4,L5,L6,L7 ) result =( L1,L2,L3,L4,L6,L7 ) print( result ) temp[0] = 3 print( result ) #dict d1 = {'a':1} d2 = d1 # not copy d3 = d1.copy() #top-level shallow copy d4 = dict( d1 ) #top-level shallow copy d5 = copy.copy( d1 ) #top-level shallow copy d6 = copy.deepcopy( d1 ) #deep copy #set s1 = {1} s2 = s1 # not copy s3 = s1.copy() #top-level shallow copy s4 = set( s1 ) #top-level shallow copy s5 = copy.copy( s1 ) #top-level shallow copy s6 = copy.deepcopy( s1 ) #deep copy #the getrefcount function in the standard sys module returns the object's #reference count import sys print( sys.getrefcount(1) )
6252a2da6e3c857b6966580fdb6e8f028040c55b
CharlieZheng/LearningPython
/NumPy/Arrays.py
3,481
3.6875
4
from numpy import * import numpy as np a1 = array([1, 1, 1]) a2 = array([2,2,2]) print(a1+a2) print(a1*2) e =np.random.random((3,2,2)) *20 print(e) '修改数组操作' arr = np.arange(10)*3 out=np.where(arr%2==1, -1, arr) print(arr) arr = arr[arr%2==1] # 取index满足条件的item组成新的数组 print(arr) print(out) '把1行10列的数组变成2行5列的数组' out = arr.reshape(5, -1) # (5, -1)或(5, 1) print(out) arr = arr.reshape(1, -1) '锤子拼接数组' b = np.repeat(13, 5).reshape(1, 5)# .reshape(1, 5)后变成矩阵,不能与数组互操作 print('b:'+str(b)) # Method 1: hb1 =np.concatenate([arr, b], axis =0) # Method 2: hb2=np.vstack([arr, b]) # Method 3: hb3=np.r_[arr, b] print('hb1:%s\nhb2:%s\nhb3:%s\n'%(str(hb1) ,str(hb2) ,str(hb3))) '水平拼接数组' # Method 1: hb1 =np.concatenate([arr, b], axis =1) # Method 2: hb2=np.hstack([arr, b]) # Method 3: hb3=np.c_[arr, b] print('hb1:%s\nhb2:%s\nhb3:%s\n'%(str(hb1) ,str(hb2) ,str(hb3))) '看效果' arr =np.array([1, 2, 3]) print(np.r_[np.repeat(arr, 3), np.tile(arr, 3)]) '求交集' arr =np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6]) b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9,8]) print ('交集:'+str(np.intersect1d(arr, b))) '求交集index' print ('交集index:' +str(np.where(arr== b))) '求相对于另一个数组元素完全不同的子集' arr =np.array([1,2, 3, 4,5]) b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9,8]) print (np.setdiff1d(arr, b)) '筛选子集' arr =np.arange(15)*1.2 # Method 1 index = np.where((arr>=5)&(arr<=10)) print(index) print(arr[index]) # Method 2 index = np.where(np.logical_and(arr>=5, arr<=10)) print(index) print(arr[index]) '行或列交换' arr = np.arange(9).reshape(3, 3) arr =arr[:, [2,1,0]] #列交换 print(arr) arr = np.arange(9).reshape(3, 3) arr =arr[[1,2,0], :] #行交换 print(arr) '反转行或列' arr = np.arange(9).reshape(3, 3) arr =arr[:, ::-1] #列交换 print(arr) arr = np.arange(9).reshape(3, 3) arr =arr[ ::-1,:] #行交换或arr[ ::-1] print(arr) '5到10的二维数组' # Solution Method 1: bt = np.random.randint(low=5, high=10, size=(5, 3)) + np.random.random((5, 3)) print(bt) # Solution Method 2: bt = np.random.uniform(5, 10, size=(5, 3)) print(bt) '截断' bt=np.arange(100) np.set_printoptions(threshold=6) print(bt) bt = np.arange(20) '恢复' np.set_printoptions(threshold=np.nan) print(bt) url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' iris = np.genfromtxt(url, delimiter=',', dtype='object', encoding='utf-8') names=('sepallength', 'sepallwidth', 'petallength', 'petallwidth', 'species') print(iris.shape) print(iris[:3]) species = np.array([row[4] for row in iris]) print(species.shape) print(species[:5]) '27.如何将一维元组数组转换为二维numpy数组?' # Solution Method 1: species =np.array([row.tolist()[:4] for row in iris]) print(species.shape) print(species[:4]) species = np.genfromtxt(url , delimiter=',', dtype='float', usecols=[0,1,2,3]) print(species.shape) print(species[:4]) '28.如何计算numpy数组的平均值,中位数,标准差?' sepallength = np.genfromtxt(url, delimiter=',', dtype='float', usecols=[0]) mu, med, sd = np.mean(sepallength), np.median(sepallength), np.std(sepallength) print(mu, med, sd) '29.如何标准化一个数组至0到1之间?' Smax, Smin = sepallength.max(), sepallength.min() S = (sepallength-Smin)/(Smax - Smin) print(sepallength.shape) print(S.shape) print(sepallength) print(S)
0ebb8cb51fc117d53c7c652eb366c2cbecb540d1
knitendra5371/Python
/DSA/linked list/ReverseDLL.py
1,088
3.734375
4
class Node: def __init__(self, d): self.data = d self.prev = None self.next = None class DLL: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node def printList(self, node): while(node is not None): print(node.data, end=" ") node = node.next print() def reverseDLL(self): temp = None curr_ptr = self.head if(curr_ptr is None or (curr_ptr.prev is None and curr_ptr.next is None)): return while(curr_ptr): temp = curr_ptr.prev curr_ptr.prev = curr_ptr.next curr_ptr.next = temp curr_ptr = curr_ptr.prev self.head = temp.prev if __name__ == "__main__": dll = DLL() dll.push(2) dll.push(4) dll.push(8) dll.push(10) dll.printList(dll.head) dll.reverseDLL() dll.printList(dll.head)
b7817e01ba1aaae1e739c7fe808308b6329d5e4b
martinchristen/pyRT
/pyrt/renderer/renderer.py
543
3.5625
4
""" This is the abstract Renderer. If you override if you implement your own. """ from abc import abstractmethod from ..scene import Scene class Renderer(object): def __init__(self, name="UNKNOWN RENDERER"): self.name = name print("# Creating Renderer: " + self.name) @abstractmethod def render(self, scene : Scene) -> list: """ Abstract rendering. This actually renmders the scene and returns the image data :param scene: the scene to render :return: """ pass
42b3c176483c9a5b7143fa51a88a0ffe2522b4ae
martinchristen/pyRT
/pyrt/geometry/triangle.py
10,928
3.65625
4
""" This is the geometric object triangle (renderable object) """ from ..geometry import Shape, Vertex from ..material import PhongMaterial, TextureMaterial, NormalMappedMaterial from ..math import * class Triangle(Shape): """Triangle class for raytracing""" def __init__(self, a: Vertex, b: Vertex, c: Vertex, material=PhongMaterial()): if type(a) != Vertex or type(b) != Vertex or type(c) != Vertex: raise ValueError("Please initialize Triangle with 3x Vertex") Shape.__init__(self, "Triangle") self.a = a self.b = b self.c = c self.material = material self.EPSILON = 0.000001 def __str__(self): return "△ABC: Position[" + str(self.a.position) + ", " + str(self.b.position) + ", " + str( self.c.position) + "]" # ------------------------------------------------------------------------------------------------------------------ def area(self) -> float: """ Calculate area of triangle :return: area """ return cross3(self.b.position - self.a.position, self.c.position - self.a.position).length() / 2.0 # ------------------------------------------------------------------------------------------------------------------ def toBarycentric(self, p: Vec3) -> Vec3: """ Calculate barycentric coordinate of point p :param P: the input point (cartesian) :return: barycentric coordinate """ abc = triangleArea(self.a.position, self.b.position, self.c.position) pbc = triangleArea(p, self.b.position, self.c.position) apc = triangleArea(self.a.position, p, self.c.position) if abc == 0.0: return Vec3(0, 0, 0) x = pbc / abc y = apc / abc return Vec3(x, y, 1.0 - x - y) # ------------------------------------------------------------------------------------------------------------------ def fromBarycentric(self, b: Vec3) -> Vec3: """ Calculate cartesian coordinate from barycentric coordinate :param b: barycentric coordinate :return: cartesian coordinate """ return self.a.position * b.x + self.b.position * b.y + self.c.position * b.z # ------------------------------------------------------------------------------------------------------------------ def circumradius(self) -> float: a = (self.c.position - self.b.position).length() b = (self.c.position - self.a.position).length() c = (self.b.position - self.a.position).length() s = (a + b + c) / 2.0 # semiperimeter z = a * b * c n = 4.0 * math.sqrt(s * (a + b - s) * (a + c - s) * (b + c - s)) if n == 0.0: return 0.0 return z / n # ------------------------------------------------------------------------------------------------------------------ def inradius(self) -> float: a = (self.c.position - self.b.position).length() b = (self.c.position - self.a.position).length() c = (self.b.position - self.a.position).length() s = (a + b + c) / 2.0 if s == 0.0: return 0.0 return math.sqrt((s - a) * (s - b) * (s - c) / s) # ------------------------------------------------------------------------------------------------------------------ def circumcenter(self) -> Vec3: a = (self.c.position - self.b.position).length() b = (self.c.position - self.a.position).length() c = (self.b.position - self.a.position).length() q = a * a * (-a * a + b * b + c * c) w = b * b * (a * a - b * b + c * c) e = c * c * (a * a + b * b - c * c) n = q + w + e if n == 0.0: return Vec3(0, 0, 0) return self.fromBarycentric(Vec3(q / n, w / n, e / n)) # ------------------------------------------------------------------------------------------------------------------ def incenter(self) -> Vec3: a = (self.c.position - self.b.position).length() b = (self.c.position - self.a.position).length() c = (self.b.position - self.a.position).length() n = a + b + c if n == 0.0: return Vec3(0, 0, 0) return self.fromBarycentric(Vec3(a / n, b / n, c / n)) # ------------------------------------------------------------------------------------------------------------------ def centroid(self) -> Vec3: return (self.a.position + self.b.position + self.c.position) / 3.0 # ------------------------------------------------------------------------------------------------------------------ def calcTexcoord(self, p: Vec3) -> Vec2: """ Returns texture-coordinate at cartesian position p :param p: :return: returns """ pb = self.toBarycentric(p) u = self.a.texcoord.x * pb.x + self.b.texcoord.x * pb.y + self.c.texcoord.x * pb.z v = self.a.texcoord.y * pb.x + self.b.texcoord.y * pb.y + self.c.texcoord.y * pb.z return Vec2(u, v) # ------------------------------------------------------------------------------------------------------------------ def hit(self, ray: Ray, hitrecord: HitRecord) -> bool: """ Ray Triangle Intersection Original Code from: "Practical Analysis of Optimized Ray-Triangle Intersection" Tomas Möller Department of Computer Engineering, Chalmers University of Technology, Sweden. http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/ :param ray: the ray to check hit :param tmin: tmin to test intersection :param tmax: tmax to test intersection :param hitrecord: the hitrecord which is only valid if there is a hit :return: True if there is a hit """ t0 = hitrecord.t # find vectors for two edges sharing vert0 edge1 = self.b.position - self.a.position edge2 = self.c.position - self.a.position # begin calculating determinant - also used to calculate U parameter pvec = cross3(ray.direction, edge2) # if determinant is near zero, ray lies in plane of triangle det = dot3(edge1, pvec) if det > self.EPSILON: tvec = ray.start - self.a.position u = dot3(tvec, pvec) if u < 0.0 or u > det: return False qvec = cross3(tvec, edge1) v = dot3(ray.direction, qvec) if v < 0.0 or u + v > det: return False elif det < -self.EPSILON: tvec = ray.start - self.a.position u = dot3(tvec, pvec) if u > 0.0 or u < det: return False qvec = cross3(tvec, edge1) v = dot3(ray.direction, qvec) if v > 0.0 or u + v < det: return False else: return False inv_det = 1.0 / det t = dot3(edge2, qvec) * inv_det u *= inv_det v *= inv_det if t0 is not None and t > t0: return False if t > 0.0: # and t<tmax hitrecord.t = t hitrecord.point = ray.start + t * ray.direction hitrecord.normal = cross3(edge1, edge2) if self.a.normal is not None and self.b.normal is not None and self.c.normal is not None: nU = self.b.normal - self.a.normal nV = self.c.normal - self.a.normal hitrecord.normal_g = self.a.normal + nU * u + nV * v else: hitrecord.normal_g = hitrecord.normal # Calculate color cU = self.b.color - self.a.color cV = self.c.color - self.a.color hitrecord.color = self.a.color + cU * u + cV * v hitrecord.material = self.material if isinstance(hitrecord.material, TextureMaterial) or isinstance(hitrecord.material, NormalMappedMaterial): hitrecord.texcoord = self.calcTexcoord(hitrecord.point) # why would we? # hitrecord.point = ray.start + t * ray.direction return True return False def hitShadow(self, ray: Ray) -> bool: """ :param ray: :param tmin: :param tmax: :return: """ # find vectors for two edges sharing vert0 edge1 = self.b.position - self.a.position edge2 = self.c.position - self.a.position # begin calculating determinant - also used to calculate U parameter pvec = cross3(ray.direction, edge2) # if determinant is near zero, ray lies in plane of triangle det = dot3(edge1, pvec) if det > self.EPSILON: tvec = ray.start - self.a.position u = dot3(tvec, pvec) if u < 0.0 or u > det: return False qvec = cross3(tvec, edge1) v = dot3(ray.direction, qvec) if v < 0.0 or u + v > det: return False elif det < -self.EPSILON: tvec = ray.start - self.a.position u = dot3(tvec, pvec) if u > 0.0 or u < det: return False qvec = cross3(tvec, edge1) v = dot3(ray.direction, qvec) if v > 0.0 or u + v < det: return False else: return False inv_det = 1.0 / det t = dot3(edge2, qvec) * inv_det u *= inv_det v *= inv_det if t > 0.0: return True return False def getBBox(self): """ Retrieve axis aligned bounding box of the triangle :return: bounding box """ xmin = min(self.a.position.x, self.b.position.x, self.c.position.x) ymin = min(self.a.position.y, self.b.position.y, self.c.position.y) zmin = min(self.a.position.z, self.b.position.z, self.c.position.z) xmax = max(self.a.position.x, self.b.position.x, self.c.position.x) ymax = max(self.a.position.y, self.b.position.y, self.c.position.y) zmax = max(self.a.position.z, self.b.position.z, self.c.position.z) return BBox(Vec3(xmin, ymin, zmin), Vec3(xmax, ymax, zmax)) def getCentroid(self) -> Vec3: """ Retrieve center of triangle :return: """ return self.centroid() def getSurfaceArea(self) -> float: """ Retrieve Surface area of Triangle :return: surface area """ return self.area() # ---------------------------------------------------------------------------------------------------------------------- # Utility functions related to triangles def triangleArea(a: Vec3, b: Vec3, c: Vec3) -> float: """ Calculate area of triangle :return: area """ return cross3(b - a, c - a).length() / 2.0
a2362127d8c7d383370debab8bd048b9f24de73c
martinchristen/pyRT
/examples/00_drawpoints.py
452
3.828125
4
# Example 1: **Introduction to the image class** # This example draws 5000 points and stores the image using PIL from pyrt.renderer import RGBImage from pyrt.math import Vec2, Vec3 import random w = 320 h = 240 image = RGBImage(w, h) for i in range(5000): image.drawPoint(Vec2(random.randint(0, w - 1), random.randint(0, h - 1)), Vec3(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)),3) image.save("00.png")
9035e9d46ddbd176336315b757870fb81c93fed8
QuentinAndre11/D10-WoD-Probabilities
/rolls.py
8,453
4
4
import random """ The goal of this code is to get the probability of success when you roll your dices with the World of Darkness roleplaying system. Brief reminder of the WoD system : - Roll as many D10 (dices with 10 faces) as your character score in attribute + skill (example : you want to give a sword blow, you have a strength of 3 and a score in melee of 2, you roll 3+2=5 dices) - Difficulty threshold is given by the Game Master. A dice is a success if the value of the dice is greater or equal than the difficulty, except if the value is one. In this case, it substracts one success at the total. - If the total is strictly positive, the action is a success. If you have 0 success, it is a failure. If it is negative, it is a critical failure. (example : you roll your 5 dices, you have 10,10,6,5,1. Your GM says the difficulty is set at 6. You have 3-1=2 success, you success in your action) - Special rule : if your character has the attribute "hero", your 10 are counted as 2 success, but are cancelled by the 1 in the first place. (example : with the same roll, you have now one 10 which is cancelled by the one, and the other 10 counts two success. So you have 3 success) In this code, there are two useful functions : - rollsStats(dices,diff,hero) which gives the useful statistics for a given number of dices and difficulty (and the optional hero attribute) - prettyArray(hero,maxDices,value) which gives an array with difficulty as columns and number of dices as rows. You can choose what statistic is shown with the input "value", and you can input whether you want an array for hero attribute, and the maximum number of rows (number of dices). We stored these arrays in the readme for 20 dices. """ def roll(dices, diff, hero=False) : """ Returns the number of success for one roll. A negative number of success is a critical failure, no success corresponds to a failure and one or more success corresponds to a success for the roll. Parameters ---------- dices : int Number of dices (D10) which will be rolled. diff : int Difficulty of the roll. A dice is counted as a success if the value of the dice is greater or equal to the difficulty. hero : optional bool If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice). Raises ------ ValueError If the number of dices is negative or null, or the difficulty is not between 1 and 10 (we use a D10). """ if (dices < 1 or diff < 1 or diff > 10): raise ValueError L = initialList(dices) L = transformedList(L) return countSuccess(L, diff, hero) def initialList(dices) : """ Creates a list L with all the rolled dices, we sort it by decreasing order to use it more easily. Parameters ---------- dices : int Number of dices (D10) which will be rolled. """ L = [] for i in range(dices) : L.append(random.randint(1,10)) L.sort(reverse = True) return L def transformedList(L) : """ Creates a list R which is the list L whithout the dices with value 10 cancelled by those with value 1 Parameters ---------- L: int list Decreasing sorted list with values between 1 and 10. """ R = [] for r in L : if r == 10 : if L[-1] == 1 : L.pop() else : R.append(r) else : R.append(r) return R def countSuccess(L, diff, hero) : """ Counts the number of success for the roll. Parameters ---------- L: int list Decreasing sorted list with values between 1 and 10. diff : int Difficulty of the roll. A dice is counted as a success if the value of the dice is greater or equal to the difficulty. hero : optional bool If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice). """ success = 0 for val in L : if val == 1 : success -= 1 elif val == 10 : if hero : success += 2 else : success += 1 elif val >= diff : success += 1 return success def rollsStats(dices,diff,hero=False) : """ Launches a serie of 10000 rolls to return a list with average number of success, probability of success, failure and critical failure. Parameters ---------- dices : int Number of dices (D10) which will be rolled. diff : int Difficulty of the roll. A dice is counted as a success if the value of the dice is greater or equal to the difficulty. hero : optional bool If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice). Raises ------ ValueError If the number of dices is negative or null, or the difficulty is not between 1 and 10 (we use a D10). """ if (dices < 1 or diff < 1 or diff > 10): raise ValueError m = 0 #m is the average number of success successRate = 0 failureRate = 0 criticRate = 0 for i in range (10000) : success = roll(dices,diff,hero) m += success if success < 0 : criticRate +=1 elif success == 0 : failureRate += 1 else : successRate += 1 S = [m,successRate,failureRate,criticRate] res = [] for s in S : res.append(round(s/100)/100) #limits probability with 2 decimal numbers to keep it readable return res def array(hero=False, maxDices=20, value="Average number of success") : """ Creates a complete array for the wanted information (average number of success by default, or success rate, failure rate or critical failure rate) giving the information for all difficulties and a number of dices between 1 and maxDices Parameters ---------- hero : optional bool If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice). maxDices : optional int Defines the number of rows (range of values for the number of dices) value : optional string Information needed (average number of success by default, or success rate, failure rate or critical failure rate) Raises ------ ValueError If the information needed is not with the right format, raises the right format. """ ind = 0 if (value == "average number of success" or value == "0") : ind = 0 elif (value == "success rate" or value == "1") : ind = 1 elif (value == "failure rate" or value == "2") : ind = 2 elif (value == "critical failure rate" or value == "3") : ind = 3 else : raise ValueError("Try with average number of success, success rate, failure rate, critical failure rate, or 0, 1, 2, 3") T = [] for dices in range (maxDices) : print(dices) T.append([]) for d in range(10) : stats = rollsStats(dices+1,d+1,hero) T[dices].append(stats[ind]) return T def prettyArray(hero=False, maxDices=20, value="Average number of success") : """ Prints the same array as array() but prettier Parameters ---------- hero : optional bool If the character is a hero, its 10 count two success instead of one, but are cancelled first by a critical failure (a one on another dice). maxDices : optional int Defines the number of rows (range of values for the number of dices) value : optional string Information needed (average number of success by default, or success rate, failure rate or critical failure rate) """ #data a = array(hero,maxDices,value) #labels columns = [i+1 for i in range(10)] rows = [i+1 for i in range(maxDices)] row_format ="{:>8}" * (len(columns) + 1) print(row_format.format("", *columns)) for t, row in zip(rows, a): print(row_format.format(t, *row))
894956d2946bd4dafa6f7cfa985b0f34f590b04b
Ninedeadeyes/WoodsofYpres
/items.py
3,501
4.0625
4
class Weapon: def __init__(self): raise NotImplementedError("Do not create raw Weapon Objects.") def __str__(self): return "{}+{} STR ".format(self.name, self.damage) class Rock(Weapon): def __init__(self): self.name="Rock" self.description= "A fist-sized rock, suitable for bludgening." self.damage=5 self.value= 1 class Dagger(Weapon): def __init__(self): self.name="Dagger" self.description="a small dagger with some rust."\ "Somewhere more dangerou than a rock" self.damage=10 self.value= 20 # \ means to continue on another line but consider same line in coding class WoodmansAxe(Weapon): def __init__(self): self.name="Woodman's Axe" self.description= "This sword is showing its age,"\ "but still has some fight in it" self.damage=15 self.value= 100 class HuntingSpear(Weapon): def __init__(self): self.name="Hunting Spear" self.description= "This sword is showing its age,"\ "but still has some fight in it" self.damage=20 self.value= 250 class SilverSword(Weapon): def __init__(self): self.name="Silver sword" self.description= "This sword is showing its age,"\ "but still has some fight in it" self.damage=30 self.value= 150 class DoomHammer(Weapon): def __init__(self): self.name="Doom Hammer" self.description= "This sword is showing its age,"\ "but still has some fight in it" self.damage=40 self.value= 100 class Consumable: def __init__ (self): raise NotImplementedError ("Do not creat raw Consumable Objects") def __str__(self): return "{}+{}HP".format(self.name, self.healing_value) class HardTack(Consumable): def __init__ (self): self.name = "Hard Tack" self.healing_value = 15 self.value= 15 class LesserHealingPotion(Consumable): def __init__(self): self.name = " Lesser Healing Potion" self.healing_value = 50 self.value = 60 class GreaterHealingPotion(Consumable): def __init__(self): self.name = " Greater Healing Potion" self.healing_value = 100 self.value = 150 class bug: def __init__(self): raise NotImplementedError("Do not create raw bug Objects.") def __str__(self): return "{} ".format(self.name) class BoneDoll(bug): def __init__(self): self.name = " Bone Doll" self.value = 7700 class BoneFlute(bug): def __init__(self): self.name = " Bone Flute " self.value = 5600 class BoneCrown(bug): def __init__(self): self.name = " Bone Crown " self.value = 6300 class BoneHarp(bug): def __init__(self): self.name = " Bone Harp " self.value = 3000 #Two important concept of OOP are composition and inheritance # Composition is when an object containing another object # Inheritance is when a class inherits behavior from another class #hence the class Weapon will be consider 'parent class' and other # will be consider ' child class'
0a840da01b6d20c3ce6e266be57be3cf83757c4d
zackcode123/Basic_Python_Exercises
/Ex3_Raio.py
202
4
4
'''Faça um programa que peça o raio de um círculo, calcule e mostre sua área.''' pi = 3.14 n1 = int(input('Digite a area do circulo:')) soma = pi*(n1*n1) print('A area do circulo é:', soma, 'm²')
809e7e3a4be9be995241c67909ae61fc5796d98d
drummerevans/Vector_Multiply
/cross_input.py
564
4.125
4
import numpy as np items = [] max = 3 while len(items) < max: item = input("Add an element to the list: ") items.append(int(item)) print("The length of the list is now increased to {:d}." .format(len(items))) print(items) things = [] values = 3 for i in range(0, values): thing = input("Add an element to the second list: ") things.append(int(thing)) print("The length of the second list is now increased to {:d}. " .format(len(things))) print(things) z = np.cross(items, things) print("The cross product of the two lists are: ", z)
630fcaf6cdae8276f74bea51e69da73b7f27138a
Catheryna1/Final
/BankAccount.oy.py
13,707
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 9 04:50:35 2021 @author: Catheryna """ import random import csv import matplotlib.pyplot as plt class Bank(): def __init__(self): pass class Accounts(Bank): def __init__(self, first_name, last_name, account_ID = "", active = 1, balance = 0): Bank.__init__(self) self.first_name = first_name self.last_name = last_name self.account_ID = account_ID self.active = active self.balance = balance def print_INDIVIDUAL(self): pass def print_All(self): pass class Savings(Accounts): def __init__(self): pass def check_account(self, search_ID): csv_file = csv.reader(open('savings Account.csv', 'r'), delimiter = ',') for row in csv_file: if search_ID == row[2]: print('Account found') def print_INDIVIDUAL(self,search_ID): data = total_accounts file = open('Savings Account Update.csv', 'w', newline = '') with file: write = csv.writer(file) write.writerows(data) print(total_accounts) table = [] csv_file = csv.reader(open('Savings Account Update.csv', 'r'), delimiter = ',') flag = False for row in csv_file: if search_ID == row[2]: table.append(row) print() if flag == False: print('Account not found. \n') def print_ALL(self): table = [] total_accounts.sort(key = lambda total_accounts: total_accounts[1]) for row in total_accounts: table.append(row) print() def withdrawl(self, total_account, user_acount_ID, user_withdraw): flag = False for account in total_accounts: if account[2] == user_account_ID and account[4] == True and account[3] >= user_withdraw: account[3] -= user_withdraw print(account) flag = True if flag == False: print('Incorrect information or account not found.') def deposit(self,total_accounts, user_account_ID, user_deposit): flag = False for account in total_accounts: if account[2] == user_account_ID and account[4] == True: new_balance = account[3] + user_deposit account[3]= new_balance print(account) flag = True if flag == False: ('why.') def plot_all(self, total_accounts): data = {} for account in total_accounts: data[account[2]] = account[3] account_ids = list(data.keys()) account_bal = list(data.values()) plt.bar(account_ids, account_bal, color = 'green',width = 0.6) plt.xlabel('Account IDs') plt.ylabel('Balance') plt.title('Savings accounts') plt.show() def close_account(self, total_account, user_account_ID): flag = False for account in total_account: if account[2] == user_account_ID and account[4] == True: account[4] = False flag = True print('Account Closed') if flag == False: print('Incorrect information or account not found.') class Checkings(Accounts): def __init__(self): pass def check_account(self, search_ID): csv_file = csv.reader(open('checkings Account.csv', 'r'), delimiter = ',') for row in csv_file: if search_ID == row[2]: print('Account found.') def print_INDIVIDUAL(self,search_ID): data = total_accounts_checkings file = open('Checkings Account Update.csv', 'w', newline = '') with file: write = csv.writer(file) write.writerows(data) print(total_accounts_checkings) table = [] csv_file = csv.reader(open('Checkings Account Update.csv', 'r'), delimiter = ',') for row in csv_file: if search_ID == row[2]: table.append(row) print() def print_ALL(self): table = [] total_accounts_checkings.sort(key = lambda total_accounts_checkings: total_accounts_checkings[1]) for row in total_accounts_checkings: table.append(row) print() def withdrawl(self, total_accounts_checkings, user_account_ID, user_withdrawl): flag = False for account in total_accounts_checkings: if account[2] == user_account_ID and account[4] == True and account[3] >= user_withdrawl: account[3] == user_withdrawl print(account) flag = True if flag == False: print("Incorrect account information or account doesn't exist.") def deposit(self, total_accounts_checkings, user_account_ID, user_deposit): flag = False for account in total_accounts_checkings: if account[2] == user_account_ID and account[4] == True: new_balance = account[3] = user_deposit account[3] = new_balance print(account) flag = True if flag == False: print("Incorrect account information or account doesn't exist.") def plot_ALL(self, total_accounts_checkings): data = {} for account in total_accounts_checkings: data[account[2]] = account[3] account_ids = list(data.keys()) account_bal = list(data.values()) plt.bar(account_ids, account_bal, color = 'green', width = 0.6) plt.xlabel('Account IDs') plt.ylabel('Balance') plt.title('Savings accounts') plt.show() def close_account(self, total_accounts_checkings, user_account_ID): flag = False try: for account in total_accounts_checkings: if account[2] == user_account_ID and account[4] == True: account[4] = False except: if flag == False: raise Exception("Incorrect account information or account doesn't exist.") if __name__ == '__main__': total_accounts = [] total_accounts_checkings = [] savings_check = {} checkings_check = {} while True: print('(0) Make a savings account') print('(1) Make a checkings account') print('(2) Search for an account') print('(3) Search for all accounts') print('(4) deposit') print('(5) withdraw') print('(6) Graph balances') print('(7) Close account') print('(8) Exit') user_select = int(input("Select an option: \n")) if user_select == 0: print('OPening savings account') first_name = input('Enter first name: ') last_name = input('Enter last name: ') balance = float(input('Enter deposit: ')) account_type = 'savings' savings_key = first_name + ':' + last_name + ':' + account_type user_select = first_name + ':' + last_name + ':' + account_type if savings_key in savings_check.keys(): print('Account already exist.') else: savings_check[savings_key] = 1 account_ID = '' ID = random.randint(0,9) account_ID = (account_ID + last_name + str(ID) + account_type) active = True account = [first_name, last_name, account_ID, balance, active, account_type] total_accounts.append(account) with open('Savings Account.csv', 'a', newline = '') as file: savings_writer = csv.writer(file) savings_writer.writerow(account) file.close() print('Account created : ',first_name, last_name, 'Account ID:', account_ID) print(total_accounts) elif user_select ==1: print('Opening checking account') first_name = input('Enter first name: ') last_name = input('Enter last name: ') balance = float(input('Enter deposit: ')) account_type = 'checkings' checkings_key = first_name + ':' + last_name + ':' + account_type if checkings_key in checkings_check.keys(): print('Account already exists.') else: checkings_check[checkings_key] = 1 account_ID = '' ID = random.randint(0,9) account_ID = (account_ID + last_name + str(ID) + account_type) active = True account = [first_name, last_name, account_ID, balance, active, account_type] total_accounts_checkings.append(account) with open('Checkings Account.csv', 'a', newline = '') as file: checkings_writer = csv.writer(file) checkings_writer.writerow(account) file.close() print('Account created:', first_name, last_name, 'Account Id: ', account_ID) elif user_select == 2: print('Search Account') account_type = input('Checkings or savings?') if account_type == "savings": search_ID = input('Enter account ID: ') obj = Savings() obj.check_account(search_ID) obj.print_INDIVIDUAL(search_ID) elif account_type == 'checkings': search_ID = input('Enter account ID: ') obj = Checkings() obj.check_account(search_ID) obj.print_INDIVIDUAL(search_ID) else: print('Enter valid account type') elif user_select == 3: print('Search All accounts') account_type = input('Are the accounts checking or savings?') if account_type == 'savings': savings = Savings() savings.print_ALL() elif account_type == 'checkings': checkings = Checkings() checkings.print_ALL() elif user_select == 4: print('Deposit') account_type = input('checkings or savings?') if account_type == 'savings': user_account_ID = input("Enter ID: ") user_deposit = float(input('Enter a deposit amount: ')) savings = Savings() savings.deposit(total_accounts, user_account_ID, user_deposit) elif account_type == 'checkings': user_account_ID = input("Enter ID: ") user_deposit = float(input('Enter a deposit amount: ')) checkings = Checkings() checkings.deposit(total_accounts_checkings, user_account_ID, user_deposit) else: print('Enter valid account type') elif user_select == 5: print("Withdrawl") account_type = input('checkings or savings?') if account_type == 'savings': user_account_ID = input('Enter account ID: ') user_withdraw = float(input('Enter withdrawl amount: ')) savings = Savings() savings.withdrawl(total_accounts, user_account_ID, user_withdraw) elif account_type == 'checking': user_account_ID = input('Enter account ID: ') user_withdraw = float(input('Enter withdrawl amount: ')) checkings = Checkings() checkings.withdrawl(total_accounts_checkings, user_account_ID, user_withdraw) else: print("Enter valid account type") elif user_select == 6: print('Graphing accounts') account_type = input("Do you want to graph checkings or savings? ") if account_type == 'savings': savings = Savings() savings.plot_all(total_accounts) elif account_type == 'checkings': checkings = Checkings() checkings.plot_ALL(total_accounts_checkings) else: print('Enter valid acount type') elif user_select == 7: print("Close account") account_type = input('checkings or savings? ') if account_type == 'savings': user_account_ID = input("Enter account ID: ") savings = Savings() savings.close_account(total_accounts, user_account_ID) elif account_type == 'checkings': user_account_ID = input("Enter account ID: ") checkings = Checkings() checkings.close_account(total_accounts_checkings, user_account_ID) elif user_select == 8: print('Exiting') break
c62a24d22dc6ed3846ca0d00d802eab58391455f
leosiqueira/uwhpsc_leo
/homework3/newton.py
1,947
3.921875
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 26 10:08:35 2014 @author: leosiqueira """ def solve(fvals, x0, debug = False): """ Estimate the zero of f(x) using Newton's method. *Input* fvals: tuple containing the function to find a root of and its derivative (f, f'). x0: the initial guess debug: logical, prints iterations if debug= True. **Returns** the estimate x satisfying f(x)=0 (assumes Newton converged!) the number of iterations iter.""" # initial guess x = x0 if debug: print 'Initial guess: x = %22.15e' % x0 # Newton iteration to find a zero of f(x) maxiter = 20 tol = 1e-14 for k in range(maxiter): # evaluate function and its derivative: f, fp = fvals(x) if (abs(f) < tol): break # compute Newton increment x: deltax = f / fp # update x: x = x - deltax if debug: print 'After %s iterations, x = %22.15e' % (k+1,x) if (k == maxiter-1): # might not have converged f, fp = fvals(x) if (abs(f) > tol): print '*** Warning: has not yet converged' return x, k+1 else: return x, k def fvals_sqrt(x): """ Return f(x) and f'(x) for applying Newton to find a square root. """ f = x**2 - 4. fp = 2.*x return f, fp def test1(debug_solve=False): """ Test Newton iteration for the square root with different initial conditions. """ for x0 in [1., 2., 100.]: print " " # blank line print 'Initial guess: x = %22.15e' % x0 x,iters = solve(fvals_sqrt, x0, debug=debug_solve) print "solve returns x = %22.15e after %i iterations " % (x,iters) fx,fpx = fvals_sqrt(x) print "the value of f(x) is %22.15e" % fx assert abs(x-2.) < 1e-14, "*** Unexpected result: x = %22.15e" % x
148b89137dcc89452f5cc9a23f58f3228875e529
sayannandi/interviewbit
/arrays/max_distance.py
648
3.5
4
class Solution: # @param A : tuple of integers # @return an integer def maximumGap(self, A): n = len(A) if n == 1: return -1 for i, num in enumerate(A): A[i] = (num, i) A.sort() max_so_far = -1 max_arr = [-1 for i in range(n)] for i in range(n - 1, -1, -1): max_arr[i] = max_so_far max_so_far = max(max_so_far, A[i][1]) ans = -1 for i, (_, idx) in enumerate(A): ans = max(ans, max_arr[i] - idx) return ans if __name__ == '__main__': sol = Solution() print(sol.maximumGap([3, 5, 4, 2]))
63e60ee629985c2d2751c668fc2265eea88985b2
KevinLaam/-EDD-Tarea1_201403888
/Tarea1.py
2,908
4.03125
4
class node_list: def __init__(self,data=None,next=None): self.data=data self.next=next class linked_list: def __init__ (self): self.head= None def insertar(self,data): if not self.head: self.head=node_list(data=data) return x=self.head while x.next : x=x.next x.next=node_list(data=data) def modificar(self,data_se): x=self.head aux=None while x and x.data != data_se: aux=x x=x.next print(x.data) #def searchData(self,data_se): # x=self.head # aux=None # # while x and x.data != data_se: # aux=x # x=x.next # print(x.data) # def searchData2(self,datas): # actual=self.head # encontrar=False # # while actual != None and not encontrar: # # if actual.data == datas: # encontrar=True # else: # actual=actual.next # # print(actual.data) def eliminar(self,data_delete): x=self.head aux=None while x and x.data != data_delete: aux=x x=x.next if aux is None: self.head=x.next elif x: aux.next=x.next x.next=None # def delete_last(self): # temp=self.head # tem2=None # # if temp == None: # print("lista vacia, no se puede eliminar el dato") # # else: # # while temp.next is not None : # temp2=temp # temp=temp.next # # if temp == None: # temp.head=None # else: # temp2.next=None # # print("ultimo:",temp.data) def Listar(self):#the method called print_list node_list=self.head lista=" " if node_list==None: print("lista vacia") else: while node_list!= None: lista+=str(node_list.data) if node_list.next != None: lista+="-->" node_list=node_list.next print(lista) import os s=linked_list() def menu(): """ os.system('cls') """ print("Selecciona una opcion") print("\t1 - Insertar Dato") print("\t2 - Modificar Dato") print("\t3 - Listar Datos") print("\t4 - Eliminar Dato") print("\t9 - salir") while True: menu() opcMenu = input("Inserta el numero de la opcion que desea realizar:") if opcMenu == "1": print("") valor = input("Ingrese el valor a insertar: ") s.insertar(valor) input("Pulsa enter tecla para continuar") elif opcMenu == "2": print("") valor = input("Ingrese el valor a modificar: ") s.modificar(valor) print("modificado") s.print_list() input("Has pulsado 2 pulsa una tecla para continuar") elif opcMenu == "3": print("") s.Listar() input("Pulsa enter tecla para continuar") elif opcMenu == "4": print("") valor = input("Ingrese el valor a eliminar: ") s.eliminar(valor) input("Pulsa enter tecla para continuar") elif opcMenu == "9": break else: print("") input("tecla incorrecta, pulsa enter para continuar") menu()
2ab414ed542eb8ce8acf15474cd3c5d06abbf144
macks2008/theobot
/theobot/timey.py
5,854
4.15625
4
#! /usr/bin/env python import re import time # CC-BY-SA Theopolisme def ordinal(value): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... u'1st' u'2nd' u'3rd' u'4th' u'5th' u'6th' u'7th' u'8th' u'9th' u'10th' u'11th' u'12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ... u'100th' u'111th' u'112th' u'1011th' """ try: value = int(value) except ValueError: return value if value % 100//10 != 1: if value % 10 == 1: ordval = u"%d%s" % (value, "st") elif value % 10 == 2: ordval = u"%d%s" % (value, "nd") elif value % 10 == 3: ordval = u"%d%s" % (value, "rd") else: ordval = u"%d%s" % (value, "th") else: ordval = u"%d%s" % (value, "th") return ordval def txt2timestamp(txt, format): """Attempts to convert the timestamp 'txt' according to given 'format'. On success, returns the time tuple; on failure, returns None.""" ## print txt, format try: return time.strptime(txt,format) except ValueError: try: return time.strptime(txt.encode('utf8'),format) except: pass return None def str2time(str): """Accepts a string defining a time period: 7d - 7 days 36h - 36 hours Returns the corresponding time, measured in seconds.""" if str[-1] == 'd': return int(str[:-1])*24*3600 elif str[-1] == 'h': return int(str[:-1])*3600 else: return int(str) class DiscussionThread(object): """An object representing a discussion thread on a page, that is something of the form: == Title of thread == Thread content here. ~~~~ :Reply, etc. ~~~~ """ def __init__(self,howold): self.content = "" self.timestamp = None self.howold = howold def __repr__(self): return '%s("%s",%d bytes)' \ % (self.__class__.__name__,self.title,len(self.content)) def feedLine(self, line): if not self.content and not line: return self.content += line + '\n' TM = re.search(r'(\d\d):(\d\d), (\d\d?) (\S+) (\d\d\d\d) \(.*?\)', line) if not TM: TM = re.search(r'(\d\d):(\d\d), (\S+) (\d\d?), (\d\d\d\d) \(.*?\)', line) if not TM: TM = re.search(r'(\d{4})\. (\S+) (\d\d?)\., (\d\d:\d\d) \(.*?\)', line) # 18. apr 2006 kl.18:39 (UTC) # 4. nov 2006 kl. 20:46 (CET) if not TM: TM = re.search(r'(\d\d?)\. (\S+) (\d\d\d\d) kl\.\W*(\d\d):(\d\d) \(.*?\)', line) #3. joulukuuta 2008 kello 16.26 (EET) if not TM: TM = re.search(r'(\d\d?)\. (\S+) (\d\d\d\d) kello \W*(\d\d).(\d\d) \(.*?\)', line) if not TM: # 14:23, 12. Jan. 2009 (UTC) pat = re.compile(r'(\d\d):(\d\d), (\d\d?)\. (\S+)\.? (\d\d\d\d) \((?:UTC|CES?T)\)') TM = pat.search(line) # ro.wiki: 4 august 2012 13:01 (EEST) if not TM: TM = re.search(r'(\d\d?) (\S+) (\d\d\d\d) (\d\d):(\d\d) \(.*?\)', line) if TM: TIME = txt2timestamp(TM.group(0),"%d. %b %Y kl. %H:%M (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%Y. %B %d., %H:%M (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%d. %b %Y kl.%H:%M (%Z)") if not TIME: TIME = txt2timestamp(re.sub(' *\([^ ]+\) *', '', TM.group(0)), "%H:%M, %d %B %Y") if not TIME: TIME = txt2timestamp(TM.group(0), "%H:%M, %d %b %Y (%Z)") if not TIME: TIME = txt2timestamp(re.sub(' *\([^ ]+\) *', '', TM.group(0)), "%H:%M, %d %b %Y") if not TIME: TIME = txt2timestamp(TM.group(0), "%H:%M, %b %d %Y (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%H:%M, %B %d %Y (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%H:%M, %b %d, %Y (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%H:%M, %B %d, %Y (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0),"%d. %Bta %Y kello %H.%M (%Z)") if not TIME: TIME = txt2timestamp(TM.group(0), "%d %B %Y %H:%M (%Z)") if not TIME: TIME = txt2timestamp(re.sub(' *\([^ ]+\) *', '', TM.group(0)), "%H:%M, %d. %b. %Y") if TIME: self.timestamp = max(self.timestamp, time.mktime(TIME)) ## pywikibot.output(u'Time to be parsed: %s' % TM.group(0)) ## pywikibot.output(u'Parsed time: %s' % TIME) ## pywikibot.output(u'Newest timestamp in thread: %s' % TIME) def size(self): return len(self.title) + len(self.content) + 12 def toText(self): return "== " + self.title + ' ==\n\n' + self.content def shouldBeArchived(self): if self.timestamp: algo = self.howold reT = re.search(r'^old\((.*)\)$',algo) maxage = str2time(reT.group(1)) old_enough_to_archive = self.timestamp + maxage currenttime = time.time() if old_enough_to_archive < currenttime: # should be archived print "SHOULD BE ARCHIVED!" return True elif self.timestamp + maxage >= time.time(): # shouldn't be archived return False else: # there was no timestamp with the nomination return False
8e4d6287bc73c492a896d3d5ec390cfea9866231
p-brcn/pig
/dice.py
417
3.859375
4
"""The die of the game :^).""" import random class Dice(): """Create a six-sided dice.""" def __init__(self): """Initiate the dice.""" self._sides = 6 random.seed() def roll(self): """Roll the dice and return the number.""" return random.randint(1, self._sides) @property def sides(self): """Get sides of the die.""" return self._sides
95d25e15de2e4a225dea05f91c991463c53d8db1
p-brcn/pig
/game_test.py
6,073
4.09375
4
"""Unit test for the game logic.""" from unittest.mock import patch from unittest import mock import unittest import game import player class TestGameClass(unittest.TestCase): """Test game class.""" def test_init_default_object(self): """Test initiating the game.""" the_game = game.Game() exp = game.Game self.assertIsInstance(the_game, exp) def test_start(self): """. Test what happens if player chooses singleplayer, Test what happpens if player chooses multiplayer, Test what happens if player writes a wrong input and then a correct one, Test what happens if player2 tries to name themselves the same as player1. """ the_game = game.Game() with mock.patch('builtins.input', side_effect=['singleplayer', 'n1']): res = the_game.start() exp = "You chose to play singleplayer!" self.assertEqual(res, exp) with mock.patch('builtins.input', side_effect=['multi', 'n1', 'n2']): res = the_game.start() exp = "You chose to play multiplayer!" self.assertEqual(res, exp) with mock.patch('builtins.input', side_effect=['test', 'single', 'n']): res = the_game.start() exp = "You chose to play singleplayer!" self.assertEqual(res, exp) with mock.patch('builtins.input', side_effect=["m", "n1", "n1", "n2"]): res = the_game.start() exp = "You chose to play multiplayer!" self.assertEqual(res, exp) @patch('random.randint') def test_roll(self, mocked_randint): """Test rolling a die. Test rolling a 1, Test rolling something other than 1. """ the_game = game.Game() with mock.patch('builtins.input', side_effect=['multi', 'n1', 'n2']): the_game.start() mocked_randint.return_value = 1 res = the_game.roll() exp = (f"\n{the_game.otherplayer.name} rolled a 1 and " "got 0 points this round!\n") self.assertEqual(res, exp) mocked_randint.return_value = 5 res = the_game.roll() exp = (f"{the_game.curplayer.name} rolled a 5") self.assertEqual(res, exp) def test_hold(self): """Test if player can hold to get points.""" with mock.patch('builtins.input', side_effect=['single', 'n1']): the_game = game.Game() the_game.start() res = the_game.hold() exp = (f"\n{the_game.curplayer.name} decided to hold\n" f"{the_game.curplayer.name} received " f"{the_game.dice_score} points\n" f"{the_game.curplayer.name} now have " f"{the_game.curplayer.score} points in total!\n") self.assertEqual(res, exp) def test_computer(self): """Test Computer Logic. Test if the computer auto roll works as intended. Test if the computer normal roll works as intended. Test if the computer hold works as intended. Test if the computer calculated works as intended. """ the_game = game.Game() with mock.patch('builtins.input', side_effect=['single', 'n1']): the_game.start() self.assertEqual(the_game.computer_logic(), "auto roll") with mock.patch('random.randint', return_value=2): the_game.computer.inc_rolls() self.assertEqual(the_game.computer_logic(), "rolled") computer_int = the_game.computer.intelligence with mock.patch('random.randint', return_value=computer_int): the_game.computer.inc_rolls() self.assertEqual(the_game.computer_logic(), "hold") the_game.computer.inc_rolls() the_game.computer.add_score(100) self.assertEqual(the_game.computer_logic(), "calculated") def test_cheat(self): """Test cheat command.""" the_game = game.Game() with mock.patch('builtins.input', side_effect=['single', 'n1']): the_game.start() the_game.cheat() res = the_game.curplayer.score == 100 self.assertTrue(res) @patch('random.randint') def test_choose_starter(self, mocked_randint): """Test chosing which player starts.""" the_game = game.Game() player1 = player.Player("Test1") player2 = player.Player("Test2") mocked_randint.return_value = 1 res = the_game.choose_starter(player1, player2) exp = "Player 1 starts" self.assertEqual(res, exp) mocked_randint.return_value = 2 res = the_game.choose_starter(player1, player2) exp = "Player 2 starts" self.assertEqual(res, exp) def test_check_winner(self): """Test checking for a winner.""" the_game = game.Game() with mock.patch('builtins.input', side_effect=['single', 'n1']): the_game.start() res = the_game.check_winner_condition() self.assertIsNone(res) the_game.curplayer.add_score(100) res = the_game.check_winner_condition() exp = "n1" self.assertEqual(res, exp) def test_switch_player(self): """Test switching player turn.""" the_game = game.Game() with mock.patch('builtins.input', side_effect=['multi', 'n1', 'n2']): the_game.start() second_player = the_game.otherplayer.name the_game.switch_player() res = second_player exp = the_game.curplayer.name self.assertEqual(res, exp) def test_check_computer_turn(self): """Test checking if it is computers turn.""" the_game = game.Game() with mock.patch('builtins.input', side_effect=['single', 'n1']): the_game.start() res = the_game.check_computer_turn() self.assertIsNone(res)
64613835c929b1ac62c8bdce72e6cb0ddc439189
seun-beta/Unit-Testing
/fish/test_fish.py
1,070
3.671875
4
import unittest import fish class TestFish(unittest.TestCase): @classmethod def setUpClass(cls): print('setUpClass') @classmethod def tearDownClass(cls): print('tearDownClass') def setUp(self): print('setUp') self.fish_1 = fish.Fish('Jake') self.fish_2 = fish.Fish('Vanessa') def tearDown(self): print('tearDown') pass def test_fullname(self): print('test_fullname') self.assertEqual(self.fish_1.fullname(), 'Jake Fish') self.assertEqual(self.fish_2.fullname(), 'Vanessa Fish') self.fish_1.first_name = 'John' self.assertEqual(self.fish_1.fullname(), 'John Fish') self.assertEqual(self.fish_1.eyelids, False) self.assertEqual(self.fish_1.skeleton, 'bone') self.fish_1.skeleton = 'cartilage' self.assertEqual(self.fish_1.skeleton, 'cartilage') def test_swim(self): print('test_swim') self.assertEqual(self.fish_1.swim(), 'The fish is swimming.') if __name__ == '__main__': unittest.main()
82bdcc6068afdf6b3cf8d25d011477427efdd6a5
Endrju00/History-of-Olympics
/family.py
1,123
3.546875
4
import pandas as pd import matplotlib.pyplot as plt if __name__ == '__main__': athlete_events = pd.read_csv('athlete_events.csv') participants = athlete_events.drop_duplicates('ID')['Name'] # to count gender the objects have to be unique # Prepare data d = {'Firstname': [], 'Surname':[]} for person in participants: data = person.split() d['Firstname'].append(data[0]) d['Surname'].append(data[-1]) # get the last part of the surname df = pd.DataFrame(data=d) top_10 = df['Surname'].value_counts()[1:11] # first is .Jr labels = [x for x in top_10.keys()] values = [top_10[x] for x in top_10.keys()] # Plot plt.style.use('ggplot') fig, ax1 = plt.subplots(1, 1) rects = ax1.bar(labels, values, color=['#03045e', '#032174', '#023E8A', '#015BA0', '#0077B6', '#0096C7', '#00A5D0', '#00B4D8', '#48CAE4', '#6CD5EA']) ax1.bar_label(rects, padding=3, fontsize=15) ax1.set_title("Most popular surnames.", fontsize=16) plt.xlabel("Surnames", fontsize=15) plt.ylabel("Number of occurrences of the surname", fontsize=15) plt.show()
8c24401b4f528b6443f8463bbd53b32661028cd0
HaydenHartley/Sandbox
/oddName.py
177
3.84375
4
name_input = input("enter your name: ") while len(name_input) < 1: name_input = input("enter your name: ") name_length = len(name_input) print (name_input[1:name_length:2])
e4c866e60c92d3713121b35b0492a06a07a72e4b
Athenian-ComputerScience-Fall2020/mad-libs-yesak1
/my_code.py
596
3.890625
4
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # none personname= input("enter a person's name") verb=input('enter a verb') adverb=input('enter an adverb') food=input('enter a food') personname2=input("enter a person's name") verb2=input('enter a verb') adverb2=input('enter an adverb') print (f"There once was a person named {personname} that really liked to {verb} {adverb}. One time, {personname} was eating a {food} and realized that {personname2} wanted to {verb2} \n with them. So {personname} and {personname2} {verb2}ed together {adverb2}")
bf97eaf66c4402ca38a0a936c43fceaa0ba26351
alexolmedo/ComputacionDistribuida
/2018.01.04.cuentas.py
1,516
3.5
4
class Cuenta: tipo = "" numero = "" saldo = 0.0 def __init__(self, argTipo, argNumero, argSaldo): self.tipo=argTipo self.numero=argNumero self.saldo=argSaldo def debito (self, monto): self.saldo -= monto def credito (self, monto): self.saldo += monto class Cliente: nombre = "" cedula = 0 cuentas = [] def __init__(self, argNombre, argCedula): self.nombre = argNombre self.cedula = argCedula def agregarCuenta(self, cuenta): self.cuentas.append(cuenta) class Transaccion: tipo = "" timestamp = "" monto = 0.0 lugar = "" def __init__(self, argTipo, argTimestamp, argMonto, argCuenta, argCliente, argLugar): self.tipo = argTipo self.timestamp = argTimestamp self.monto = argMonto self.cuenta = argCuenta self.usuario = argCliente self.lugar = argLugar def retiro(self): self.cuenta.debito(self.monto) def deposito(self): self.cuenta.credito(self.monto) cliente1 = Cliente("Alexander Olmedo", "1724885775") cuentaC1 = Cuenta("Ahorros","12345",500.25) cliente1.agregarCuenta(cuentaC1) cliente2 = Cliente("Ronny Cabrera", "1236541236") cuentaC2 = Cuenta("Corriente", "23651", 700.12) cliente2.agregarCuenta(cuentaC2) print cuentaC1.tipo, cuentaC1.numero, cuentaC1.saldo t1 = Transaccion("Retiro", "01-04-2018", 456.25, cuentaC1, cliente1, "Quito") t1.retiro() print cuentaC1.tipo, cuentaC1.numero, cuentaC1.saldo
b68e9ef0f7ac561544d0c87c516c20a8a6261dab
saikumarballu/PythonPrograms
/palindrom.py
363
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 2 14:59:11 2019 @author: saib org=a.lower().split(",") print(org) b=a.lower().split(",") print(b) c='' for s in b: c=c+s print(c[::-1]) """ a="A man, a plan, a canal; Panama" b=list(a.lower()) alphas = list(filter(lambda x:x.isalpha(),b)) print(alphas) print("True" if alphas==alphas[::-1] else "False")
1868740c233aab72a24aedb0b3b2fb3014f14118
saikumarballu/PythonPrograms
/RegularExp.py
2,058
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 3 10:14:04 2019 @author: saib ^ - Begining of String or expression $ - Ending of String or an Expression + - One or more occurance of previous character * - import re pat1 = re.compile('^Hello') mystr = "Hi Hello World" if pat1.search(mystr): print("Matched") else: print("Not Matched") pat2 = re.compile('World$') if pat2.search(mystr): print("Matched") else: print("Not Matched") import re #pat1 = re.compile('^\d{10}$') # Matching 10 digits pat1 = re.compile('^(\+91)?\d{10}$') # '^(\+91) is optional and later it should have 10 digits if pat1.search('+917894561230'): # '^\d+$' Matching any number of digits print("It is Number") else: print("Not Just a Number") import re #pat1 = re.compile('^\d{10}$') # Matching 10 digits pat1 = re.compile('^(\+91)?(\d{10})$') searchobj = pat1.search('+911234567890') if searchobj: print(searchobj.group(0)) # Entire match print(searchobj.group(1)) # first Group print(searchobj.group(2)) # Second Group print("It is Number") else: print("Not Just a Number") p = re.compile('\d+') print(p.findall('12 Number,11 pipes,10 Cars')) # returns only numbers in the string email = re.copmile('(\w+)@(\w+\.com)') import re pat1=re.compile('^Hello',re.IGNORECASE) # ignore case while searching email = re.copmile('(\w+)@(\w+\.com)') mystr = "hello World" if pat1.search(mystr): print("Matched") else: print("Not Matched") if pat1.search(mystr): print("Matched") else: print("Not Matched") import re p= re.compile(r'\W+') # removes all non-words and returns only words lists= p.split('This is a pattern split, simple and short, easier version of split().') print(p.split('This is a pattern split, simple and short, easier version of split().',3)) """ import re p=re.compile('(blue|white|red)') print(p.sub('color', 'blue socks and red shoes')) # Replace pattern with color print(p.sub('color', 'blue socks and red shoes', count=1)) # Replace pattern with color
aa1d0cc8b6e7b6f0ecb3ca5921ae75026901a9ea
Paul-Cl-ark/cli_games
/rock-paper-scissors.py
2,587
3.96875
4
from random import choice from time import sleep moves = ('rock', 'paper', 'scissors') def print_winner(winner): print('\n') if winner == 'draw': print('DRAW...') elif winner == 'computer': print('YOU LOSE THIS ROUND!') else: print('YOU WIN THIS ROUND!') print('\n--------------------------------------') def calculate_winner(computer_move, player_move): if computer_move == player_move: return 'draw' elif computer_move == 'rock' and player_move == 'scissors' \ or computer_move == 'scissors' and player_move == 'paper' \ or computer_move == 'paper' and player_move == 'rock': return 'computer' else: return 'player' def get_symbol(input): symbol_dictionary = { 'rock': '👊', 'paper': '✋', 'scissors': '✌️' } return symbol_dictionary[input] def print_moves(computer_move, player_move): print('\n', get_symbol(computer_move), '🆚', get_symbol(player_move), sep=" ") def count_down(): sleep(0.3) print('\n3...') sleep(0.85) print('2...') sleep(0.85) print('1...\n') sleep(0.85) def get_player_move(): player_move = input('\nEnter \'rock\', \'paper\' or \'scissors\'... ') if player_move not in moves: print('\nTry again...') sleep(1) get_player_move() return player_move def play(): computer_move = choice(moves) player_move = get_player_move() count_down() print_moves(computer_move, player_move) winner = calculate_winner(computer_move, player_move) print_winner(winner) return winner play_again = True scores = { 'computer': 0, 'player': 0, 'draw': 0 } while play_again: print('\nROCK 👊, PAPER ✋, SCISSORS ✌️!\n\nBEST OF 3!') while scores['computer'] < 3 and scores['player'] < 3: winner = play() scores[winner] += 1 print('\n') print('COMPUTER:', scores['computer'], ' d[o_0]b') print('YOU:', scores['player'], ' 0w0') print('DRAW:', scores['draw'], ' =-= ') print('\n--------------------------------------') else: print('\n') if winner == 'computer': print('YOU LOSE!') else: print('YOU WIN!') play_again_choice = input( '\nPlay again? Enter \'yes\' to continue playing... ') print('\n--------------------------------------') play_again = play_again_choice[0] == 'y' scores = {k: 0 for k, v in scores.items()}
44a4dda12809ebd8ba6e3c6c52c96e130a0fa7e1
PrateekMinhas/Python
/assignment14.py
1,555
4.4375
4
Q.1- Write a python program to print the cube of each value of a list using list comprehension. lst=[1,2,3,4,5] lstc=[i**3 for i in lst] print(lstc) #Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension. lst_pr= [ i for i in range(2,int(input("Enter the end input of the range for the prime numbers"))) if all(i%j!=0 for j in range(2,i)) ] #all returns true if all items in a seq are true print(lst_pr) #Q.3- Write the main differences between List Comprehension and Generator Expression. """generator expression uses () while list comprehension uses [] list comprehension returns a list that we can iterate and access via index but same is not the case in generator expression""" #LAMBDA & MAP #Q.1- Celsius = [39.2, 36.5, 37.3, 37.8] Convert this python list to Fahrenheit using map and lambda expression. Celsius = [39.2, 36.5, 37.3, 37.8] far=list(map(lambda i:(i * (9/5)) + 32,Celsius)) print(far) #Q.2- Apply an anonymous function to square all the elements of a list using map and lambda. lst1=[10,20,30,40,50] lstsq=list(map(lambda i:i**2,lst1)) print(lstsq) #FILTER & REDUCE #Q.1- Filter out all the primes from a list. lis3 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for m in range(2, 18): lis3 = list(filter(lambda x: x == m or x % m and x > 1, lis3)) print(lis3) #Q.2- Write a python program to multiply all the elements of a list using reduce. from functools import reduce lis4 = [1,2,3,4,5,6,7,8,9,10] mul = reduce(lambda x, y: x*y,lis4) print(mul)
cc1aa3c2ec38ffc869b942af0491d3c44baf9ba1
PrateekMinhas/Python
/assignment3.py
2,048
4.25
4
#Q.1- Create a list with user defined inputs. ls=[] x=int(input("enter the number of elements")) for i in range (x): m=input() ls.append(m) print (ls) #Q.2- Add the following list to above created list: #[‘google’,’apple’,’facebook’,’microsoft’,’tesla’] ls1=['google','apple','facebook','microsoft','tesla'] ls.extend(ls1) print(ls) #Q.3 - Count the number of time an object occurs in a list. ls2=[1,2,3,3,'rabbit',',','$','$',4,7] x = input("enter an element from the string to know its occurence in it") print (ls2.count(x)) #Q.4 - create a list with numbers and sort it in ascending order. ls3=[1,2,45,6,8,4,3,6,8,9,0,8,67,-4] ls3.sort() print (ls3) #Q.5 - Given are two one-dimensional arrays A and B which are sorted in ascending order. #Write a program to merge them into a single sorted array C that contains every item from #arrays A and B, in ascending order. [List] A=[1,3,4,6,7,-8,-98] B=[1,4,5,3,6,56,33,23] C=[12,34,5] A.sort() #sorts A B.sort() #sorts B C.sort() #sorts C A.extend(B) #adds b to A C.extend(A) #adds new A to C C.sort() #sorts the new C print(C)#prints C #Q.6 - Count even and odd numbers in that list. odd=[] even=[] for y in C: if y%2==0: even.append(y) else: odd.append(y) print ("even numbers are ",len(even)) print ("odd numbers are ",len(odd)) #TUPLE #Q.1-Print a tuple in reverse order. tup=('apple','mango','banana') rev=reversed(tup) print(tuple(rev)) #Q.2-Find largest and smallest elements of a tuples. tup1=(1,2,4,5,6,78,-90) print(max(tup1)) print(min(tup1)) #STRINGS #Q.1- Convert a string to uppercase. string='im so sister shook ryt now !!' print (string.upper()) #Q.2- Print true if the string contains all numeric characters. string2=str(input("enter a string")) print (string2.isdigit()) #Q.3- Replace the word "World" with your name in the string "Hello World". string3='Hello World' print(string3.replace('World','Prateek Minhas'))
46e9979cd8a2425b46f7f4bf6917516fd64ca081
dasherinuk/homework
/homework_left.py
284
4
4
array=[] input_amount=int(input("Enter the amount of elements")) for i in range (0,input_amount): element_input=int(input("Enter your element")) array.append(element_input) print(array) for i in range(len(array)-1): array[i] = array[i+1] array[-1]=0 print(array)
b07f52dcbe8954d40666807cabcf0218744d7524
dasherinuk/homework
/homework_31.10.py
309
3.9375
4
array=[] amount=int(input("Enter the amount of elements")) for i in range (0,amount): element_input=int(input("Enter your element")) array.append(element_input) print(array) for i in range(0,amount): if array[i] > 0: array[i]=1 elif array[i] < 0: array[i]=-1 print(array)
ec9cf19559140c672c666ad15ad01ac90169a805
dasherinuk/homework
/change_1_2_array.py
577
3.53125
4
input_user=int(input()) main_array=[] for i in range(0,input_user): array = [int(r) for r in input().split()] main_array.append(array) len_array=input_user # 1 2 3 # 4 5 6 # 7 8 9 sum_first_array=sum(main_array[0]) ##for index in range(0,len_array): ## sum_first_array+=main_array[index][0] sum_last_array=sum(main_array[-1]) ##for index in range(0,len_array): ## sum_last_array+=main_array[index][-1] if sum_first_array > sum_last_array: main_array[0], main_array[-1] = main_array[-1], main_array[0] print(*main_array, sep="\n")
dded39863ce76844ffa7f1e8ae79fa54a9619487
0xch25/Data-Structures
/2.Arrays/Problems/Height Checker.py
769
4.09375
4
'''Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: Current array : [1,1,4,2,1,3] Target array : [1,1,1,2,3,4] On index 2 (0-based) we have 4 vs 1 so we have to move this student. On index 4 (0-based) we have 1 vs 3 so we have to move this student. On index 5 (0-based) we have 3 vs 4 so we have to move this student. ''' def heightChecker(heights): count = 0 s = sorted(heights) for i in range(len(heights)): if heights[i] != s[i]: count += 1 return count heights=[1,1,4,2,1,3] print(heightChecker(heights))
8ecd98ebb901cb5a26893a09b4057c6362e43f6f
0xch25/Data-Structures
/2.Arrays/Problems/Number of Good Pairs.py
610
3.6875
4
''' Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. Example 1: Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed ''' class Solution: def numIdenticalPairs(self,nums): hashmap={} count=0 for num in nums: if num in hashmap: count+=hashmap[num] hashmap[num]+=1 else: hashmap[num]=1 return count s=Solution() nums=[1,2,3,1,1,3] print(s.numIdenticalPairs(nums))
cef5dd3e9ca6fe8f9ce33b6e4f8aca9e35f368f4
0xch25/Data-Structures
/2.Arrays/Problems/Running sum of 1D Array.py
497
4.21875
4
'''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]''' def runningSum(nums): sum =0 for i in range(len(nums)): temp=nums[i] nums[i] =nums[i] +sum sum+=temp return nums nums=[1,1,1,1,1] nums2=[1,2,3,4] print(runningSum(nums)) print(runningSum(nums2))
7816262c0cda16be8c7d255780fba2c1203905a8
0xch25/Data-Structures
/3.Stacks/Palindrome using Stacks.py
544
4.15625
4
'''Program to check weather the given string is palindrome or not''' class Stack: def __init__(self): self.items = [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] s = Stack() str= input("enter the string:") for char in str: s.push(char) str2="" while not s.is_empty(): str2 = str2 + s.pop() if str == str2: print('The string is a palindrome') else: print('The string is not a palindrome')
8cf6f4add4206848befc6559c83f207033d67529
0xch25/Data-Structures
/2.Arrays/Problems/Check If N and Its Double Exist.py
590
4.09375
4
''' Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 10 is the double of M = 5,that is, 10 = 2 * 5. ''' def checkIfExist(arr): for i in range(0, len(arr)): for j in range(0, len(arr)): if arr[i] == arr[j] * 2 and j != i: return True return False arr=[1,2,3,4,5] print(checkIfExist(arr))
e3655a11ecdd6541eabc9ba2e942c8184360e79d
0xch25/Data-Structures
/7.Graphs/Problems/Range Sum of BST.py
668
3.9375
4
''' https://leetcode.com/problems/range-sum-of-bst/ Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32 ''' def rangeSumBST(root, L, R): if root is None: return 0 if root.val > R: return rangeSumBST(root.left, L, R) if root.val < L: return rangeSumBST(root.right, L, R) return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R) root = [10,5,15,3,7,None,18] L = 7 R = 15 print(rangeSumBST(root,L,R))
532c4d70a4f5037a4a520e4ffe3a1edd92cb2ff0
0xch25/Data-Structures
/2.Arrays/Squares of a Sorted Array.py
490
4.0625
4
'''Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] One Line Solution: def sortedSquares(self, A: List[int]) -> List[int]: return sorted([x**2 for x in A]) ''' def sortedSquares(A): B = [] for i in A: B.append(i * i) return sorted(B) A=[1,2,3,21,0] print(sortedSquares(A))
d8893f260d7836c4dae56181bee4c081b2097bd1
0xch25/Data-Structures
/1.Linked List/Detect Loop(2ptr).py
1,005
4.0625
4
''' Given a linked list, determine if it has a cycle in it. ''' class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert(self, data): newNode = Node(data) if self.head: current = self.head while current.next: current = current.next current.next = newNode else: self.head = newNode print("newnode inserted:",data) def detectLoop(self): slow_p = self.head fast_p = self.head while fast_p and fast_p.next: slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return True return False L = LinkedList() L.insert(3) L.insert(2) L.insert(0) L.insert(-4) L.head.next.next.next.next=L.head.next #Create a Loop i.e last node will point to the first node print(L.detectLoop())
85d22aeebd8243443c2210b065efc2636c8bde8c
0xch25/Data-Structures
/1.Linked List/Intersection of Two Linked Lists.py
982
3.84375
4
''' Write a Function to find the node at which the intersection of two singly linked lists begins Approach1:using Dictionaries def getIntersectionNode(headA,headB): dict = {} while headA: dict[headA] = 1 headA = headA.next while headB: if headB in dict: return headB headB = headB.next return None ''' #Approach2:Optimized Version def getIntersectionNode1(headA,headB): tempA = headA lenA = 0 while (tempA): lenA += 1 tempA = tempA.next tempB = headB lenB = 0 while (tempB): lenB += 1 tempB = tempB.next if lenA > lenB: while (lenA != lenB): headA = headA.next lenA -= 1 if lenA < lenB: while (lenA != lenB): headB = headB.next lenB -= 1 while (headA and headB): if headA == headB: return headA headA = headA.next headB = headB.next return None
e70a83469f49d7f0dcb0ce94f8621e1b8b032836
0xch25/Data-Structures
/10.Strings/Problems/Shuffle String.py
776
4.1875
4
''' Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Example 1: Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. Example 2: Input: s = "abc", indices = [0,1,2] Output: "abc" Explanation: After shuffling, each character remains in its position. Example 3: Input: s = "aiohn", indices = [3,1,4,2,0] Output: "nihao" ''' def restoreString(s,indices): res = [" "] * len(s) for i in range(len(s)): res[indices[i]] = s[i] return "".join(res) s = "aiohn" indices = [3,1,4,2,0] print(restoreString(s,indices))
8488bf556555ef239437cef6f2449cc0414074b2
0xch25/Data-Structures
/1.Linked List/problems/Convert Binary Number in a Linked List to Integer.py
470
3.875
4
''' Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. Example 1: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 ''' def getDecimalValue(head): s = '' while (head): s += str(head.val) head = head.next return int(s, 2)
79ca4e928dcab2736833269027a8209c2965d47d
0xch25/Data-Structures
/3.Stacks/Postfix Evaluation.py
760
3.84375
4
def postfix_evaluation(str): s=str.split() n=len(s) stack =[] for i in range(n): if s[i].isdigit(): stack.append(int(s[i])) elif s[i]=="+": a=stack.pop() b=stack.pop() stack.append(int(a)+int(b)) elif s[i]=="*": a=stack.pop() b=stack.pop() stack.append(int(a)*int(b)) elif s[i]=="/": a=stack.pop() b=stack.pop() stack.append(int(b)/int(a)) elif s[i]=="-": a=stack.pop() b=stack.pop() stack.append(int(b)-int(a)) return stack.pop() str="100 200 + 2 / 5 * 7 +" str2="2 3 1 * + 9 -" print(postfix_evaluation(str)) print(postfix_evaluation(str2))
933bb92720f57065456529f36a6ceb0adf3cb8da
josemigueldev/tkinter-crud
/main.py
5,611
3.734375
4
from tkinter import * from tkinter import ttk import sqlite3 class Product: db_name = "database.db" def __init__(self, window): self.window = window self.window.title("Aplicacion de productos") # creating a frame container frame = LabelFrame(self.window, text="Registrar un nuevo producto") frame.grid(row=0, column=0, columnspan=2, pady=20) # label and name input Label(frame, text="Nombre: ").grid(row=0, column=0) self.name = Entry(frame) self.name.focus() self.name.grid(row=0, column=1) # label and price input Label(frame, text="Precio: ").grid(row=1, column=0) self.price = Entry(frame) self.price.grid(row=1, column=1) # button add product self.save_button = ttk.Button(frame, text="Guardar Producto", command=self.add_product, cursor="hand1") self.save_button.grid(row=2, columnspan=2, sticky="WE") # ouput messages self.message = Label(self.window, text="mensaje", fg="blue") self.message.grid(row=1, columnspan=2, sticky="WE") # table self.table = ttk.Treeview(self.window, height=10, columns=("#1", "#2")) self.table.grid(row=2, column=0, columnspan=2) self.table.heading("#0", text="Id") self.table.heading("#1", text="Nombre") self.table.heading("#2", text="Precio") # buttons edit_button = ttk.Button(self.window, text="Editar", command=self.edit_product, cursor="hand1") edit_button.grid(row=3, column=0, sticky="WE") delete_button = ttk.Button(self.window, text="Eliminar", command=self.delete_product, cursor="hand1") delete_button.grid(row=3, column=1, sticky="WE") # filling the rows self.get_products() def run_query(self, query, parameters=()): with sqlite3.connect(self.db_name) as conn: cursor = conn.cursor() # obtenemos un cursor a la conexion result = cursor.execute(query, parameters) # ejecutamos una consulta conn.commit() # guardamos los cambios return result def get_products(self): # Limpiando tabla records = self.table.get_children() for element in records: self.table.delete(element) # Hacer consulta query = "SELECT * FROM products ORDER BY name ASC" rows = self.run_query(query) # obtengo las filas for row in rows: self.table.insert("", END, text=row[0], values=(row[1], row[2])) def add_product(self): if self.validation_product(): query = "INSERT INTO products VALUES(NULL, ?, ?)" parameters = (self.name.get(), self.price.get()) self.run_query(query, parameters) self.message["text"] = f"El producto {self.name.get()} ha sido agregado" self.message["fg"] = "green" self.name.delete(0, END) # limpiamos la caja de texto name self.price.delete(0, END) # limpiamos la caja de texto price else: self.message["text"] = "El nombre y el precio son requeridos" self.message["fg"] = "red" self.get_products() # refrescamos los productos def validation_product(self): # validar si el campo name y price no estan vacios return len(self.name.get()) != 0 and len(self.price.get()) != 0 def delete_product(self): id_item = self.table.item(self.table.selection())["text"] if id_item: name_product = self.table.item(self.table.selection())["values"][0] query = "DELETE FROM products WHERE id = ?" self.run_query(query, (id_item,)) self.message["text"] = f"El producto {name_product} ha sido eliminado" self.get_products() else: self.message["text"] = "Seleccione un item a eliminar" self.message["fg"] = "red" return def edit_product(self): id_item = self.table.item(self.table.selection())["text"] if id_item: name = self.table.item(self.table.selection())["values"][0] price = self.table.item(self.table.selection())["values"][1] self.edit_window = Toplevel() self.edit_window.title("Editar Producto") Label(self.edit_window, text="Nombre").grid(row=0, column=0) new_name = Entry(self.edit_window, textvariable=StringVar(value=name)) new_name.grid(row=0, column=1) Label(self.edit_window, text="Precio").grid(row=1, column=0) new_price = Entry(self.edit_window, textvariable=IntVar(value=price)) new_price.grid(row=1, column=1) update_button = Button( self.edit_window, text="Update", command=lambda:self.edit_records(new_name.get(), new_price.get(), id_item) ) update_button.grid(row=2, columnspan=2) else: self.message["text"] = "Seleccione un item a editar" self.message["fg"] = "red" return def edit_records(self, new_name, new_price, id_item): query = "UPDATE products SET name = ?, price = ? WHERE id = ?" parameters = (new_name, new_price, id_item) self.run_query(query, parameters) self.edit_window.destroy() self.message["text"] = f"Record {new_name} update successfully" self.message["fg"] = "green" self.get_products() if __name__ == "__main__": window = Tk() application = Product(window) window.mainloop()
5075c9230e0ed97262d585dc7f39079e6fe265f3
jjefferson34/projects
/projects/dataanalysis.py
380
3.71875
4
import json def findAverageAge(data): sum = 0 for entry in data: sum += int(entry["age"]) return sum / len(data) def main(): file = open("allanswers.json", "r") data = json.load(file) print("Analyzing data...") averageAge = findAverageAge(data) print("Average age: %d" %averageAge) if __name__ == "__main__": main()
fb6785fbbc7e3514f8eebc0c727c270cb3cabdba
agencer/PythonCourse_Summer2020
/hw_gencer.py
6,179
3.578125
4
import random from datetime import datetime # Let's start with the classes for different non liquid investments. # The question asks for inheritence. So let's create one: class NonLiquidItems(): def __init__(self, value, name): self.name = name self.value = value class Stock(NonLiquidItems): def __init__(self, value, name): NonLiquidItems.__init__(self, int(value), name) class MutualFund(NonLiquidItems): def __init__(self, name): NonLiquidItems.__init__(self, float(1), name) class Bond(NonLiquidItems): def __init__(self, value, name): NonLiquidItems.__init__(self, int(value), name) # Let's continue with our Portfolio class where we have # 1) cash attitude # 2) stock value attitude # 3) mutual_funds value attitude class Portfolio(): def __init__(self): self.cash = float(0) self.item_dictionary = {} self.value_dictionary = {} self.history_string = "Here is the list of all transactions ordered by time:\n" # cool! Now let's create the Porfoglio class methods for cash addition, # substraction, and the purchase of other items. def addCash(self, add): if type(add) not in [int, float]: raise TypeError("\nInput should be either integer or float.") else: self.cash += add now = datetime.now() date_time = now.strftime("%d/%m/%Y at %H:%M:%S.%f") output = "{} unit cash is deposited. Current deposited unit cash is {}.\n".format(add, self.cash) self.history_string += f"{date_time},\n{output}" def withdrawCash(self, remove): if type(remove) not in [int, float]: raise TypeError("Input should be either integer or float.") elif self.cash < remove: raise ValueError("The amount desired to be withdrawn cannot be greater than the deposited cash.") else: self.cash -= remove output = "{} unit cash is withdrawm. Current deposited unit cash is {}.\n".format(remove, self.cash) now = datetime.now() date_time = now.strftime("%d/%m/%Y at %H:%M:%S.%f") self.history_string += f"{date_time},\n{output}" # Yes! Now let's create functions for the stock purchase and sale: def buyItem(self, number, item): if type(number) not in [int, float]: raise TypeError("Stock input must be integer while mutual funds input must be float.") elif self.cash < number*item.value: raise ValueError("The desired item requires greater unit cash than the deposited cash.") else: self.withdrawCash(number*item.value) self.value_dictionary.update({item.name : item.value}) if item.name in self.item_dictionary: dict_tempo = {"{}".format(item.name) : self.item_dictionary[item.name] + number} self.item_dictionary.update(dict_tempo) else: dict_tempo = {"{}".format(item.name) : number} self.item_dictionary.update(dict_tempo) output = "{} unit cash is spent to buy {} number of {}.\n".format((number*item.value), number, item.name) now = datetime.now() date_time = now.strftime("%d/%m/%Y at %H:%M:%S.%f") self.history_string += f"{date_time},\n{output}" # Yes! Now let's create functions for the stock purchase and sale: def buyStock(self, number, name): self.buyItem(int(number), name) def buyMutualFund(self, number, name): self.buyItem(float(number), name) def buyBond(self, number, name): self.buyItem(int(number), name) #Now let's update selling methods: def sellItem(self, item, number, item_type): if type(number) not in [int, float]: raise TypeError("Stock input must be integer while mutual funds input must be float.") elif item not in self.item_dictionary: raise ValueError(f"You do not have any {item} to sell.") elif self.item_dictionary[item] < number: raise ValueError("You do not have enough {} unit item to sell. You can sell {} at max.".format(item, self.item_dictionary[item])) else: if item_type == "stock": profit = round(random.uniform(0.5*(number*portfolio.value_dictionary[item]), 1.5*(number*portfolio.value_dictionary[item])),2) self.addCash(profit) self.item_dictionary.update({item: self.item_dictionary[item]-number}) elif item_type == "mutualfund": profit = round(random.uniform(9,1.1),2) self.addCash(profit) self.item_dictionary.update({item: self.item_dictionary[item]-number}) elif item_type == "bond": profit = round(number*random.normalvariate(portfolio.value_dictionary[item], 0.1*(portfolio.value_dictionary[item]))) self.addCash(profit) self.item_dictionary.update({item: self.item_dictionary[item]-number}) else: raise TypeError("Item type is not recognized. Choose either \'stock, mutualfund, or bond\'") output = "{} cash is earned from the sale of {} unit of {} item.\n".format(profit, number, item) now = datetime.now() date_time = now.strftime("%d/%m/%Y at %H:%M:%S.%f") self.history_string += f"{date_time},\n{output}" # Let's create the selling functions: def sellStock(self, item, number): self.sellItem(item, int(number), item_type = "stock") def sellMutualFund(self, item, number): self.sellItem(item, float(number), item_type = "mutualfund") def sellBond(self, item, number): self.sellItem(item, int(number), item_type = "bond") # Now, let's define a history method. def history(self): print(self.history_string) # Main portfolio = Portfolio() #Creates a new portfolio portfolio.addCash(300.50) #Adds cash to the portfolio s = Stock(20, "HFH") #Create Stock with price 20 and symbol "HFH" portfolio.buyStock(5, s) #Buys 5 shares of stock s mf1 = MutualFund("BRT") #Create MF with symbol "BRT" mf2 = MutualFund("GHT") #Create MF with symbol "GHT" portfolio.buyMutualFund(10.3, mf1) #Buys 10.3 shares of "BRT" portfolio.buyMutualFund(2, mf2) #Buys 2 shares of "GHT" print("cash: ", portfolio.cash, "\nOther items: ", portfolio.item_dictionary) #Prints portfolio portfolio.sellMutualFund("BRT", 3) #Sells 3 shares of BRT portfolio.sellStock("HFH", 1) #Sells 1 share of HFH portfolio.withdrawCash(50) #Removes $50 portfolio.history() #Prints a list of all transactions ordered by time # Extra b1 = Bond(10, "TBill") portfolio.buyBond(5, b1) portfolio.sellBond("TBill", 3) portfolio.sellBond("TBill", 1) portfolio.history() #Prints a list of all transactions ordered by time
4f45c92ee32651269b186c7ac51ce7897ed1ab1c
memuller/bunnyscript
/Python/14-lists-index.py
473
4.125
4
# -*- coding: utf-8 -*- ''' Faça um programa exatamente como o anterior, mas que possua um for no qual a variável de controle represente o índice de cada elemento, ao invés de o elemento em si. for i blabla: #aqui i deve ser o índice de cada elemento ''' # len(lista) # retorna a quantidade de elementos de uma lista, string, etc i=0 lista="eu gosto de você", "eu gosto de barcos grandes" for i in range(0,len(lista)): print "{}: {}".format(i+1, lista[i])
e30453364c48bdf2673d717cbd4ec9e06eca6581
memuller/bunnyscript
/Python/17-list-duplicates.py
892
4.125
4
# -*- coding: utf-8 -*- ''' Escreva um programa que leia palavras fornecidas pelo usuário. Caso a palavra não tenha sido fornecida anteriormente, a adicionamos em uma lista. Paramos de ler palavras quando o usuário não inserir nenhuma. Ao final do programa, imprimimos a lista das palavras não-repetidas inseridas. ''' i=0 words=list() word=raw_input("Digite uma palavra: ") words.append(word) while "uma coisa" != "outra coisa": insira=True word=raw_input("Digite uma palavra: ") if(word == ""): break for i in range(0,len(words)): if word == words[i]: insira=False if insira: words.append(word) # works well enough. mas novamente, posso só #...assumir que sempre quero inserir a palavra que estou lendo agora. # o loop me faz mudar de idéia ou não, mas a cada nova palavra # estou disposto a inserir. print words
a2fb281d1a4a402573494612e7d752c5440e3f17
jamesmili/BattleShip
/Game.py
1,601
4
4
from State import * def main(): print "Rules for battleship: \n" print "1) Each Player gets two boards, and five ships" print "2) Objective is to sink all of your opponents ships" print "3) Firing shots by typing coordinates 'A', 3" print "4) You can only have one length 2 ship, two length 3 ships, one length 4 ship, and one length 5 ship" p1 = State("Player1") p2 = State("Player2") #set up Battleships print "Player 1 Setup Battleships\n" while p1.shipsavailable != []: p1.printShipBoard() sx, sy = input("Enter starting coordinate of ship: ") ex, ey = input("Enter ending coordinate of ship: ") p1ship = Ship(Coordinates(sx, sy), Coordinates(ex, ey)) p1.setShip(p1ship) print "Player 2 Setup Battleships\n" while p1.shipsavailable != []: p2.printShipBoard() sx, sy = input("Enter starting coordinate of ship: ") ex, ey = input("Enter ending coordinate of ship: ") p2ship = Ship(Coordinates(sx, sy), Coordinates(ex, ey)) p2.setShip(p2ship) #start game while True: print "Player 1's Turn" p1.printP2Board(p2) p1mx, p1my = input("Enter firing coordinate (ex. 'A', 3): ") p1.fire(Coordinates(p1mx, int(p1my)), p2) if p1.isGameOver(p2): break print "Player 2's Turn" p2.printP2Board(p1) p2mx, p2my = input("Enter firing coordinate (ex. 'A', 3): ") p2.fire(Coordinates(p2mx,int(p2my)), p1) if p2.isGameOver(p1): break if __name__ == "__main__": main()
0f0f6fcd447b17773cd930fb8b47b1e06a8f2a8a
ethyl2/Hash-Tables
/src/tk/sorting.py
417
4.03125
4
d = { "foo": 12, "bar": 17, "qux": 2 } # Sorting by Key: items = list(d.items()) print(items) items.sort() print(items) for i in items: print(f'{i[0]}: {i[1]}') print('\n') # Sort by Value: items = list(d.items()) print(items) """ def get_key(e): return e[1] ​ items.sort(key=get_key) """ items.sort(key=lambda e: e[1], reverse=True) print(items) for i in items: print(f'{i[0]}: {i[1]}')
d1667225c113c51c6bd4bdca42a55d7c129bb348
ethyl2/Hash-Tables
/src/tk/indexing.py
588
3.640625
4
records = [ ("Alice", "Engineering"), ("Bob", "Sales"), ("Carol", "Sales"), ("Dave", "Engineering"), ("Erin", "Engineering"), ("Frank", "Engineering"), ("Grace", "Marketing") ] def build_index(rec): idx = {} for r in rec: name, dept = r if dept not in idx: idx[dept] = [] idx[dept].append(name) return idx idx = build_index(records) # print all the departments for i in idx: print(i) # print everyone in Engineering: print(idx["Engineering"]) # print entire idx for i in idx: print(f'{i}:{idx[i]}')
f37fb441250ae026c201842c0200a4e9b2734fe0
josecgomezvazquez/SudokuSolver
/sudokuGenerator.py
3,151
4.46875
4
# Used for randomizing from random import sample # Sudoku Generator """ Begin the creation of the board """ base = 3 # Size of the base of a 3x3 square side = base * base # Size of the side of a sudoku board # Pattern for a baseline solution # r = rows # c = columns def pattern(r, c): return (base * (r % base) + r // base + c) % side # Randomize rows and columns (of valid base return) def shuffle(s): return sample(s, len(s)) rBase = range(base) # Row base rows = [g * base + r for g in shuffle(rBase) for r in shuffle(rBase)] cols = [g * base + c for g in shuffle(rBase) for c in shuffle(rBase)] nums = shuffle(range(1, base * base + 1)) # Produce sudoku board using randomized baseline pattern board = [[nums[pattern(r, c)] for c in cols] for r in rows] # Testing the first print looks good for line in board: print(line) print('\n') # Just to separate the randomzied boards """ End of creation of the baord """ """ Begin the removal of random pieces of the board """ # Removing numbers to make things look like a sudoku puzzle squares = side * side empties = squares * 3 // 4 for p in sample(range(squares), empties): board[p // side][p % side] = 0 numSize = len(str(side)) for line in board: print("["+" ".join(f"{n or '.':{numSize}}" for n in line)+"]") print('\n') """ End of the removal of random pieces of the board """ def printBoard(board): for i in range(len(board)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") for j in range(len(board)): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print(board[i][j]) else: print(str(board[i][j]) + " ", end="") def findEmpty(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 0: return (i, j) # row, col return None def valid(bo, num, pos): # Check row for i in range(len(bo[0])): if bo[pos[0]][i] == num and pos[1] != i: return False # Check column for i in range(len(bo)): if bo[i][pos[1]] == num and pos[0] != i: return False # Check box box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if bo[i][j] == num and (i,j) != pos: return False return True def solveBoard(board): find = findEmpty(board) if not find: return True else: row, col = find for i in range(1, 10): if valid(board, i, (row, col)): board[row][col] = i if solveBoard(board): return True board[row][col] = 0 return False printBoard(board) solveBoard(board) print('\n\n') printBoard(board)
b8426fb3918281d063f0d7077e1d8a3caf5cf382
SabiulSabit/Polynomial-Equation
/B.py
1,003
3.515625
4
import numpy as np print("Enter 6 ploy5 coefficients:") number = 6 #for i in range(6): #n = input("") #x.append(int(n)) while (True): arr = list(map(float, input("").split())) if(len(arr) == 6): break else: print("Wrong input. Please enter 6 ploy5 coefficients: ") print("Enter solution:") a = float(input("")) one = arr[0] two = arr[1] three = arr[2] four = arr[3] five = arr[4] six = arr[5] #j = 5 #for i in x: print("a5 = ", end=" ") print('%.3f' % one) print("a4 = ", end=" ") print('%.3f' % two) print("a3 = ", end=" ") print('%.3f' % three) print("a2 = ", end=" ") print('%.3f' % four) print("a1 = ", end=" ") print('%.3f' % five) print("a0 = ", end=" ") print('%.3f' % six) #j = j - 1 print("xstar =", end=" ") print(round(a, 6)) a = a * (-1) x = np.array([one, two, three, four, five, six]) #print(x) y = np.array([1.0, a]) ans, d = np.polydiv(x, y) tt = 4 for i in ans: print("b", end="") print(tt, " =", end=" ") print(round(i, 3)) #print(ans)
61b3e2c81debcc3076f42b7df02e3b107b53270f
pablo-grande/Aula
/KDC-Simulator/node.py
1,611
3.515625
4
from aes import * class Node(object): """ A node is just an identifier and a hash key""" def __init__(self, node_id): self.__id = node_id self.__key = create_key() # shared with KDC self.__key_dict = {} self.__messages = {} # below some general functions to interact with the object def __str__(self): return 'Id: {0}\nkey: {1}\nkey dictionary: {2}\nmessages: {3}'.format( self.__id, self.__key, self.__key_dict, self.__messages); def getSelfKey(self): return self.__key def getId(self): return self.__id def setKey(self, node_id, key): """ Puts a key in a inner dictionary: id => node_Key """ keys = self.__key_dict keys[node_id] = key def getKey(self, node_id): return self.__key_dict[node_id] #Now some functions to deal with the messages dictionary def putMessage(self, node_id, message): messages = self.__messages messages[node_id] = message def sendMessage(self, message, node): """ Encrypt a message with the session key and put it in the message dictionary of the other node """ key = self.getKey(node.getId()) encrypted = encrypt(key,message) node.putMessage(self.getId(),encrypted) def getMessage(self,node): """Retrieves a message of a given node and decrypts it with the key""" node_id = node.getId() key = self.getKey(node_id) message = self.__messages[node_id] return decrypt(key,message)
355a3568f845a02c8c3af90bf627ea2a207d7b84
ndri/challenges
/old/33.py
1,139
4.125
4
#!/usr/bin/env python # 33 - Area Calculator import sys try: shape, args = sys.argv[1], ' '.join(sys.argv[2:]) except: sys.exit('Error. Use -h for help.') if shape == '-h': print 'Challenge 33 - Area Calculator' print '-h\t\t\tDisplay this help' print '-r width height\t\tArea for a rectangle' print '-c radius\t\tArea for a circle' print '-t base height\t\tArea for a triangle' elif shape == '-r': try: width, height = args.split()[:2] area = float(width) * float(height) print 'The area of this rectangle is {0:.4}'.format(area) except: print 'Usage: -r width height' elif shape == '-c': try: radius = float(args.split()[0]) area = 3.14159265358 * radius**2 print 'The area of this circle is {0:.4}'.format(area) except: print 'Usage: -c radius' elif shape == '-t': try: base, height = args.split()[:2] area = 0.5 * float(base) * float(height) print 'The area of this triangle is {0:.4}'.format(area) except: print 'Usage: -t base height' else: print 'Error. Use -h for help.'
05962d07fdeabc7d4c774d5ce609206b55813df4
ndri/challenges
/17.py
152
3.9375
4
#!/usr/bin/env python # 17 - Count the words in a string string = 'the quick brown fox jumps over the lazy dog' words = len(string.split()) print words
cb032ab3bb68230342d365afbcd3616121c65152
hjj99m/sturpy_gamedev
/pygame_temp02.py
4,973
3.6875
4
# -*- coding: utf-8 -*- """ My First Game """ import pygame ''' 定義物件 define class --------------------------------------------------''' class Missile: def __init__(self, pos): self.pos = [pos[0], pos[1]] def get_pos(self): return self.pos def set_pos(self, pos): self.pos = [pos[0], pos[1]] ''' 定義函數 define function -----------------------------------------------''' def process_missile_group(m_group): remove_mg = set([]) for m in m_group: m_pos = m.get_pos() if m_pos[1] <=0: remove_mg.add(m) if len(remove_mg) > 0: m_group.symmetric_difference_update(remove_mg) def update_missile(m_group): if len(m_group) > 0: for m in m_group: m_pos = m.get_pos() screen.blit(missile_png, (m_pos[0], m_pos[1])) new_pos = [m_pos[0], m_pos[1] - 10] m.set_pos(new_pos) ''' 變數宣告 ---------------------------------------------------------------''' screen_w, screen_h = 400, 640 mouseX, mouseY = 0, 0 missileX, missileY = 0, 0 score = 0 life = 3 missile_grp = set([]) #set ''' 遊戲設定 ---------------------------------------------------------------''' pygame.init() #initial 初始化 clock = pygame.time.Clock() ''' 場景設定 ---------------------------------------------------------------''' screen = pygame.display.set_mode((screen_w, screen_h)) title = pygame.display.set_caption("My First Game") hide_cusor = pygame.mouse.set_visible(1) #隱藏鼠標 clock = pygame.time.Clock() ''' 載入圖片和聲音檔案-------------------------------------------------------''' ship = pygame.image.load('tship.png') ship_icon = pygame.transform.scale(ship, (30, 30)) missile_png = pygame.image.load('missile.png') ''' 文字設定----------------------------------------------------------------''' font = pygame.font.SysFont("consolas", 20) ''' text = font.render("要顯示的文字", 減少鋸齒, (R, G, B)) ''' text1 = font.render("Anti-Corona", True, (80, 80, 150)) text2 = font.render("Defeat COVID-19", True, (150, 200, 150)) text_score = font.render("Socre:", True, (10, 20, 30)) text_score_pt = font.render(str(score), True, (10, 20, 30)) ''' Sprites ---------------------------------------------------------------''' run = True while run: '''---------------------------------------------------------------------''' for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: #buttons = pygame.mouse.get_pressed() if event.button == 1: print('滑鼠左鍵') missile = Missile([mouseX-10, mouseY-60]) missile_grp.add(missile) score = score + 10 text_score_pt = font.render(str(score), True, (10, 20, 30)) print(score) if event.button == 2: print('滑鼠中鍵') if event.button == 3: print('滑鼠右鍵') if event.button == 4: print('滾輪向上') if event.button == 5: print('滾輪向下') if event.type == pygame.MOUSEMOTION: mouseX, mouseY = pygame.mouse.get_pos() if event.type == pygame.KEYDOWN: keys = pygame.key.get_pressed() if keys[pygame.K_z]: pass if keys[pygame.K_x]: pass if keys[pygame.K_c]: pass if keys[pygame.K_v]: pass #print(event) ''' 程式運算、計算-------------------------------------------------------''' #mouseX, mouseY = pygame.mouse.get_pos() #取得鼠標x,y座標值 '''buttons = pygame.mouse.get_pressed() if buttons[0] == 1: print('滑鼠左鍵') if buttons[1] == 1: print('滑鼠中鍵') if buttons[2] == 1: print('滑鼠右鍵') ''' '''把所有文字、圖片依序畫在場景內-----------------------------------------''' screen.fill((255,255,255)) #背景顏色 screen.blit(text1, (120, 80)) screen.blit(text2, (120, 120)) screen.blit(text_score, (10, 10)) screen.blit(text_score_pt, (180, 10)) for i in range(0, life): screen.blit(ship_icon, (5 + i*33, screen_h - 33)) process_missile_group(missile_grp) update_missile(missile_grp) #screen.blit(missile, (missileX, missileY)) screen.blit(ship, (mouseX - 45, mouseY - 45)) clock.tick(60) '''---------------------------------------------------------------------''' pygame.display.flip() #刷新畫面 '''--while loop end---------------------------------------------------------''' pygame.quit() #quit 結束pygame
6bfef5338d6574be09828fe4e6a250b5c831ab9e
fgrelard/ProcessMRI
/src/compleximage.py
2,730
3.734375
4
import numpy as np import math import cmath def separate_real_imaginary(img_data): """ Separates the real and imaginary parts in a complex image. Real and imaginary parts are assumed to be mixed in the last dimension of size n With real contained in the first n//2 slices and imaginary in the last n//2 slices Parameters ---------- img_data: numpy.ndarray n-D complex image Returns ---------- real: numpy.ndarray real image imaginary: numpy.ndarray imaginary image """ real = np.zeros(shape=(img_data.shape[:-1]+ (img_data.shape[-1]//2,))) imaginary = np.zeros(shape=(img_data.shape[:-1]+ (img_data.shape[-1]//2,))) dim = len(img_data.shape) ri = img_data.shape[dim-1] for i, x in np.ndenumerate(img_data): image = img_data[i] if i[-1] < ri//2: real[i] = image else: index = i[:-1] + (i[-1] % (ri//2),) imaginary[index] = image return real, imaginary def to_complex(img_data): """ Converts a complex image where real and imaginary are separated into a single complex image, with pixel value = re+i*im Parameters ---------- img_data: numpy.ndarray n-D complex image with real and imaginar parts separated Returns ---------- numpy.ndarray n-D complex image with complex values """ complex_img = np.zeros(shape=(img_data.shape[:-1]+ (img_data.shape[-1]//2, )), dtype=complex) real, imaginary = separate_real_imaginary(img_data) for i, x in np.ndenumerate(complex_img): complex_img[i] = complex(real[i], imaginary[i]) return complex_img def complex_to_phase(img_data): """ Converts a complex image with complex values to the phase image (atan2(im,re)) Parameters ---------- img_data: numpy.ndarray n-D complex image with complex values Returns ---------- numpy.ndarray n-D phase image with float values """ out_img_data = np.zeros_like(img_data, dtype=float) for item, x in np.ndenumerate(img_data): out_img_data[item] = cmath.phase(img_data[item]) return out_img_data def complex_to_magnitude(img_data): """ Converts a complex image with complex values to the magnitude image (sqrt(re^2+im^2)) Parameters ---------- img_data: numpy.ndarray n-D complex image with complex values Returns ---------- numpy.ndarray n-D magnitude image with float values """ out_img_data = np.zeros_like(img_data, dtype=float) for item, x in np.ndenumerate(img_data): out_img_data[item] = abs(img_data[item]) return out_img_data
81be275d54c77ac60482e8fd78febe61182691f7
patrickfriedman/Sudoku-Solver
/Sudoku.py
3,023
3.71875
4
from random import randrange def diff(difficulty): #players difficulty if (difficulty == 0): shown = 55 elif (difficulty == 1): shown = 45 elif (difficulty == 2): shown = 35 return shown def newBoard(): #creates an empty board board = [[0 for x in range(9)] for y in range(9)] return board def newGame(nb, sb, diff): #creates solvable board per difficulty for user for x in range(diff): x = randrange(9) y = randrange(9) nb[x][y] = sb[x][y] return nb def printBoard(b): #print boards in nice format print() for i in range(len(b)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - ") for j in range(len(b[0])): if j % 3 == 0 and j != 0: print(" | ", end = "") if j == 8: print(b[i][j]) else: print(str(b[i][j]) + " ", end = "") def find_unsolved(b): #look for unsolved position for i in range(len(b)): for j in range(len(b[0])): if b[i][j] == 0: return (i, j) return None def correct(b, num, pos): #check each constraint #row for i in range(len(b[0])): if b[pos[0]][i] == num and pos[1] != i: return False #column for i in range(len(b)): if b[i][pos[1]] == num and pos[0] != i: return False #grid grid_x = pos[1] // 3 grid_y = pos[0] // 3 for i in range(grid_y * 3, grid_y * 3 + 3): for j in range(grid_x * 3, grid_x * 3 + 3): if b[i][j] == num and (i, j) != pos: return False return True def solve(b): #solve recursively find = find_unsolved(b) if not find: return True else: row, col = find for x in range(1, 10): x = randrange(10) #creates random starting number for uniqueness if correct(b, x, (row, col)): b[row][col] = x if solve(b): return True b[row][col] = 0 return False def textGame(): sb = newBoard() #create an empty board solve(sb) #solves new board printBoard(newGame(newBoard(), sb, diff(0))) #creates a game board that can be solved per difficulty print() input("Press Enter for the Solution: ") printBoard(sb) #prints solved board #textGame() #use to run game in text editor
c3d8124982c4d803f1b54d193966f3f906e59bdf
SDMR-LAB/interpeter
/lang105.py
407
3.640625
4
def block(code): opened = [] blocks = {} for i in range(len(code)): if code[i] == '[': opened.append(i) elif code[i] == ']': blocks[i] = opened[-1] blocks[opened.pop()] = i return blocks def parse(code): new = "" for c in code: if c in "shift_left shift_right plus minus point zapa[]": new += c return new
5d67e0b356bf312478a940ad7d9bf965b7b751ac
bijon1161/Python-Course-from-coursera.org
/ProblemSet4.py
5,039
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 1 20:04:57 2021 @author: Admin """ # - ProblemSet4.py *- coding: utf-8 -*- """ Problem 4_1: Write a function that will sort an alphabetic list (or list of words) into alphabetical order. Make it sort independently of whether the letters are capital or lowercase. First print out the wordlist, then sort and print out the sorted list. Here is my run on the list firstline below (note that the wrapping was added when I pasted it into the file -- this is really two lines in the output). problem4_1(firstline) ['Happy', 'families', 'are', 'all', 'alike;', 'every', 'unhappy', 'family', 'is', 'unhappy', 'in', 'its', 'own', 'way.', 'Leo Tolstoy', 'Anna Karenina'] ['alike;', 'all', 'Anna Karenina', 'are', 'every', 'families', 'family', 'Happy', 'in', 'is', 'its', 'Leo Tolstoy', 'own', 'unhappy', 'unhappy', 'way.'] """ #%% firstline = ["Happy", "families", "are", "all", "alike;", "every", \ "unhappy", "family", "is", "unhappy", "in", "its", "own", \ "way.", "Leo Tolstoy", "Anna Karenina"] #%% def problem4_1(wordlist): """ Takes a word list prints it, sorts it, and prints the sorted list """ print(wordlist) wordlist.sort(key=str.lower) print(wordlist) # replace this pass (a do-nothing) statement with your code #%% """ Problem 4_2: Write a function that will compute and print the mean and standard deviation of a list of real numbers (like the following). Of course, the length of the list could be different. Don't forget to import any libraries that you might need. Here is my run on the list of 25 floats create below: problem4_2(numList) 51.528 30.81215290541488 """ #%% import random numList = [] random.seed(150) for i in range(0,25): numList.append(round(100*random.random(),1)) #%% def problem4_2(ran_list): import statistics """ Compute the mean and standard deviation of a list of floats """ print(statistics.mean(ran_list)) print(statistics.stdev(ran_list)) # replace this pass (a do-nothing) statement with your code #%% """ Problem 4_3: Write a function problem4_3(product, cost) so that you can enter the product and its cost and it will print out nicely. Specifically, allow 25 characters for the product name and left-justify it in that space; allow 6 characters for the cost and right justify it in that space with 2 decimal places. Precede the cost with a dollar-sign. There should be no other spaces in the output. Here is how one of my runs looks: problem4_3("toothbrush",2.6) toothbrush $ 2.60 """ #%% def problem4_3(product, cost): """ Prints the product name in a space of 25 characters, left-justified and the price in a space of 6 characters, right-justified""" print("{0:<25}${1:>6.2f}".format(product, cost)) # replace this pass (a do-nothing) statement with your code #%% """ Problem 4_4: This problem is to build on phones.py. You add a new menu item r) Reorder This will reorder the names/numbers in the phone list alphabetically by name. This may sound difficult at first thought, but it really is straight forward. You need to add two lines to the main_loop and one line to menu_choice to print out the new menu option (and add 'r' to the list of acceptable choices). In addition you need to add a new function to do the reordering: I called mine reorder_phones(). Here is a start for this very short function: def reorder_phones(): global phones # this insures that we use the one at the top pass # replace this pass (a do-nothing) statement with your code Note: The auto-grader will run your program, choose menu items s, r, s, and q in that order. It will provide an unsorted CSV file and see if your program reorders it appropriately. The grader will provide a version of myphones.csv that has a different set of names in it from the ones we used in the lesson. This difference in data will, of course, not matter with a well coded program. Below the result of this added function is shown using the names used in class. Note that name is a single field. Reorder by that field, don't try to separate first and last name and reorder by one or the other --- just treat name as a single field that you re-order by. Also, in this case upper/lower case won't matter. TIP: phones[] is a list of lists (each sublist is a [name, phone]. It looks complicated to sort. Just pretend that each sublist is a single name item and code it accordingly. It will work. This is a beginner course and this sort function requires only one line and no fancy outside material to make it work.) The main thrust of this problem is to add in the various pieces to make a new menu entry. Before: Choice: s Name Phone Number 1 Jerry Seinfeld (212) 842-2527 2 George Costanza (212) 452-8145 3 Elaine Benes (212) 452-8723 After: Choice: s Name Phone Number 1 Elaine Benes (212) 452-8723 2 George Costanza (212) 452-8145 3 Jerry Seinfeld (212) 842-2527 """
e416d465ae64dad5353d431d099ff1fab5e801cf
CodingPirates/taarnby-python
/uge1/5_lister.py
2,203
4.125
4
#coding=utf8 # Når vores programmer bliver lidt mere komplicerede får vi rigtig mange variable # Det gør at de bliver mere og mere besværlige at læse # Nogle gange så hænger flere af de variable sammen # Så kan vi prøve at lave dem om til en enkelt variabel som gemmer på mere end én ting ad gangen # Den mest simple hedder en liste minshoppingliste = ["1 kg mel","2 liter mælk","3 skumfiduser"] print("Min shoppingliste lyder: "+str(minshoppingliste)) # Det ser ikke særlig pænt ud, men det er også ok # Når vi bruger lister, så plukker vi enkelte ting ud ad gangen # Det gør vi med at bruge firkantede parenteser # minshoppingliste[<nummer>] giver os et element fra listen print("Det første på listen er "+minshoppingliste[0]) print("Det tredie på listen er "+minshoppingliste[2]) print("Det andet på listen er "+minshoppingliste[1]) # Hov! Der står 2 hvor vi skal tage det tredie element # Jep, den er god nok. Computere tæller altid fra 0, så det kan vi lige så godt vænne os til # Vi kan også bruge variable når vi vælger fra listerne: nummer = 0 print("Element nummer "+str(nummer) + " på listen er: " + minshoppingliste[nummer]) print("") # Prøv at lave om på "nummer" og se hvad der sker # Vi kan også lave andre slags lister. For eksempel "dict", som er en slags ordbog # En dict er god til at gemme ting hvor rækkefølgen er ligegyldig # I stedet for en firkantet parentes bruger vi en krøllet (Tuborg) parentes # Hvert element i listen gemmes som en nøgle og en værdi med kolon imellem mitfodboldhold = {"målmand" : "P. Schmeichel", "højre back" : "P. Ninkov", "angriber" : "C. Ronaldo"} print("Holdets målmand er: "+mitfodboldhold["målmand"]) print("Holdets højre back er: "+mitfodboldhold["højre back"]) print("Holdets angriber er: "+mitfodboldhold["angriber"]) print("") # Vi kan godt lave om på dele af holdet uden at starte forfra mitfodboldhold["målmand"] = "J. Hart" print("Holdets nye målmand er: "+mitfodboldhold["målmand"]) print("Holdets højre back er: "+mitfodboldhold["højre back"]) print("Holdets angriber er: "+mitfodboldhold["angriber"]) print("") # Øvelse: Lav en liste over jeres yndlingsbøger og print ud til skærmen
691b544bfdd55701f8aa45bc3fb350f21c2a5a4d
SLrepository/dev
/partie1.py
1,188
3.78125
4
# -*- coding: utf-8 -*- ## 1\.Exercice 1 : Hello World print("\nExercise Nr. #1") print("---------------") print("Hello World") Macron = "hello world" print(Macron) ## 2\.Exercice 2 : Calculs divers print("\nExercise Nr. #2") print("---------------") print(3*3) try: 12/0 except ZeroDivisionError: print("Null division not allowed") print(4+9+78) print(12-7) print(5e4) ## 3\.Exercice 3 : Communiquer avec l'ordinateur print("\nExercise Nr. #3") print("---------------") name = input("Who should I introduce ? ") print("Hi",name,", welcome on board!".format(name)) ## 4\.Exercice 4 : Nom et prénom print("\nExercise Nr. #4") print("---------------") name = "Vladimir" familyname = "Illitch" print("Bonjour {} {}".format(name,familyname)) ## 5\.Exercice 5 : Des caractères au nombre print("\nExercise Nr. #5") print("---------------") myNumber = "123" print(myNumber) print(type(myNumber)) myNumber = int(myNumber) print(myNumber) print(type(myNumber)) ## 6\.Exercice 6 : Majuscules et miniscules print("\nExercise Nr. #6") print("---------------") myMAJString = "ALEA JACTA EST" print(myMAJString.lower()) myminString = "alea jacta est" print(myminString.upper())
0c96d7d80611737119321313920bd3d8005b4e70
royabouhamad/Algorithms
/Sorting/QuickSort.py
667
3.859375
4
def partition(list, left, right, pivot): while left <= right: while list[left] < pivot: left += 1 while list[right] > pivot: right -= 1 if left <= right: list[left], list[right] = list[right], list[left] left += 1 right -= 1 return left def quicksort(list, left, right): if left < right: pivot = list[(left+right)/2] index = partition(list, left, right, pivot) quicksort(list, left, index - 1) quicksort(list, index, right) return list numbers = [11, 2, 32, 9, 29, 0, 15, 40, 8, 1, 37] print(quicksort(numbers, 0, len(numbers) - 1))
dd390f155046dceec4cbbcd0a5f9c8368a88851f
PraneshASP/COMPETITVE-PROGRAMMING
/LEETCODE/HARD/124. Binary Tree Maximum Path Sum.py
643
3.671875
4
# Definition for a binary tree node. import sys class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: ans = -sys.maxsize - 1 def helper(self, root: TreeNode) -> int: if not root: return 0 l = max(0, self.helper(root.left)) r = max(0, self.helper(root.right)) self.ans = max(self.ans, root.val + l + r) return max(l, r)+root.val def maxPathSum(self, root: TreeNode) -> int: self.helper(root) return self.ans if __name__ == "__main__": vals = [1,2,3]
2b1bb143910ac13d63bf9fe1be87ca57f89cf98f
richardpon/mypractice
/leetcode/14_longest_common_prefix/longest_common_prefix.py
421
3.59375
4
class Solution: def longestCommonPrefix(self, strs): longest_prefix = "" if len(strs) == 0: return longest_prefix for i in range(0, len(strs[0])): cur_char = strs[0][i] for s in strs[1:]: if i >= len(s) or cur_char != s[i]: return longest_prefix longest_prefix += cur_char return longest_prefix
4ffc7902e78df665462fa618b65750e6b445c880
richardpon/mypractice
/leetcode/122_best_time_to_buy_and_sell_stock_ii/best_time_to_buy_and_sell_stock_ii.py
1,632
3.859375
4
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) < 2: return 0 #maybe buy on day n #if next day cheaper, then reset and maybe buy that day #if next day is higher, maybe sell #if next day lower, sell day before #if next day higher (or last day), maybe sell, but don't total_profit = 0 #maybe buy or sell buy_price = prices[0] sell_price = None for price in prices[1:]: if sell_price is None: # do I have a potential sell price, or better buy? if price > buy_price: # have potential sale (price went up) sell_price = price else: # buy this day instead buy_price = price else: # have a potential sale price if price >= sell_price: # price went up, sell this day instead sell_price = price else: #price went down, should sell yesterday(buy today) cur_profit = sell_price - buy_price total_profit += cur_profit #buy today (sold yesterday, buy today) buy_price = price sell_price = None #should sell when done? if sell_price and sell_price > buy_price: cur_profit = sell_price - buy_price total_profit += cur_profit return total_profit
f99a6f7cba5470fee26eedbd0e6db4338bf40499
richardpon/mypractice
/codewars/5kyu/draw_the_borders_1_simple_ascii_border/draw_borders.py
4,437
3.828125
4
from typing import Tuple, Set class Solution: def draw_borders(self, shape): #convert each shape[] into squares and borders # output = borders is set of tuples representing border borders = self.get_borders(shape) #donut detection borders = self.remove_donut(borders) #draw return self.draw(borders) def get_borders(self, shape) -> Set[Tuple[int,int]]: # maintain set of borders borders = set() for block in shape: # add all borders if not already in the shape # for each of possible 8 border squares surrounding block: possible_borders = self.get_surrounding_coordinates(block) for cur_coordinate in possible_borders: if cur_coordinate not in shape: borders.add(cur_coordinate) return borders def get_surrounding_coordinates(self,coordinate_tuple) -> Set[Tuple[int,int]]: x = coordinate_tuple[0] y = coordinate_tuple[1] return {(x-1,y+1), (x,y+1), (x+1,y+1), \ (x-1,y),(x+1,y), \ (x-1,y-1), (x,y-1), (x+1,y-1) } def up_down_neighbors(self,coordinate_tuple) -> Set[Tuple[int,int]]: x = coordinate_tuple[0] y = coordinate_tuple[1] return {(x-1,y),(x+1,y), (x,y+1), (x,y-1)} def remove_donut(self,borders) -> Set[Tuple[int,int]]: # identify a known border on the outside # single pass, what is block with lowest x? This is starting point #from starting point, mark adjacent blocks as outside #identify a block with the lowest x min_x = 100 starting_block = None for block in borders: if block[0] < min_x: min_x = block[0] starting_block = block #from min block, mark adjacent blocks as outside outside = {starting_block} # known outside borders borders_to_check = borders borders_to_check.remove(starting_block) #already checked starting block #iteratively mark adjacent blocks of known outside blocks as outside squares_to_check = self.up_down_neighbors(starting_block) while(squares_to_check): cur_square = squares_to_check.pop() if cur_square in borders: #found another outside border outside.add(cur_square) borders_to_check.remove(cur_square) squares_to_check |= self.up_down_neighbors(cur_square) return outside def draw(self,shape) -> str: # find the min/max x/y #start printing characters with a raster scan from top left output = "" (min_x, max_x, min_y, max_y) = self.get_min_max(shape) # print characters for y in range(max_y, min_y - 1, -1): line = "" max_x_for_row = self.get_max_x_for_row(y, shape) for x in range(min_x, min(max_x + 1, max_x_for_row + 1)): line += self.get_char(x, y, shape) output += line + "\n" return output[0:-1] def get_char(self, x, y, shape) -> str: # borders with only top/down neighbors are vertical # borders with only L/R neighbors are horizontal # otherwise, + if (x,y) not in shape: return " " if (x,y-1) in shape and (x,y+1) in shape and \ (x-1,y) not in shape and (x+1,y) not in shape: return("|") elif (x-1,y) in shape and (x+1,y) in shape and \ (x,y+1) not in shape and (x, y-1) not in shape: return("-") else: return("+") def get_min_max(self, shape) -> (int, int, int, int): min_x = 100 max_x = -100 min_y = 100 max_y = -100 for square in shape: x = square[0] y = square[1] min_x = min(min_x, x) max_x = max(max_x, x) min_y = min(min_y, y) max_y = max(max_y, y) return (min_x, max_x, min_y, max_y) def get_max_x_for_row(self, y, shapes) -> int: x = -100 for (cur_x, cur_y) in shapes: if cur_y == y: x = max(x, cur_x) return x s = Solution() print(s.draw_borders({(1,1)}))
95a5bdc7784e1729fbb136e74aefd62c9da9a6e7
microsoft/AdversarialGMM
/mliv/linear/utilities.py
1,196
3.59375
4
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np from functools import reduce def cross_product(*XS): """ Compute the cross product of features. Parameters ---------- X1 : n x d1 matrix First matrix of n samples of d1 features (or an n-element vector, which will be treated as an n x 1 matrix) X2 : n x d2 matrix Second matrix of n samples of d2 features (or an n-element vector, which will be treated as an n x 1 matrix) Returns ------- A : n x (d1*d2*...) matrix Matrix of n samples of d1*d2*... cross product features, arranged in form such that each row t of X12 contains: [X1[t,0]*X2[t,0]*..., ..., X1[t,d1-1]*X2[t,0]*..., X1[t,0]*X2[t,1]*..., ..., X1[t,d1-1]*X2[t,1]*..., ...] """ for X in XS: assert 2 >= np.ndim(X) >= 1 n = np.shape(XS[0])[0] for X in XS: assert n == np.shape(X)[0] def cross(XS): k = len(XS) XS = [np.reshape(XS[i], (n,) + (1,) * (k - i - 1) + (-1,) + (1,) * i) for i in range(k)] return np.reshape(reduce(np.multiply, XS), (n, -1)) return cross(XS)
112e10fe234d7685da85c2b1ce37bd1f8f2d08e0
PramodhMahadeshKM/OOPPythonMiniProject
/3_Implementation/telephone.py
11,013
3.921875
4
"""This is the source file for the telephone project.""" import re class Customer: def __init__(self,idn=None,name=None,email=None,number=None): """Parent class constructor.""" self.idn=idn self.name=name self.email=email self.number=number def update_email(self,new_email): """Function to update mail id.""" self.email=new_email print('Updated successfully!\n') def display(self): """Function to display info.""" print(f'ID = {self.idn}\nName = {self.name}') print(f'Email = {self.email}\nPhone no. = {self.number}') class PrepaidCustomer(Customer): def __init__(self,idn=None,name=None,email=None,number=None,balance=None): """Prepaid class constructor.""" super().__init__(idn,name,email,number) self.balance=balance def read_data(self): """Function to get data of the user from backend(.txt file here).""" file = open('Prepaid.txt', 'r') total_list = [] for line in file: k = line.rstrip() total_list.append(k) file.close() return total_list def get_data(self,total_list): """Function to check the list.""" size = len(total_list) if size != 5: print('Incorrect no. of data in prepaid.txt\n') return -1 for i in range(0, size): if total_list[i] == '': print('Data missing') break else: try: self.idn = int(total_list[0]) except Exception as err: print(f'Error occured - {err}') print('Incorrect idn') return -1 try: self.name = total_list[1] assert self.name.isalpha() except Exception: print('Error occured : ') print('Incorrect name') return -1 try: self.email = total_list[2] assert re.search(r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$', self.email) except Exception: print('Error occured : ') print('Incorrect email') return -1 try: self.number = total_list[3] assert re.search(r'([789]\d{9}?)', self.number) assert len(self.number) == 10 except Exception: print('Error occured : ') print('Incorrect phone no.') return -1 try: self.balance = float(total_list[4]) assert self.balance > -10 except Exception as err: print(f'Error occured - {err}') print('Incorrect balance') return -1 return 0 def make_call(self,duration): """Function to make call.""" cost = duration * 0.5 if self.balance<-10: print('Add balance to make a call\n') return -1 if (self.balance-cost)<-10: print('Insufficient balance to make call\n') return -1 else: self.balance-=cost return self.balance def add_balance(self,money): """Function to add balance.""" if money<0: print('Please add money\n') return -1 if self.balance<0: return -1 else: self.balance += money print('Added successfully!\n') return self.balance def display_balance(self): """Function to display balance.""" print(f'The balance is {self.balance} Rs.\n') def prepaid_features(self): """Function to display and implement features.""" loop='Y' while loop in ('y','Y'): print(f'\nWelcome {self.name}\n') print('The features available are :') print('1. MAKE A CALL') print('2. ADD BALANCE') print('3. UPDATE EMAIL') print('4. CHECK BALANCE') print('5. DISPLAY INFO') key = input('Enter the no. of the the feature to use: ') if key == '1': try: mins = float(input('Enter no. of mins of call: ')) assert mins > 0 PrepaidCustomer.make_call(self,mins) except Exception as err: print(f'Error - {err}') print('Please enter value appropriately') elif key == '2': try: mon = float(input('Enter the amount you would like to add: ')) assert mon > 0 PrepaidCustomer.add_balance(self,mon) except Exception as err: print(f'Error - {err}') print('Please enter value appropriately') elif key == '3': try: mail=input('Enter the new email id: ') assert re.search(r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$', mail) PrepaidCustomer.update_email(self,mail) except Exception: print('Please enter valid email id\n') elif key == '4': PrepaidCustomer.display_balance(self) elif key == '5': PrepaidCustomer.display(self) else: print('Please enter the correct choice\n') loop=input('Would you like to go back to features page?(y/n): ') def display(self): """Function to display info.""" super().display() print(f'Balance = {self.balance} Rs.\n') class PostpaidCustomer(Customer): def __init__(self,idn=None,name=None,email=None,number=None,time=None): """Postpaid class constructor.""" super().__init__(idn, name, email, number) self.time=time def read_data(self): """Function to get data of the user from backend(.txt file here).""" file = open('Postpaid.txt', 'r') total_list = [] for line in file: k = line.rstrip() total_list.append(k) file.close() return total_list def get_data(self,total_list): """Function to pass data.""" size = len(total_list) if size != 5: print('Incorrect no. of data in prepaid.txt\n') return -1 for i in range(0, size): if total_list[i] == '': print('Data missing') break else: try: self.idn = int(total_list[0]) except Exception as err: print(f'Error occured - {err}') print('Incorrect idn') return -1 try: self.name = total_list[1] assert self.name.isalpha() except Exception: print('Error occured : ') print('Incorrect name') return -1 try: self.email = total_list[2] assert re.search(r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$', self.email) except Exception: print('Error occured : ') print('Incorrect email') return -1 try: self.number = total_list[3] assert re.search(r'([789]\d{9}?)', self.number) assert len(self.number) == 10 except Exception: print('Error occured : ') print('Incorrect phone no.') return -1 try: self.time = float(total_list[4]) assert self.time >=0 self.bill = self.time*0.4 except Exception as err: print(f'Error occured - {err}') print('Incorrect time') return -1 return 0 def make_call(self,duration): """Function to make call.""" if duration<0: print('Enter correct value') return -1 if self.time<0: return -1 else: self.bill = self.time * 0.4 self.time+=duration self.bill+=(duration*0.4) return self.bill def pay_bill(self,money): """Function to pay bill.""" self.bill=self.time*0.4 if money<=self.bill and money>0: self.bill-= money self.time-= (money/0.4) print('Paid successfully\n') return self.bill if self.bill<-10: return -1 else: print('Pay the bill as shown\n') return -1 def display_bill(self): """Function to diplay bill.""" print(f'The remaining bill is {self.bill} Rs.') def postpaid_features(self): """Function to display and implement features.""" loop='Y' while loop in ('y','Y'): print(f'\nWelcome {self.name}\n') print('The features available are :') print('1. MAKE A CALL') print('2. PAY BILL') print('3. UPDATE EMAIL') print('4. CHECK BILL') print('5. DISPLAY INFO') key = input('Enter the no. of the the feature to use: ') if key == '1': try: mins = float(input('Enter no. of mins of call: ')) assert mins > 0 PostpaidCustomer.make_call(self,mins) except Exception as err: print(f'Error - {err}') print('Please enter value appropriately') elif key == '2': try: PostpaidCustomer.display_bill(self) mon = float(input('Enter the amount you would like to pay: ')) assert mon > 0 PostpaidCustomer.pay_bill(self,mon) except Exception as err: print(f'Error - {err}') print('Please enter value appropriately') elif key == '3': try: mail=input('Enter the new email id: ') assert re.search(r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$', mail) PostpaidCustomer.update_email(self,mail) except Exception: print('Please enter valid email id\n') elif key == '4': PostpaidCustomer.display_bill(self) elif key == '5': PostpaidCustomer.display(self) else: print('Please enter the correct choice\n') loop=input('Would you like to go back to features page?(y/n): ') def display(self): """Function to display info.""" super().display() print(f'Time conversed = {self.time} mins\nRemaining Bill = {self.bill} Rs.')
e27d12cf122b6bbb62491f06d9e0ac37dc001b41
LaloGarcia91/CrackingTheCodingInterview
/Chapter_4/ListOfDepths.py
2,584
3.6875
4
from Chapter_4.Trees.BinaryNode import * from Chapter_2.LinkedList import * import math class ListOfDepths: def __init__(self): self.allListsOfDepths = [] self.binaryTreeRoot = None def add(self, root, node): if node.value > root.value: if root.rightNode is None: root.rightNode = node else: self.add(root.rightNode, node) else: if root.leftNode is None: root.leftNode = node else: self.add(root.leftNode, node) def BuildListOfDepths(self): root = self.binaryTreeRoot if root is None: return current = LinkedList() current.append(root) while current.getListSize() > 0: self.allListsOfDepths.append(current) # add the previous level parents = current # go to next level current = LinkedList() currentParent = parents.head # head of the linked list (holds a binary node) while currentParent is not None: node = currentParent.data if node.leftNode is not None: current.append(node.leftNode) if node.rightNode is not None: current.append(node.rightNode) currentParent = currentParent.nextNode def PrintListOfDepths(self): self.BuildListOfDepths() currentNode = None depth = 1 for parent in self.allListsOfDepths: print("----------> Depth #", depth) currentNode = parent.head while currentNode is not None: print(currentNode.data.value) currentNode = currentNode.nextNode depth += 1 listOfDepths = ListOfDepths() listOfDepths.binaryTreeRoot = BinaryNode(50) root = listOfDepths.binaryTreeRoot listOfDepths.add(root, BinaryNode(48)) listOfDepths.add(root, BinaryNode(67)) listOfDepths.add(root, BinaryNode(70)) listOfDepths.add(root, BinaryNode(30)) listOfDepths.add(root, BinaryNode(65)) listOfDepths.add(root, BinaryNode(90)) listOfDepths.add(root, BinaryNode(20)) listOfDepths.add(root, BinaryNode(32)) listOfDepths.add(root, BinaryNode(98)) listOfDepths.add(root, BinaryNode(15)) listOfDepths.add(root, BinaryNode(25)) listOfDepths.add(root, BinaryNode(31)) listOfDepths.add(root, BinaryNode(35)) listOfDepths.add(root, BinaryNode(66)) listOfDepths.add(root, BinaryNode(69)) listOfDepths.add(root, BinaryNode(94)) listOfDepths.add(root, BinaryNode(99)) listOfDepths.PrintListOfDepths()
d1566aa76b394885eeb94a8bb1f730a958b5b834
LaloGarcia91/CrackingTheCodingInterview
/Chapter_2/LoopDetection.py
1,196
3.953125
4
from Chapter_2.LinkedList import * class LinkedListLoopDetect: def FindBeginning(self, linkedList): slow = linkedList.head fast = linkedList.head # find meeting point. This will be LOOP_SIZE - k steps into the linked list while fast is not None and fast.nextNode is not None: slow = slow.nextNode fast = fast.nextNode.nextNode if slow == fast: # collision break # Error checking - no meeting point, and therefore no loop if fast is None or fast.nextNode is None: return None ''' Move slow to head. Keep fast at Meeting point. Each are k steps from the Loop Start. If they move at the same pace, they must meet at Loop Start. ''' slow = linkedList.head while slow != fast: slow = slow.nextNode fast = fast.nextNode # Both now point to the start of the loop return fast llist = LinkedList() llist.append("A") llist.append("B") llist.append("C") llist.append("D") llist.append("E") llist.append("C") llist.printList() result = LinkedListLoopDetect().FindBeginning(llist) print(result)
2c69dfb001152a2017815ada26426d69925404e8
LaloGarcia91/CrackingTheCodingInterview
/Chapter_1/OneAway.py
1,301
3.734375
4
class OneAway: def __init__(self, str1, str2): self.CheckIfWordsAre1CharAway(str1, str2) def CheckIfWordsAre1CharAway(self, str1, str2): check_1 = self.LoopThe2Words(str1, str2) check_2 = self.LoopThe2Words(str2, str1) if check_1 or check_2: print("One Away was found!") return True if not check_1 and not check_2: print("None 'One Away' found.") return False def LoopThe2Words(self, str1, str2): if str1 == str2: return False if (len(str1) == (len(str2) + 1)) or len(str1) == len(str2): counterForLettersNotShared = 0 # if this counter remains in 1... means that strings are "One Away". lettersSharedSoFar = "" # if this string is always 1 char away from the longest string passed, strings are "One Away" i = 0 while i < len(str1): if i < len(str2) and str1[i] == str2[i]: lettersSharedSoFar += str1[i] else: counterForLettersNotShared += 1 if len(lettersSharedSoFar) == len(str2) or len(lettersSharedSoFar)+1 == len(str2): return True i += 1 return False OneAway("hello", "hell")
42096d931802f6a0edcfa5702f2a91d0bbba2cd5
LaloGarcia91/CrackingTheCodingInterview
/Chapter_1/CheckPermutation.py
775
4.125
4
class CheckPermutation: def __init__(self, str1, str2): self.checkIfIsPermutation(str1, str2) def checkIfIsPermutation(self, str1, str2): str1_len = len(str1) str2_len = len(str2) if str1_len == str2_len: counterIfEqualLetters = 0 for str1_letter in str1: if str1_letter in str2: counterIfEqualLetters += 1 else: print("It is NOT a permutation") return False if counterIfEqualLetters == str1_len: print("It IS a permutation") return True else: print("Words are not even the same length") # run exercise CheckPermutation("HELLO", "HLLEO")
2d4789ea57bf69e568774d4359be67ce3ebe8c13
LaloGarcia91/CrackingTheCodingInterview
/Chapter_2/LinkedList.py
8,468
4.03125
4
import math class Node: data = None nextNode = None def __init__(self, data): self.data = data class LinkedList: head = None def append(self, data): if self.head is None: self.head = Node(data) return currentNode = self.head while currentNode.nextNode is not None: currentNode = currentNode.nextNode currentNode.nextNode = Node(data) def prepend(self, data): newHead = Node(data) # in order to prepend a node, we need to create a new head newHead.nextNode = self.head # the old head is the NEXT node of the new head, meaning it will be index 1 of the list self.head = newHead # set the new head of the linked list def deleteNode(self, deleteBy, thisValue): # a node can be deleted either by the node-value or by the index of the node in the linked list if self.head is None: return currentNode = self.head if deleteBy == "index": self.deleteNodeByIndex(currentNode, thisValue) if deleteBy == "value": self.deleteNodeByValue(currentNode, thisValue) if currentNode is None: print("The node " + deleteBy + ": " + str(thisValue) + " does NOT exist.") return self.printDeletedNodeMsg(deleteBy, thisValue) def deleteNodeByIndex(self, currentNode, thisIndex): if thisIndex == 0: self.head = self.head.nextNode return index = 0 previousNode = None while index < thisIndex: previousNode = currentNode currentNode = currentNode.nextNode index += 1 previousNode.nextNode = currentNode.nextNode def deleteNodeByValue(self, currentNode, thisValue): previousNode = None while (currentNode.nextNode is not None) and currentNode.data != thisValue: previousNode = currentNode currentNode = currentNode.nextNode previousNode.nextNode = currentNode.nextNode def printDeletedNodeMsg(self, msgType, thisData): if msgType == "index": print("..........deleted the node at index: " + str(thisData)) return if msgType == "value": print("..........deleted the node with value of: " + str(thisData)) return return False def getListSize(self): if self.head is None: return 0 # list size is 0 currentNode = self.head # the actual CURRENT node at this point of the program size = 1 # starts at 1, because we are counting the currentNode while currentNode.nextNode is not None: # while the "currentNode" node in iteration is not the last node in the singled list currentNode = currentNode.nextNode size += 1 return size def printListSize(self): print("..........current linked list size is: ", self.getListSize()) def printList(self): print("..........CURRENT LIST BELOW") if self.head is None: print("There is nothing in the list.") return currentNode = self.head # the current node (the first on the list) print("Node Index 0 => " + str(currentNode.data)) index = 1 # start counting at index 1 while currentNode.nextNode != None: currentNode = currentNode.nextNode print("Node Index " + str(index) + " => " + str(currentNode.data)) index += 1 def replaceListNodesWithAnotherListNodes(self, thisList): currentNode_originalList = self.head currentNode_tempList = thisList.head while currentNode_originalList is not None: currentNode_originalList.data = currentNode_tempList.data currentNode_originalList = currentNode_originalList.nextNode currentNode_tempList = currentNode_tempList.nextNode def howManyTimesThisNodeRepeats(self, nodeValue): if self.head is None: return currentNode = self.head times = 0 while currentNode is not None: if currentNode.data == nodeValue: times += 1 currentNode = currentNode.nextNode return times def cloneOriginalListAsBackwards(self): originalListBackwards = LinkedList() currentNode = self.head originalListBackwards.prepend(currentNode) while currentNode.nextNode is not None: currentNode = currentNode.nextNode originalListBackwards.prepend(currentNode.data) return originalListBackwards def checkIfThis2NodesDataAreEqual(self, nodeData1, nodeData2): if nodeData1 == nodeData2: return True return False def deleteMiddleNodeFromList(self, linkedList): listSize = linkedList.getListSize() if listSize <= 2: return nodeIndex = math.floor((listSize - 1) / 2) linkedList.deleteNode("index", nodeIndex) def listPartition(self, linkedList, number): if linkedList.head is None: print("List is empty.") return tempList = LinkedList() currentNode_originalList = linkedList.head while currentNode_originalList is not None: if currentNode_originalList.data >= number: tempList.append(currentNode_originalList.data) else: tempList.prepend(currentNode_originalList.data) currentNode_originalList = currentNode_originalList.nextNode linkedList.replaceListNodesWithAnotherListNodes(tempList) def checkIfListIsPalindrome(self, linkedList): if linkedList.head is None: return originalListBackwards = linkedList.cloneOriginalListAsBackwards() backwardsListCurrentNode = originalListBackwards.head originalListCurrentNode = linkedList.head while originalListCurrentNode.nextNode is not None: if not linkedList.checkIfThis2NodesDataAreEqual(backwardsListCurrentNode.data, originalListCurrentNode.data): print("List is NOT a palindrome.") return False originalListCurrentNode = originalListCurrentNode.nextNode backwardsListCurrentNode = backwardsListCurrentNode.nextNode print("List IS a palindrome.") return True def removeDuplicates(self): if self.head is None: return currentNode = self.head index = 0 duplicatesFound = False while currentNode.nextNode is not None: if self.howManyTimesThisNodeRepeats(currentNode.data) > 1: self.deleteNode("value", currentNode.data) duplicatesFound = True currentNode = currentNode.nextNode index += 1 if duplicatesFound is False: print("No duplicates were found") def printKthToLast(self, linkedList, kth): listSize = linkedList.getListSize() if linkedList.head is None: return False if kth > listSize: print("The Kth passed is longer than the linked list size.") return False getNodeAtThisIndex = listSize - kth currentNode = linkedList.head if kth == listSize: nodeValueMsg = "Value is: " + str(currentNode.data) nodeKthMsg = "Node at Kth: " + str(kth) print(nodeKthMsg + " | " + nodeValueMsg) return positionCounter = 1 while positionCounter is not getNodeAtThisIndex: currentNode = currentNode.nextNode positionCounter += 1 nodeValueMsg = "Value is: " + str(currentNode.nextNode.data) nodeKthMsg = "Node at Kth: " + str(kth) print(nodeKthMsg + " | " + nodeValueMsg) def returnKtnNode(self, linkedList, kth): listSize = linkedList.getListSize() if kth > listSize: return False currentNode = linkedList.head if kth == listSize: return currentNode positionCounter = 1 while positionCounter is not (listSize - kth): currentNode = currentNode.nextNode positionCounter += 1 return currentNode.nextNode def RemoveFirstNode(self): if self.head is None: return data = self.head.data self.head = self.head.nextNode return data
522f02bc0640964a1c2ed57d3499383a021506c2
oaugusto256/computerscience-psu
/cs161-intro-programming-solving-problem/HW4/score.py
814
4.03125
4
import math def score(distance, radius): """ Radius = 200 Examples: score(0,200) - Return 10 score(4,200) - Return 10 score(19,200) - Return 10 score(20,200) - Return 9 score(45,200) - Return 8 score(49,200) - Return 8 score(50,200) - Return 7 score(199,200) - Return 1 score(200,200) - Return 0 score(25x10,200) - Return 0 """ point = math.floor(10*(distance/radius)) # Calculate the target color which the arrow was shoot. score = 10 - point # Calculate the score using the point if score <= 0: # If the score is less or equal than 0. The arrow was fired off target score = 0 return score # Return the score
cfaef8bea20c252652c22f58e5c0b569b46312e4
miawich/repository_mia
/Notes/NotesB/05_sorting_miawich.py
2,149
4.21875
4
# sorting import random import time # swapping values a = 1 b = 2 temp = a a = b b = temp print(a, b) # pythonic way a, b = b, a # works only in python # selection sort my_list = [random.randrange(1, 100) for x in range(100)] my_list_2 = my_list[:] my_list_3 = my_list[:] print(my_list) print() for cur_pos in range(len(my_list)): min_pos = cur_pos for scan_pos in range(cur_pos + 1, len(my_list)): if my_list[scan_pos] < my_list[min_pos]: min_pos = scan_pos my_list[cur_pos], my_list[min_pos] = my_list[min_pos], my_list[cur_pos] print(my_list) # insertion sort for key_pos in range(1, len(my_list_2)): key_val = my_list_2[key_pos] # key dancer scan_pos = key_pos - 1 # looking to the dancer to the left while scan_pos >= 0 and key_val < my_list_2[scan_pos]: my_list_2[scan_pos + 1] = my_list_2[scan_pos] # move the scan position left scan_pos -= 1 my_list_2[scan_pos + 1] = key_val # commit the move print(my_list_2) my_list_3.sort() # much quicker!!! print(my_list_3) # optional function parameters print("Hello", end=" ") print("World", end=" ") print("Hello", "World", sep="Big", end="!!!\n") def hello(name, time_of_day="morning"): print("hello", name, "good", time_of_day) hello("mia") # lambda function # when you need a function, but dont want to make a function # also called anonymous function # lambda= parameter: return double_me = lambda x: x * 2 print(double_me(5)) product = lambda a, b: a * b my_list = [random.randrange(1, 100) for x in range(100)] print(my_list) print() my_2dlist = [[random.randrange(1, 100) , random.randrange(1, 100)] for x in range(100)] print(my_2dlist) print() # sort method(change the list in place) my_list.sort() print(my_list) my_list.sort(reverse=True) print(my_list) print() my_2dlist.sort(key=lambda a: a[0]) print(my_2dlist) print() my_2dlist.sort(key=lambda a: a[1]) print(my_2dlist) print() my_2dlist.sort(reverse=True, key=lambda a: sum(a)) print(my_2dlist) print() # sorted function (returns a new list) new_list = sorted(my_2dlist, reverse=True, key=lambda x: abs(x[0] - x[1])) print(new_list)
175536d4e18ea3aae593a3f6f786a64582048a01
JohnGoure/python-crash-course
/Chapter-3/places-to-visit.py
295
3.953125
4
places = ['monterey', 'paris', 'los angles', 'lake tahoe', 'new york city'] print(places) print(sorted(places)) print(places) print(sorted(places) ) print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse = True) print(places)
b9a5b00d8638d3134d0a3deada8b4da242ec52cc
JohnGoure/python-crash-course
/Chapter-5/ordinal-numbers.py
352
4.0625
4
ordinal_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] for ordinal_number in ordinal_numbers: if ordinal_number == 1: print(str(ordinal_number) + "st") elif ordinal_number == 2: print(str(ordinal_number) + "nd") elif ordinal_number == 3: print(str(ordinal_number) + "rd") else: print(str(ordinal_number) + "th")
13550a3bd2b683327b96a2676f5d006b69353b73
AndreiBratkovski/CodeFights-Solutions
/Arcade/Intro/Smooth Sailing/isLucky.py
614
4.21875
4
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. Example For n = 1230, the output should be isLucky(n) = true; For n = 239017, the output should be isLucky(n) = false. """ def isLucky(n): n_list = [int(i) for i in str(n)] half = int((len(n_list)/2)) list1 = n_list[:half] list2 = n_list[half:] if sum(list1) == sum(list2): return True else: return False
c54226da11c55ca48ea8ea3d9231897a66bdb9bf
AndreiBratkovski/CodeFights-Solutions
/Arcade/The Core/Intro Gates/addTwoDigits.py
268
4.0625
4
""" You are given a two-digit integer n. Return the sum of its digits. Example For n = 29, the output should be addTwoDigits(n) = 11. """ def addTwoDigits(n): total = 0 n = [int(i) for i in str(n)] for i in n: total += i return total
144affbc9d46e349ee76697c0f3ef466faaa3b3f
AndreiBratkovski/CodeFights-Solutions
/Arcade/Intro/Island of Knowledge/isIPv4Address.py
1,723
4.0625
4
""" An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address. IPv4 addresses are represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots, e.g., 172.16.254.1. Given a string, find out if it satisfies the IPv4 address naming rules. Example For inputString = "172.16.254.1", the output should be isIPv4Address(inputString) = true; For inputString = "172.316.254.1", the output should be isIPv4Address(inputString) = false. 316 is not in range [0, 255]. For inputString = ".254.255.0", the output should be isIPv4Address(inputString) = false. There is no first number. """ def isIPv4Address(inputString): orderedNumList = [] if inputString[0] == ".": return False IPNum = "" for i in inputString: if i != ".": IPNum += i else: if IPNum == "": return False else: orderedNumList.append(IPNum) IPNum = "" try: IPNum = int(IPNum) orderedNumList.append(str(IPNum)) except ValueError: return False if len(orderedNumList) != 4: return False try: orderedNumList = [int(x) for x in orderedNumList] except ValueError: return False for i in orderedNumList: if 0 <= i <= 255: continue else: return False return True
27f090cb703d12372205b7308efe17f5e0a73980
AndreiBratkovski/CodeFights-Solutions
/Arcade/Intro/Smooth Sailing/commonCharacterCount.py
718
4.34375
4
""" Given two strings, find the number of common characters between them. Example For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. Strings have 3 common characters - 2 "a"s and 1 "c". """ def commonCharacterCount(s1, s2): global_count = 0 char_count1 = 0 char_count2 = 0 s1_set = set(s1) for i in s1_set: if i in s2: char_count1 = s1.count(i) char_count2 = s2.count(i) if char_count1 <= char_count2: global_count += char_count1 elif char_count2 <= char_count1: global_count += char_count2 return global_count
71bbd17180dddba7251a2e1822d0d6452acc87d3
NunchakusLei/python-basic
/smart_lock.py
246
3.96875
4
password = input("Enter the passwrod to open the door > ") correct_password = "123456" if password == correct_password: print("The password is correct. Openning the door.") else: print("The password is incorrect. No open the door.")
b7315bf9114c641c1b3493ffef65109da2dc9046
Surenu1248/Python3
/eighth.py
434
4.15625
4
# Repeat program 7 with Tuples (Take example from Tutorial) tpl1 = (10,20,30,40,50,60,70,80,90,100,110) tpl2 = (11,22,33,44,55,66,77,88,99) # Printing all Elements..... print("List Elements are: ", tpl1) # Slicing Operations..... print("Slicing Operation: ", tpl1[3:6]) # Repetition..... print("Repetition of list for 5 times: ", (tpl1,) * 5) # Concatenation of lst and lst2 print("Combination of lst and lst2: ", tpl1 + tpl2)
f1e4f6da855d49216d836d7e79fe89ee69983346
Surenu1248/Python3
/first.py
401
3.953125
4
# Write a program for add, subtract, multiplication, division of two numbers. def add(a,b): return a + b def sub(a,b): return a - b def mul(a,b): return a * b def div1(a,b): return a / b def div2(a,b): return a // b print(add(10, 5)) print(sub(10, 5)) print(mul(10, 5)) print("Floating Division: ", div1(10, 5)) print("Integer Division: ", div2(10, 5))
54d2387d255062fe1e739f7defeb0cff1f9cf634
Surenu1248/Python3
/third.py
233
4.375
4
# Write a program to find given number is odd or Even def even_or_odd(a): if a % 2 == 0: print(a, " is Even Number.....") else: print(a, " is Odd Number.....") print(even_or_odd(10)) print(even_or_odd(5))
b70f897288430e69f488f4d79474f8f4678ddc16
ChWeiking/PythonTutorial
/Python高级/day41(线程进程回顾)/demo/01_进程线程锁/同步.py
356
3.515625
4
from threading import Thread import time num = 0 def test1(): global num for i in range(1000000): num += 1 print("test1 num=%s"%num) def test2(): global num for i in range(1000000): num += 1 print("test2 num=%s"%num) p1 = Thread(target=test1) p1.start() #time.sleep(3) p2 = Thread(target=test2()) p2.start()
b451f256bb1918783542ba683f146f463c3b6276
ChWeiking/PythonTutorial
/Python基础/day08(面向对象、类)/demo/练习/day_08.py
3,684
3.75
4
''' 面向对象技术简介 类(Class): 用来描述具有相同的属性和方法的对象的集合。 它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。 类变量:类变量在整个实例化的对象中是公用的。 类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。 数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。 方法重写:如果从父类继承的方法不能满足子类的需求, 可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。 实例变量:定义在方法中的变量,只作用于当前实例的类。 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。 继承也允许把一个派生类的对象作为一个基类对象对待。 例如,有这样一个设计:一个Dog类型的对象派生自Animal类, 这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)。 实例化:创建一个类的实例,类的具体对象。 方法:类中定义的函数。 对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。 ''' ''' class Car: #self表示当前实例对象 #实例变量:定义在方法中的变量,只作用于当前实例的类 #self: 代表类的实例,self 在定义类的方法时是必须有的, # 虽然在调用时不必传入相应的参数。 def runing(self): print("我是别克,我在跑………………") def toot(self): print("我在按喇叭鸣笛………………") bb = Car() bb.color = '白色' bb.lunzi = '四驱动' bb.runing() bb.toot() print('汽车属性:',bb.color,end = '') print(bb.lunzi) print() bb.color = '黑色' bb.lunzi = '涡轮四驱' print('汽车属性:',bb.color,end = '') print(bb.lunzi) print() print('********************************') print() bb1 = Car() bb1.color = '金黄色' bb1.lunzi = '二区' bb1.runing() bb1.toot() print('汽车属性:',bb1.color,end = '') print(bb1.lunzi) ''' class Car(): def __init__(self): self.name = '福特' self.price = 486748 dazhong = Car() print(dazhong.name) print(dazhong.price) print('************************************************') class Car(): def __init__(self,name,price): self.name = name self.price = price dazhong = Car('一汽大众',120000) print(dazhong.name) print(dazhong.price) print('************************************************') print() print('自定义参数,然后覆盖与没参数时的自动调用本身') print() class Car(): def __init__(self,name='本田',price=10000): self.name = name self.price = price dazhong = Car('一汽大众',120000) print(dazhong.name) print(dazhong.price) fute = Car('福特') print(fute.name) print(fute.price) class Car(): def __init__(self,name,price=10000): print(self) self.name = name self.price = price dazhong = Car('一汽大众',120000) print(dazhong) print(dazhong.name) print(dazhong.price) fute = Car('福特',321545) print(fute) print(fute.name) print(fute.price) print('************************************************') print() print('多参数调用,元组和字典的使用') print() class Car(): def __init__(self,*name,**price): print(self) self.name = name self.price = price dazhong = Car('一汽大众',la='塞班',p=1544) print(dazhong) print(dazhong.name) print(dazhong.price) fute = Car('福特','别克','奥迪',lala = '小米',sasa = '雷军',papa=321545) print(fute) print(fute.name) print(fute.price) print('************************************************')
5e1ffe216af069b7078d350af8f10421ad3e0f8b
ChWeiking/PythonTutorial
/Python高级/day36(链表、数据结构)/demo/01_引入.py
473
3.75
4
import time start_time = time.time() # 注意是三重循环 for a in range(0, 1001): for b in range(0, 1001): for c in range(0, 1001): if a**2 + b**2 == c**2 and a+b+c == 1000: print("a, b, c: %d, %d, %d" %, (a, b,c)) end_time = time.time() print("elapsed: %f" % (end_time - start_time)) print("complete!") #1000*1000*1000*2 #2*n**3 #3*n**3+10--->3*n**3--->n**3 # if xx: # 1 # 2 # 3 # 4 # else: # 1 # 2
d6306fd2b306a4a534e7984a84b69c438a9b2248
ChWeiking/PythonTutorial
/Python基础/day05(集合容器、for循环)/demo/01_list/04_列表基础操作.py
2,101
4.0625
4
list = [1,2,3,4,5] # 按下标取值1 print(list[0]) # 按下标最后一个元素 print(list[-1]) search = list.index(5) #查找对应值的下标 print(search) list = [1,2,3,4,5,5,5] #查找某个元素的出现次数 mynum = list.count(5) print(mynum) #列表长度 print(len(list)) #大小值 print(max(list)) print(min(list)) #末尾添加 list.append(8) print(list) #从下标插入 list.insert(0,9) print(list) #追加多个值 list2 = [233,666,888] list.extend(list2) print(list) # 区别 list.append(list2) print(list) # 从下标修改对应元素 list[0] = 0 print(list) # 弹出 rec = list.pop() print(rec) print(list) #按下标弹出 rec = list.pop(0) print(rec) print(list) #按下标删除 list.pop(4) print(list) #按元素删除 list.remove(5) print(list) strlist = ['Hi~']*20 print(strlist) print(list2+list2) print('hello' in strlist) print('hello' not in strlist) # 排序 list3 = list2+list2 print(list3) list3.sort() print(list3) list4 = list3.sort() print(list4) # 区别 list3 = list2+list2 list4 = sorted(list3) print(list4) # 循环判断是否为列表最后一个元素 # list5 = [1,2,3,4,5] # while True : # XX = int(input("请输入一个数字:")) # if XX == list[-1]: # print("True") # else: # print("False") # 使用下标比对值 a = [1,2,3,45,56,76,87,8] b = 8 c = a.index(b) if len(a)-1 == c: print("true") else: print("false") # 按元素查询下标 list = [1,2,3,5,6,2,4,8,9,2,7] la = list.index(2) print(la) # 查询元素在列表的数量 lala = list.count(2) print(lala) # 按下表位置插入元素(下标2,插入11) list.insert(2,11) print(list) # 从末尾添加元素 list.append(678) print(list) # 删除并弹出末尾元素 list.pop() print(list) # 按下标删除元素 del list[0] print(list) # 函数用于在列表末尾一次性追加另一个序列中的多个值 list.extend([34,43,545,67]) print(list) # 移除元素 list.remove(11) print(list) list.remove(2) print(list) # 集合容器嵌套取值并修改 k = ([2,3,1,3,4,5],'老王',546) print(k) k[0][5] = 66 print(k)
5689fb6197e042236fade0ca7724d6ce96025538
ChWeiking/PythonTutorial
/Python高级/day33(tcp通信)/demo/01_tcp服务器端.py
682
3.59375
4
#1. 买个手机 #2. 插上手机卡 #3. 设计手机为正常接听状态(即能够响铃) #4. 静静的等着别人拨打 from socket import * # 1. socket创建一个套接字 tcpServer = socket(AF_INET,SOCK_STREAM) tcpServer.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 2. bind绑定ip和port tcpServer.bind(('',5678)) # 3. listen使套接字变为可以被动链接 tcpServer.listen(5) # 4. accept等待客户端的链接 print('服务端监听中......') #第一个值:关联了服务端和客户端信息,可以与对应的客户端通信 #第二个值:客户端的ip,port socketClient,cliendAddrdess = tcpServer.accept() print(socketClient) tcpServer.close()
e371b410dcd37608a68114fff2a56926b3efff88
ChWeiking/PythonTutorial
/Python高级/day41(线程进程回顾)/demo/02_链表队列栈/02.单向循环链表.py
2,925
3.953125
4
class Node(object): """docstring for SinCycLinkedList""" #初始化节点 def __init__(self,item): self.item = item self.next = None class SinCycLinkedList(object): """docstring for SinCycLinkedList""" def __init__(self): self._head = None # is_empty() 判断链表是否为空 def is_empty(self): return self._head == None # length() 返回链表的长度 def length(self): if self.is_empty(): return 0 count = 1 cur = self._head while cur.next != self._head: count += 1 cur = cur.next return count # travel() 遍历 def travel(self): if self.is_empty(): return cur = self._head print(cur.item) while cur.next != self._head: cur = cur.next print(cur.item) print("") # add(item) 在头部添加一个节点 def add(self,item): node = Node(item) if self.is_empty(): self._head = node node.next = self._head else: node.next = self._head cur = self._head while cur.next != self._head: cur = cur.next cur.next = node self._head = node # append(item) 在尾部添加一个节点 def append(self,item): node = Node(item) if self.is_empty(): self._head = node node.next = self._head else: cur = self._head while cur.next != self._head: cur = cur.next cur.next = node#将尾节点指向node node.next = self._head#将node指向头结点_head # insert(pos, item) 在指定位置pos添加节点 def insert(self,pos,item): if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: node = Node(item) cur = self._head count = 0 while count < (pos-1): count += 1 cur = cur.next node.next = cur.next cur.next = node # remove(item) 删除一个节点 def remove(self,item): if self.is_empty(): return cur = self._head pre = None if cur.item == item: #如果不止一个节点 if cur.next != self._head: #先找到尾节点,将尾节点的next指向第二个节点 while cur.next != self._head: cur = cur.next cur.next = self._head.next self._head = self._head.next else: #链表只有一个节点 self._head = None else: pre = self._head while cur.next != self._head: if cur.item == item: pre.next = cur.next return else: pre = cur cur = cur.next if cur.next == item: pre.next = cur.next # search(item) 查找节点是否存在 def search(self,item): if self.is_empty(): return False cur = self._head if cur.item == item: return True while cur.next != self._head: cur = cur.next if cur.item == item: return True return False def main(): ll = SinCycLinkedList() ll.add(1) ll.add(2) ll.append(3) ll.insert(2, 4) ll.insert(4, 5) ll.insert(0, 6) print("length:",ll.length()) ll.travel() print(ll.search(3)) print(ll.search(7)) ll.remove(1) print("length:",ll.length()) ll.travel() if __name__ == "__main__": main()