blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5b0c8fc9f82e9e39c9ee7a1d6f9ee9687aea3281
filmote/PythonLessons
/Week2_4.py
956
4.125
4
import turtle def polygon(aTurtle, sides, length): counter = 0 angle = 360 / sides while counter < sides: aTurtle.right(angle) aTurtle.forward(length) counter = counter + 1 # ------------------------------------------------- # set up our shapes # triangle = { "name": "Triangle", "numberOfSides": 3, "length": 120 } small_square = { "name": "Square", "numberOfSides": 4, "length": 70 } big_square = { "name": "Square", "numberOfSides": 4, "length": 150 } pentagon = { "name": "Pentagon", "numberOfSides": 5, "length": 60 } shapes = [triangle, small_square, big_square, pentagon] # ------------------------------------------------- # draw our shapes # window = turtle.Screen() window.bgcolor("black") terry = turtle.Turtle() terry.shape("turtle") terry.color("red") for shape in shapes: polygon(terry, sides = shape["numberOfSides"], length = shape["length"]) window.exitonclick()
63526f56cdceb9832abfecc2667b0a72e27e8bba
Biofobico/learn_python
/chp6_dictionaries/alien.py
1,156
3.890625
4
alien_0 = {'color': 'green', 'points': 5} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) new_points = alien_0['points'] print(f"You just earned {new_points} points!") print(alien_0['color']) print(alien_0['points']) alien_1 = {} alien_1['color'] = 'violet' alien_1['points'] = 7 print(alien_1) alien_2 = {'color': 'yellow'} print(f"The alien is {alien_2['color']}.") alien_2['color'] = "orange" print(f"The alien is now {alien_2['color']}.") print("\n") alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} print(f"Original position: {alien_0['x_position']}") # Move the alien to the right. # Determine how far to move the alien based on its current speed if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: # This must be a fast alien x_increment = 3 # The new position is the old position plus the increment alien_0['x_position'] = alien_0['x_position'] + x_increment print(f"New Position: {alien_0['x_position']}") print('\n') alien_0 = {'color': 'green', 'points': 5} print(alien_0) del alien_0['points'] print(alien_0)
5fa6884b11f9481ee914f6f186cabeb319f48453
landalex/FinalProject
/pythonShineTest.py
422
3.828125
4
newList = [] for i in range(len(listOrig)): newList.append(listOrig[i]) counter = 0 for i in range(len(listOrig) - 1): counter += 1 if listOrig[i] > listOrig[i+1]: newList[i+1] = newList[i] newList[i] = listOrig[i+1] elif listOrig[i] <= listOrig[i+1]: newList[i+1] = listOrig[i+1] if counter == ((len(listOrig)) - 1): if newList[-2] > newList[-1]: newList[-1] = newList[-2] newList[-2] = listOrig[-1]
bfb620c5098c6f05221f30ce7f4105f2230d926e
mathieuguyot/advent_of_code_2020
/src/day_3.py
683
3.78125
4
file = open('./data/day_3.txt',mode='r') lines = file.read().splitlines() file.close() def slope(lines, offset_col, offset_row): col_size = len(lines[0]) cur_col = 0 cur_row = 0 tree_count = 0 while cur_row < len(lines): if lines[cur_row][cur_col % col_size] == "#": tree_count += 1 cur_col += offset_col cur_row += offset_row return tree_count problem_1 = slope(lines, 3, 1) problem_2 = slope(lines, 1, 1) * slope(lines, 3, 1) * slope(lines, 5, 1) * slope(lines, 7, 1) * slope(lines, 1, 2) print("DAY III") print("Part I :",problem_1) print("Part II :",problem_2) assert problem_1 == 151 assert problem_2 == 7540141059
85589f4690b21964fb054087e313ea1649f2fb78
rifanarasheed/PythonDjangoLuminar
/FILEIO/covid_analysis.py
1,617
3.96875
4
# need each states confirmed cases from covid_19_india dataset covid = open("covid_19_india.csv","r") # file reading dict = {} # created an empty dictionary to get count of confirmed cases of each state # key value # state confirmed for line in covid: # reading each line and splitting each word by , data = line.rstrip("\n").split(",") # only needed state and confirmed cases state = data[3].rstrip("***") # removing *** from states having *** if(state == "Telengana"): # there is telengana and telengane, so both are taken as two state state = "Telangana" confirmed_cases = int(data[8]) if(state not in dict): # if state key is not present in the dict , that key is present with its corresponding case, not 1 dict[state] = confirmed_cases else: dict[state] = confirmed_cases # if the state key is present, then update the confirm case. for key,value in dict.items(): # print the dict where state is key and confirmed cases are value print(key,"---->",value) # to get state which has highest confirmed cases ( sort ) # key = dict.get --> to get all values. to get specific value,we need to specify it in () # reverse = True , to get highest value result = sorted(dict,key = dict.get,reverse= True) print(result) # to print in alphabetic order # result = sorted(dict) # to get highest confirmed state print(result[0],dict.get(result[0])) # to get 1st state of list as well as its value.
b43f1787d4d20358f4c34fcb3ed8327ca88794d6
MaesterPycoder/Python_Programming_Language
/python_codes/reverse.py
64
3.75
4
a=list(input("Enter number:")) a.reverse() print("".join(a))
127ef87c7ba3865e982df6149ecdd385541dad80
chinmairam/Python
/data.py
519
3.625
4
filename = 'data.txt' try: with open(filename) as f: for line in f: items = line.split(',') total = 0 try: for item in items: num = int(item) total += num print("Total = " + str(total)) except: print("Error converting to integer.",items) except: print("Error opening file. " + filename) finally: print("This is finally block. Code will execute no matter what.")
41be38486c6d0191158300ad2794f4eb9f71d546
kabdesh/lesson-1
/nice.py
609
4.03125
4
number = int (input ("Введите число 1-12: ")) if number == 1: print("январь") elif number == 2: print("Февраль") elif number == 3: print("Февраль") elif number == 4: print("Февраль") elif number == 5: print("Февраль") elif number == 6: print("Февраль") elif number == 7: print("Февраль") elif number == 8: print("Февраль") elif number == 9: print("Февраль") elif number == 10: print("Февраль") elif number == 11: print("Февраль") elif number == 12: print("Февраль")
3648230763806af85c8eb7fcd19f081b0c15b3d4
b166erbot/sql-khanacademy
/sql-6.py
2,124
3.875
4
import sqlite3 from os.path import exists def bancoDeDados(*args: tuple): """ Função que comita os comandos sql. """ connection = sqlite3.connect('teste6.db') cursor = connection.cursor() cursor.execute(*args) retorno = cursor.fetchall() connection.commit() connection.close() return retorno def main(): existiaDb = exists('teste6.db') comandoSql = ('CREATE TABLE IF NOT EXISTS padaria (id INTEGER PRIMARY' ' KEY, nome TEXT, quantidade INTEGER, preço INTEGER,' ' lucro INTEGER)') bancoDeDados(comandoSql) if not existiaDb: bancoDeDados('INSERT INTO padaria VALUES (1, "rosca", 30, 0.30, 0.05)') bancoDeDados('INSERT INTO padaria VALUES(2, "pão", 50, 0.20, 0.05)') bancoDeDados('INSERT INTO padaria VALUES(3, "pudim", 30, 0.50, 0.15)') bancoDeDados( 'INSERT INTO padaria VALUES(4, "mortadela", 15, 3.00, 1.00)') bancoDeDados( 'INSERT INTO padaria VALUES(5, "iogurte", 20, 2.50, 1.00)') bancoDeDados('INSERT INTO padaria VALUES(6, "bolo", 10, 30.00, 10.00)') bancoDeDados('INSERT INTO padaria VALUES(7, "torta", 5, 20.00, 7.50)') bancoDeDados( 'INSERT INTO padaria VALUES(8, "brigadeiro", 30, 0.50, 0.15)') bancoDeDados('INSERT INTO padaria VALUES(9, "pastel", 15, 1.50, 0.50)') bancoDeDados( 'INSERT INTO padaria VALUES(10, "coxinha", 15, 1.30, 0.40)') bancoDeDados( 'INSERT INTO padaria VALUES(11, "pão de queijo", 200, 0.30, 0.10)') bancoDeDados( 'INSERT INTO padaria VALUES(12, "pão de forma", 10, 2.50, 0.90)') bancoDeDados( 'INSERT INTO padaria VALUES(13, "biscoito", 10, 1.50, 0.50)') bancoDeDados( 'INSERT INTO padaria VALUES(14, "bolacha", 90, 1.50, 0.70)') bancoDeDados( 'INSERT INTO padaria VALUES(15, "chocolate", 50, 0.70, 0.20)') print(bancoDeDados('SELECT SUM(lucro) FROM padaria')) print(bancoDeDados('SELECT * FROM padaria ORDER BY quantidade')) if __name__ == '__main__': main()
0f17cd7822955aeb9e6c03d60686f5be829cf61c
MirnaZe/Tarea_03
/rendimientoAuto.py
916
3.71875
4
#Mirna Zertuche Calvillo A01373852 #Un programa que calcula el rendimiento de kilometros por litro de gasolina, lo transforma a millas por galon y calcula cuantos litros se necesitan para ciertos kilometros def KmporLitro(Km,Lt): Kxl=Km/Lt return Kxl def MiporGalon(Km,Lt): KaM= Km/1.6093 LaG= Lt*0.264 MxG= KaM/LaG return MxG def LitrosRecorrer(kl,Kmr): LxR= Kmr/kl return LxR def main(): Km = int(input("Teclea el número de km recorridos: ")) Lt = int(input("Teclea el número de litros de asolina usados: ")) kl= KmporLitro(Km,Lt) mg= MiporGalon(Km,Lt) print("Si reorres",Km,"Kms con",Lt,"litros de gasolina, el rendimiento es:") print("%.2f" %kl,"km/l") print("%.2f" %mg,"mi/gal") Kmr = int(input("¿cuántos kilómetros vas a recorrer? ")) Ltn = "%.2f" %LitrosRecorrer(kl,Kmr) print("Para recorrer",Kmr,"km necesitas",Ltn,"litros de gasolina") main()
cc839b7b7be1f4516d7bb83ded927308947c0c08
slih01/Alleyway
/ball.py
488
3.78125
4
from turtle import Turtle import random class Ball(Turtle): def __init__(self): super().__init__() self.shape("circle") self.color("white") self.shapesize(stretch_len=0.7,stretch_wid=0.7) self.penup() self.hideturtle() self.goto(random.randint(-250,250),0) self.showturtle() self.setheading(self.towards(0,-220)) def move(self): self.hideturtle() self.forward(10) self.showturtle()
0062e95b427d3b2feae277c76bf6a0cc3b0fb5fd
Tailsxky/python_learning_demo
/guess_random_number/project.py
719
4.125
4
from random import randint guess_number = randint(1,50) #print(type(guess_number)) bingo = False your_guess = int(input("guess a number between 1 to 50: ")) while bingo == False: '''if(type(int(your_guess)) != int): print("please input a number:") your_guess = input("guess again: ")''' if(your_guess < guess_number): print("{} is small than the correct number".format(your_guess)) your_guess = int(input("guess again: ")) elif(your_guess > guess_number): print("{} is bigger than the correct number".format(your_guess)) your_guess = int(input("guess again: ")) else: bingo = True print("{} is the correct number!".format(your_guess))
2b360e7cb9203ef081fc826be56edc17a31a9bff
haiwenzhu/leetcode
/substring_with_concatenation_of_all_words.py
1,168
3.53125
4
class Solution: """ @see https://leetcode.com/problems/substring-with-concatenation-of-all-words/ """ # @param S, a string # @param L, a list of string # @return a list of integer def findSubstring(self, S, L): l = len(L[0]) lenOfL = len(L) res = [] for i in range(0, l): matches = [] for j in range(i, len(S), l): s = S[j:j+l] if s in L: if matches.count(s) != L.count(s): matches.append(s) if len(matches) == lenOfL: res.append(j - lenOfL*l + l) matches.pop(0) else: #delete the part befor first occurance of s tmp = matches[matches.index(s)+1:] matches = tmp matches.append(s) else: matches = [] return res if __name__ == "__main__": solution = Solution() print(solution.findSubstring("abababab", ["a", "b", "a"]))
23e304867b047472eeb4eb211b8789593122d89a
andrew8gmf/python
/matrizes_matematica/1-e).py
633
3.953125
4
import numpy as np import random print("\nSoma de matrizes\n") x = int(input("Ordem das matrizes: ")) y=x*x matrizA = np.arange(y).reshape(x,x) for i in range(x): for j in range(x): matrizA[i][j] = random.randint(0,9) print("\n\nMatriz A: \n") for i in range(x): for j in range(x): print(matrizA[i][j], end=" ") print() matrizB = np.arange(y).reshape(x,x) for i in range(x): for j in range(x): matrizB[i][j] = random.randint(0,9) print("\n\nMatriz B: \n") for i in range(x): for j in range(x): print(matrizB[i][j], end=" ") print() soma = np.add(matrizA,matrizB) print("\n\nMatriz A + Matriz B: \n") print(soma)
a4405e1698d6e00f2da2d4cfba2b228bd6f92580
gokilarani/python
/large.py
183
3.78125
4
a=input() b=input() c=input() if (int(a)>int(b)) and (int(a)>int(c)): print('a is great') elif (int(b)>int(c)): print('b is great') else: print('c is great')
b7fe74be0601476f0f521dea48c572d619d0e637
zakir360hossain/MyProgramming
/Languages/Python/Learning/basics/builtins/sorting.py
353
3.90625
4
state = ['PA', 'MA', 'NJ', 'NY', 'TN', 'CA', 'DE', 'AL', 'AZ', 'AR'] print(sorted(state)) print(sorted(state, reverse=True)) fruit_and_price = {'Apple': 1.99, 'Banana': 0.99, 'Orange': 1.49, 'Cantaloupe': 3.99, 'Grapes': 0.39} print(sorted(fruit_and_price.keys())) # or just fruit_and_price, .keys() not needed print(sorted(fruit_and_price.values()))
31cc77d837c979e5fb6dbfb92084bb6856685399
running258/autotest_2
/test.py
255
3.734375
4
class A: def __init__(self): A = 'A' self.a = 'a' print('init A') class B(A): def __init__(self): super(B, self).__init__() # self.b = 'b' # print('init B') pass b = B() print(b.a)
580678e760f446055328a93b1d23e907d551adc3
jacklynknight08/py_FamilyDictionary
/family_dict.py
725
4.59375
5
# Define a dictionary that contains information about several members of your family. my_family = { 'mother': { 'name': 'Beth', 'age': 50 }, 'sister': { 'name': 'Jessi', 'age': 33 }, 'brother': { 'name': 'Joey', 'age': 29 }, 'father': { 'name': 'Steve', 'age': 50 } } # Using a dictionary comprehension, produce output that looks like the following example. # Krista is my sister and is 42 years old # Helpful hint: To convert an integer into a string in Python, it's str(integer_value) for key, value in my_family.items(): print("My " + key +"'s name is " + value["name"] + " and is " + str(value["age"]) + " years old.")
5f80776fc0ed601c7adb3b6e156df2a1ea660e44
1098813507/Taller-de-Algoritmos
/4.py
239
3.890625
4
print("la suma de 2 numeros ") nume1=float(input("digite un numero")) print(nume1) nume2=float(input("digite un numero")) print(nume2) suma=nume1+nume2 print("la suma de los numeros"+str(sume1)+"y"+str(num2)+"es"+str(suma1)) print("end")
927dbedba275860b05ec924a1a92e8ae50f8ede3
saidadem3/hrank
/Python/dictionary/dictionary.py
703
3.875
4
if __name__ == '__main__': #how many students we will create in our dictionary n = int(input()) student_marks = {} #first input (name) is the key for the dictionary (student_marks) - line 9 #(*line) takes multiple inputs and stores them as the values to a student - line 9 #(scores) converts each number to a float then stores the values to a list - line 11 #(s_m[name] = scores) adds new item to dictionary - line 12 for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() grades = student_marks.get(query_name) print("%.2f" % float(sum(grades)/len(grades)))
ce0dadb022f46b32ed8f33ea71e5d477082b424a
ankurjaiswal496/Leetcode-Solutions
/problems-tab/459. Repeated Substring Pattern.py
378
3.578125
4
class Solution: def repeatedSubstringPattern(self, s) : # print(len(s)//2) for k in range(1, len(s)//2 +1): # print(s[k:] + s[:k]) if s == s[k:] + s[:k]: print(s[k:] + s[:k]) return True return False obj=Solution() obj.repeatedSubstringPattern("abab") # s="abab" # print(s[1:])
4a750716d15ce023e41f8d8f470b27260371e10f
KirillKras/python_basic
/pb_les5_e2.py
255
3.5625
4
# Задача-2: # Напишите скрипт, отображающий папки текущей директории. import os def view_dir(): for r, d, f in os.walk(os.getcwd()): for folder in d: print(folder) view_dir()
8411b8c8c7a1501a182c9ec80b8578f8860fb9d1
CWJWANJING/Number-guessing
/number-guessing.py
1,860
3.828125
4
import random import pdb # can decide how many people to play # maximum players # 1&2: number in range 1-100 # 3: number in range 1-150 # 4: 1-200 # 5: 1-250 # 6: 1-300 # enter the number of player first # 2-players: def checknum(inp, guessnum): correct = False if inp < guessnum: print(f"The number is greater than {inp}") if inp > guessnum: print(f"The number is smaller than {inp}") if inp == guessnum: print(f"You win! The number is {guessnum}") correct = True return correct def validinp(inp): if not inp.isdigit(): return False if int(inp) not in range(1,7): return False return True def validinp1(inp): if not inp.isdigit(): return False if int(inp) not in range(1,101): return False return True if __name__ == "__main__": print(f"Please enter the numer of players:") pnum = None while True: pnum = input() # pnum can only be in range 1-6 valid = validinp(pnum) if valid == False: continue # else, do the thing else: break if int(pnum) == 1: print(f"Please guess a number in range 1-100, you have 10 chances:") guessnum = random.randint(1,100) while True: inp = input() valid = validinp1(inp) if valid == False: print("Please enter a valid number") continue else: correct = checknum(int(inp), guessnum) if correct == True: break else: continue # if int(inp) == 2: # # TODO: # if int(inp) == 3: # # TODO: # if int(inp) == 4: # # TODO: # if int(inp) == 5: # # TODO: # if int(inp) == 6: # # TODO:
054f4dd0d87129f8f94d891757e71723aabfeb20
SilvesSun/learn-algorithm-in-python
/dynamic programming/718_最长重复子数组.py
702
3.53125
4
from pprint import pprint from typing import List class Solution: def findLength(self, nums1: List[int], nums2: List[int]) -> int: # dp[i][j] 表示以下标i-1结尾的nums1, 和以下标j-1结尾的nums2的最长重复子数组长度 m, n = len(nums1), len(nums2) dp = [[0] * (n+1) for _ in range(m+1)] res = 0 for i in range(1, m+1): for j in range(1, n+1): if nums1[i - 1] == nums2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 if dp[i][j] > res: res = dp[i][j] return res if __name__ == '__main__': a = [1, 2, 3, 2, 1] b = [3, 2, 1, 4] print(Solution().findLength(a, b))
6fc9c09ac901664d3ae7551efdb81acf0b294ccb
jan-2018-py1/joelstiller_classwork
/find_character.py
359
4.3125
4
# Assignment: Find Characters # Write a program that takes a list of strings # and a string containing a single character, and prints a new list of all the strings containing that character. def find_char(chr,xlist): for x in xlist: if chr in x: print x word_list = ['hello','world','my','name','is','Anna'] find_char('o',word_list)
cd2a711edd3d890da1b921859b3f93278fccb01c
rakshi2002/stars
/subtraction/subtraction.py
115
3.53125
4
def dosubtraction(): a=9 b=4 c=a-b #difference of a and b print(a,"-",b,"=",c) dosubtraction()
2abbabee6552232b65fb159cf765c6e4b7c95e68
bcasalvieri/Modern-Python-Bootcamp
/10_looping_in_python/emoji_art_exercise.py
110
3.96875
4
for num in range(1, 10): print("😀" * num) num = 1 while num < 10: print("😀" * num) num += 1
c406b50f8f4e827b0b9b7ed5e81ef187592f446b
RosaIss/advent_of_code
/2018/d2_1.py
691
3.71875
4
""" --- Day 2: Inventory Management System part 1---""" import sys def calculate_checksum(ids): two_char = 0 three_char = 0 size_alpha = 26 alpha = [0] * size_alpha for i in ids: alpha = [0] * size_alpha for c in i: alpha[ord(c) - ord('a')] += 1 two_char += 1 if 2 in alpha else 0 three_char += 1 if 3 in alpha else 0 return two_char * three_char def main(): line = None checksum = None ids = [] for line in sys.stdin: line = line[:-1] ids.append(line) checksum = calculate_checksum(ids) print "Checksum: {}".format(checksum) if __name__ == "__main__": main()
5aafa164b62e8db0a9e2e57906f2bb5c6641ff42
michedomingo/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py
6,622
3.671875
4
#!/usr/bin/python3 """ This module contains unittest for /models/rectangle.py """ import unittest from models.base import Base from models.rectangle import Rectangle class TestRectangle(unittest.TestCase): """This class TestRectangle defines tests for class Rectangle methods""" def test00_args(self): """Test for valid arguments""" r = Rectangle(10, 2, 0, 0, 12) self.assertEqual(r.width, 10) self.assertEqual(r.height, 2) self.assertEqual(r.x, 0) self.assertEqual(r.y, 0) self.assertEqual(r.id, 12) def test01_int(self): """Test valid id attribute""" Base._Base__nb_objects = 0 r1 = Rectangle(10, 2) r2 = Rectangle(2, 10) r3 = Rectangle(10, 2, 0, 0, 12) self.assertEqual(r1.id, 1) self.assertEqual(r2.id, 2) self.assertEqual(r3.id, 12) def test02_width_height(self): """Test for valid width & height""" r1 = Rectangle(10, 2) r2 = Rectangle(2, 10) r3 = Rectangle(10, 2, 0, 0, 12) self.assertEqual(r1.width, 10) self.assertEqual(r1.height, 2) self.assertEqual(r2.width, 2) self.assertEqual(r2.height, 10) self.assertEqual(r3.width, 10) self.assertEqual(r3.height, 2) def test03_x_y(self): """Test for valid x & y""" r1 = Rectangle(10, 20) r2 = Rectangle(1, 2, 3, 4, 5) self.assertEqual(r1.x, 0) self.assertEqual(r1.y, 0) self.assertEqual(r2.x, 3) self.assertEqual(r2.y, 4) def test04_none(self): """Test with None""" with self.assertRaises(TypeError) as e: r = Rectangle(None) self.assertEqual( "__init__() missing 1 required positional argument: 'height'", str(e.exception)) def test05_empty(self): """Test without arguments""" with self.assertRaises(TypeError) as e: r = Rectangle() self.assertEqual( "__init__() missing 2 required positional arguments:" + " 'width' and 'height'", str(e.exception)) def test06_nan(self): """Test with nan""" with self.assertRaises(TypeError) as e: Rectangle(float('nan'), 2, 3, 4,) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, float('nan'), 3, 4,) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, float('nan'), 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, float('nan')) self.assertEqual('y must be an integer', str(e.exception)) def test07_infinity(self): """Test with infinity""" with self.assertRaises(TypeError) as e: Rectangle(float('inf'), 2, 3, 4,) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, float('inf'), 3, 4,) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, float('inf'), 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, float('inf')) self.assertEqual('y must be an integer', str(e.exception)) def test08_float(self): """Test with float""" with self.assertRaises(TypeError) as e: Rectangle(1.1, 2, 3, 4,) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2.2, 3, 4,) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3.3, 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, 4.4) self.assertEqual('y must be an integer', str(e.exception)) def test09_string(self): """Test with string""" with self.assertRaises(TypeError) as e: Rectangle("1", 2, 3, 4,) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, "2", 3, 4,) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, "3", 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, "4") self.assertEqual('y must be an integer', str(e.exception)) def test10_list(self): """Test with list""" with self.assertRaises(TypeError) as e: Rectangle([1, 2, 3], 2, 3, 4) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, [1, 2, 3], 3, 4) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, [1, 2, 3], 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, [1, 2, 3]) self.assertEqual('y must be an integer', str(e.exception)) def test11_tuple(self): """Test with list""" with self.assertRaises(TypeError) as e: Rectangle((1, 2, 3), 2, 3, 4) self.assertEqual('width must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, (1, 2, 3), 3, 4) self.assertEqual('height must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, (1, 2, 3), 4) self.assertEqual('x must be an integer', str(e.exception)) with self.assertRaises(TypeError) as e: Rectangle(1, 2, 3, (1, 2, 3)) self.assertEqual('y must be an integer', str(e.exception)) def test12_area(self): """Test for valid area values""" r1 = Rectangle(3, 2) r2 = Rectangle(2, 10) r3 = Rectangle(8, 7, 0, 0, 12) self.assertEqual(r1.area(), 6) self.assertEqual(r2.area(), 20) self.assertEqual(r3.area(), 56) if __name__ == '__main__': unittest.main()
0dd110262d016921388a93e0783183e5781d3833
Yasara123/Grade-Prediction-System
/final_SFT/win_Login.py
3,238
3.515625
4
__author__ = 'Yas' from Tkinter import * from ttk import Button from Tkinter import Tk import base64 import tkMessageBox as box import os from PIL import Image, ImageTk ''' This is the login class of the system. It verify the username and password by using config text file. If user fogot the pass word he/she can change the new password and restore the password by restoring it. At the 1st time user should enter the system by using username Yas and password sri ''' #this is the class which display the error massage class Example(): def onError(self): box.showerror("Error", "Login Fail") def onInfo(self): box.showinfo("Information", "Login Sucessfully") #this is the class for login function class LoginWindow(): def __init__(self, root): self.mastert = root self.mastert.configure(background='#8A002E') self.img = ImageTk.PhotoImage(Image.open("logo4.jpg")) self.imglabel = Label(self.mastert, image=self.img).grid(row=0, column=4) self.mastert.wm_title("System Login") Label(self.mastert,background='#8A002E',foreground="white", text="Enter System UserName").grid(row=1) Label(self.mastert, background='#8A002E',foreground="white",text="Enter System Password:").grid(row=2) self.e1 = Entry(self.mastert) self.e2 = Entry(self.mastert) self.e1.grid(row=1, column=1) self.e2.grid(row=2, column=1) Button(self.mastert, text='Help', command=self.Help).grid(row=3, column=0, sticky=W, pady=4) Button(self.mastert, text='Quit', command=self.mastert.quit).grid(row=3, column=3, sticky=W, pady=4) Button(self.mastert, text='Submit', command=self.Fun).grid(row=3, column=4, sticky=W, pady=4) Button(self.mastert, text='Fogot Password', command=self.fogot).grid(row=3, column=1, sticky=W, pady=4) #read password from file------------------- def getUserUserNm(self,user): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word) if tem[0]==base64.b64encode(user): return 1 else: return 0 #get password----------- def getUserPass(self,pas): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word) if tem[1]==base64.b64encode(pas): return 1 else: return 0 #this is the function for enter the system if login sucessful def SysLog(self): os.system('python win_HomeWin1.py') #this is the function for change password def fogot(self): os.system('python Config.py') #this is the function for verify username and password def Fun(self): self.UserNM = self.e1.get() self.PassWD = self.e2.get() user=self.getUserUserNm(self.UserNM) pas=self.getUserPass(self.PassWD) if (user==1)&(pas==1): Example().onInfo() self.mastert.withdraw() self.SysLog() else: Example().onError() def Help(self): os.system('python win3_Help.py') #To generate the system root = Tk() my_gui = LoginWindow(root) root.mainloop()
2f543f213abb7f5f10db6a7d2e7f0b36487e6801
RaymondTseng/ThaiTravel
/Search/engsegment.py
2,774
3.625
4
# -*- coding:utf-8 -*- import nltk from nltk.corpus import stopwords import json comments = ['I am not fond of shopping. But when i got there in saw the affordable and a lot of clothes to choose and made me wants to shop. This mall will also test your bargaining skills. The only problem is the mall close at 8pm. It is quite early though. Outside the mall are a lot of food stalls. It...', "If you can't go to Chatuchak Weekend Market, Platinum Mall is best option..It's wholesale mall & you’ll save more if buying in larger quantities ( fashion clothing and accessories )Fun shopping with nice foodcourt @ 4th floor; crowded, but really enjoy the atmosphere", "we actually wanted to go to chatuchak weekend market . my friend recommended we go to Platinum instead as it's air conditioned . was delighted to be here . plenty of handicrafts store on level 4. men's clothing was very cheap as well as accessories . the food court was awesome too. there is a huge KFC in the food...", "This Mall is located in the Pratunam Area and you can access it directly from the Central World through the newly constructed Walk Way.It has six floors of clothes and accessories and each floor is named after the six famous International shopping districts: Soho,Oxford,Orchard,Camden,Ginza and Nathan.The complex also contains a Novotel Hotel,food court and various other eating options like Black..."] def extract_tags(comments): idf = {} temp = [] if not comments: return [] for comment in comments: comment = json.loads(comment) content = comment['content'] words = nltk.word_tokenize(content.decode('utf8')) clean_words = [w for w in words if (w not in stopwords.words('english'))] tag_words = nltk.pos_tag(clean_words, tagset='universal') result = [w[0] for w in tag_words if w[1] in [u'NOUN', u'ADV', u'ADJ', u'ADP']] tf = {} for r in result: if tf.has_key(r): tf[r] += 1 else: tf[r] = 1 for key, value in tf.iteritems(): tf[key] = float(value) / len(result) temp.append(tf) result = set(result) for r in result: if idf.has_key(r): idf[r] += 1 else: idf[r] = 1 for key, value in idf.iteritems(): idf[key] = len(comments) / (value + 1) result = [] for tf in temp: for key, value in tf.iteritems(): tf[key] = value * idf[key] result += (sorted(tf.items(), key=lambda d: d[1], reverse=True)[:3]) result = sorted(result, key=lambda d: d[1], reverse=True) result = [term[0] for term in result[:3]] return result # print extract_tags(comments)
adc818ff6f429531b325c8b1e4c4a70e4d2a4b39
djaychela/playground
/dna/tax_calc.py
939
3.640625
4
def calc_tax_due(amount, allowance_used): tax_amount = 0 lower_rate = 0.2 higher_rate = 0.4 additional_rate = 0.45 if amount < 11500 and not allowance_used: return 0 elif amount < 11500 and allowance_used: return amount * lower_rate elif amount >= 11500 and not allowance_used: amount -= 11500 else: tax_amount += (11500 * lower_rate) amount -= 11500 if amount > 33500: tax_amount += (33500 * lower_rate) amount -= 33500 else: tax_amount += (amount * lower_rate) return tax_amount if amount > 105000: tax_amount += (105000 * higher_rate) amount -= 105000 else: tax_amount += (amount * higher_rate) return tax_amount tax_amount += (amount * additional_rate) return tax_amount for i in range(0,700000, 10000): print(f"Value: {i}, after tax: {i- calc_tax_due(i, True)}")
263fed61f8c65bb8f0565e4419692b2a77ced64e
catherning/PRe_deap
/csv_splitter.py
2,489
3.5625
4
#from https://gist.github.com/jrivero/1085501 import os def split(action, delimiter=',', row_limit=10000, output_name_template='output_%s.csv', output_path='.', keep_headers=True): """ Splits a CSV file into multiple pieces. A quick bastardization of the Python CSV library. Arguments: `row_limit`: The number of rows you want in each output file. 10,000 by default. `output_name_template`: A %s-style template for the numbered output files. `output_path`: Where to stick the output files. `keep_headers`: Whether or not to print the headers in each output file. Example usage: >> from toolbox import csv_splitter; >> csv_splitter.split(open('/home/ben/input.csv', 'r')); """ import csv filehandler=open(path+action+'.csv','r') reader = csv.reader(filehandler, delimiter=delimiter) current_piece = 1 current_out_path = os.path.join( output_path, output_name_template % current_piece ) current_out_writer = csv.writer(open(current_out_path, 'w', newline=''), delimiter=delimiter) current_limit = row_limit if keep_headers: headers = reader.next() current_out_writer.writerow(headers) for i, row in enumerate(reader): if i + 1 > current_limit: current_piece += 1 current_limit = row_limit * current_piece current_out_path = os.path.join( output_path, output_name_template % current_piece ) current_out_writer = csv.writer(open(current_out_path, 'w', newline=''), delimiter=delimiter) if keep_headers: current_out_writer.writerow(headers) if action=='device' or action=='logon': current_out_writer.writerow(row[1:(len(row))]) elif action=='http': current_out_writer.writerow(row[1:4]+[row[5]]) else: current_out_writer.writerow(row[1:(len(row)-1)]) path='D:/r6.2/' list_actions=['device','file','logon','email','http'] #list_actions=['http'] #file=open(path+'http.csv') #for i,line in enumerate(file): # if i<3: # print(line) # else: # break for action in list_actions: file=path+action+'.csv' nb_row=50000 if action=='http': nb_row=400000 split(action,row_limit=nb_row,output_name_template=action+'_%s.csv',output_path=path+'splitted/',keep_headers=False)
07097e7867a7ba2ba51e0e8f02ec1cc3fb650add
utkarsh04apr/python
/python-coding-W3school/looping/7-for-else.py
153
3.8125
4
data = [1,3,5,7,9,11,21,13,15,17] for n in data: if n%2==0: print("even no is in data") break else: print("no even no is there")
bd3ce93a9907ef45c161d941cb50ee224a74c715
jinglongzou/Sword_Offer
/Sword_Offer/issue20.py
1,137
3.59375
4
# -*- coding:utf-8 -*- # 定义栈的数据结构,请在该类型中实现一个能够得到栈中 # 所含最小元素的min函数(时间复杂度应为O(1))。 # 考察栈的概念、建立、O(1)时间复杂度:则要求要么是顺序表存储,要么是单独一个变量 # 因此构建一个变量来存储最小值,并在,插入和删除时维护最小值 # 构建一个辅助栈来存储最小值,这样出入栈、返回最小值都是O(1);利用空间换取时间 class Solution: def __init__(self): self.s = [] self.s_ = [] def push(self, node): # write code here least = self.min() if not least or node < least: self.s_.append(node) self.s.append(node) def pop(self): if self.s: elem = self.s.pop() least = self.min() if elem == least: self.s_.pop() # write code here def top(self): if self.s: return self.s[-1] # write code here def min(self): if self.s_ != []: return self.s_[-1] # write code here
a83098ebae4ba14847dffb543170443c4dcc0ecc
aleblucher/An-lise-de-Treli-as-Planas
/inn.py
1,078
3.640625
4
def readMecSol(file_name): with open(file_name, "r") as arquivo: #read file file = arquivo.readlines() def is_number(s): #test if a string is a number try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False clean = [] tags = [] for i in file: if "*" in i: #search for block tags tags.append(file.index(i)) clean.append(i.strip()) #print(tags) cleaner = {} for i in range(len(tags)-1): #get block info for that tag cleaner[clean[tags[i]].replace("*", "")] = clean[tags[i]+1:tags[i+1]-1] for i in cleaner.keys(): #transform numbers from strings temp = [] for j in cleaner[i]: j = [float(x) if is_number(x) else x for x in j.split()] #list comprehensions magic temp.append(j) cleaner[i] = temp return cleaner
d6ff42b0aff7248b0bb3e3dcab9dd09ec5e524b8
zhaolijian/suanfa
/leetcode/sword_to_offer3.py
826
3.625
4
# 找出数组中重复的数字。 # 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。 # 方法1 原地操作 class Solution: def findRepeatNumber(self, nums) -> int: i = 0 while i < len(nums): if nums[i] == i: i += 1 continue if nums[nums[i]] == nums[i]: return nums[i] nums[nums[i]], nums[i] = nums[i], nums[nums[i]] # 方法2 哈希表 class Solution: def findRepeatNumber(self, nums) -> int: s = set() for ele in nums: if ele in s: return ele s.add(ele)
0e891b3314e45a3736d95659400dce657f014eb6
jvano74/advent_of_code
/2015/day_08_test.py
3,435
4.3125
4
import re class Puzzle: """ --- Day 8: Matchsticks --- Space on the sleigh is limited this year, and so Santa will be bringing his list as a digital copy. He needs to know how much space it will take up when stored. It is common in many programming languages to provide a way to escape special characters in strings. For example, C, JavaScript, Perl, Python, and even PHP handle special characters in very similar ways. However, it is important to realize the difference between the number of characters in the code representation of the string literal and the number of characters in the in-memory string itself. For example: "" is 2 characters of code (the two double quotes), but the string contains zero characters. "abc" is 5 characters of code, but 3 characters in the string data. "aaa\"aaa" is 10 characters of code, but the string itself contains six "a" characters and a single, escaped quote character, for a total of 7 characters in the string data. "\x27" is 6 characters of code, but the string itself contains just one - an apostrophe ('), escaped using hexadecimal notation. Santa's list is a file that contains many double-quoted string literals, one on each line. The only escape sequences used are \\ (which represents a single backslash), \" (which represents a lone double-quote character), and \xFF where FF are any two hexadecimal characters (which represents a single character with that ASCII code). Disregarding the whitespace in the file, what is the number of characters of code for string literals minus the number of characters in memory for the values of the strings in total for the entire file? For example, given the four strings above, the total number of characters of string code (2 + 5 + 10 + 6 = 23) minus the total number of characters in memory for string values (0 + 3 + 7 + 1 = 11) is 23 - 11 = 12. """ pass def length(escaped_string): if escaped_string[0] != '"' or escaped_string[-1] != '"': raise SyntaxError(f"Invalid string {escaped_string}") escaped_string = escaped_string[1:-1] escape_mode = False hex_depth = 0 total = 0 for c in escaped_string: if hex_depth > 0: hex_depth -= 1 continue if escape_mode: escape_mode = False if c == "x": hex_depth = 2 continue if c == "\\": continue if c == '"': continue raise SyntaxError(f"Invalid escape {c}") if c == "\\": escape_mode = True total += 1 return total def test_length(): assert length(r'"hello"') == 5 assert length(r'"\\g"') == 2 assert length(r'"\\\\g"') == 3 assert length(r'"v\xfb\"lgs\"kvjfywmut\x9cr"') == 18 assert length(r'"porvg\x62qghorthnc\"\\"') == 17 def test_submission(): file_total = 0 mem_total = 0 extra = 0 with open("./input_day_8.txt", "r") as fp: line = fp.readline().rstrip() while line: file_total += len(line) extra += 2 + line.count("\\") + line.count('"') calc = length(line) mem_total += calc line = fp.readline().rstrip() assert (file_total - mem_total) == 1342 assert extra == 2074
6e4e9688f2c6cecad539820f70cfffdef574364c
iCoder0020/Competitive-Coding
/CodeChef/Python/FCTRL2.py
240
3.59375
4
#ID: ishan_sang #PROG: FCTRL2 #LANG: Python def fact(n): ans=1 for n in range(n,1,-1): ans*=n return ans t=int(input()) for t in range(t,0,-1): n=int(input()) print(fact(n),"\n")
db97b01da5544db0f3d3658a752e562734118a9a
cpp337323012/PycharmProjects
/DataTestPG/Python_Base/part01/my_reg.py
507
3.640625
4
''' 2019年12月11日22:58:14 11位手机号码匹配: 移动: 139 138 137 136 135 134 150 151 152 157 158 159 联通: 130 131 132 185 186 145 电信: 133 153 180 199 ''' import re def checkCellphone(cellphone): reqex = '^(13[0-9]|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$' result = re.findall(reqex,cellphone) if result: print('成功') return True else: print('失败') return False cellphone = '13301473825' print(checkCellphone(cellphone))
9396f066893e4ae52cf2e00832722c7d22445cb0
ChiShengChen/2018makeNTU_meowmeow
/gesture-keyboard-master/suggestions.py
2,438
3.703125
4
import os ''' Author: Federico Terzi This library contains the classes needed to manipulate words and obtain suggestions This is a work in progress.... ''' class Hinter: ''' Hinter is used to load a dictionary and obtain some suggestions regarding the next possible letters or compatible words. ''' def __init__(self, words): self.words = words @staticmethod def load_english_dict(): ''' Loads the english dictionary and returns a Hinter object with the words loaded into the self.words list ''' ENGLISH_FILENAME = "dict" + os.sep + "english.txt" words = [i.replace("\n","") for i in open(ENGLISH_FILENAME)] return Hinter(words) def compatible_words(self, word, limit = 10): ''' Returns the words that starts with the "word" parameter. The "limit" parameter defines how many words the function returns at maximum ''' output = [] word_count = 0 #Cycle through all the words to find the ones that starts with "word" for i in self.words: if i.startswith(word): output.append(i) word_count+=1 if word_count>=limit: #If limit is reached, exit break return output def next_letters(self, word): ''' Returns a list of compatible letters. A letter is compatible when there are words that starts with "word" and are followed by the letter. ''' #Get 100 compatible words words = self.compatible_words(word, 100) letters = [] #Cycle through all the compatible words for i in words: if len(i)>len(word): #if the "word" is longer than a compatible word, skip letter = i[len(word):len(word)+1] #Get the following letter if not letter in letters: #Avoid duplicates letters.append(letter) return letters def does_word_exists(self, word): ''' Check if a specific word exists in the loaded dictionary ''' if word in self.words: return True else: return False def most_probable_letter(self, clf, classes, linearized_sample, word): ''' Get the most probable letter for a given recorded sign and the current word ''' if word=="": return None probabilities = clf.predict_log_proba(linearized_sample) ordered = sorted(classes) values = {} for i in xrange(len(probabilities[0])): values[round(probabilities[0,i], 5)] = classes[ordered[i]] ordered = sorted(values, reverse=True) possible_letters = self.next_letters(word) for i in ordered: if values[i] in possible_letters: return values[i] return None
e2dfb63f574b39e04f078332e45a9a23d7efade9
Jungeol/algorithm
/leetcode/easy/202_happy_number/django.py
680
3.546875
4
""" https://leetcode.com/problems/happy-number/ Runtime: 32 ms, faster than 66.18% of Python3 online submissions for Happy Number. Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Happy Number. """ class Solution: def __init__(self): self.numbers = [] def isHappy(self, n: int) -> bool: words = list(str(n)) sumVal = 0 for word in words: sumVal += int(word) ** 2 if sumVal == 1: return True elif sumVal not in self.numbers: self.numbers.append(sumVal) return self.isHappy(sumVal) elif sumVal in self.numbers: return False
f98f5bf9e75576272321876f87a4474ef0b554d2
Wictor-dev/ifpi-ads-algoritmos2020
/iteração/22_boi_magro_e_gordo.py
1,087
3.921875
4
def main(): n = int(input('N: ')) print('### Boi 1 ###') n_iden = int(input('Digite o número de identificação')) nome = input('DIgite o nome do boi: ') peso = float(input('Digite o peso do boi: ')) n_iden_menor = n_iden nome_menor = nome peso_menor = peso count = 2 while (n - 1) > 0: print(f'### boi {count} ###') iden = int(input('Digite o numero de identificação: ')) boi_name = input('Digite o nome do boi: ') boi_peso = float(input('Digite o peso do boi:(KG) ')) if(boi_peso > peso): peso = boi_peso nome = boi_name n_iden = iden if(boi_peso < peso_menor): peso_menor = boi_peso nome_menor = boi_name n_iden_menor = iden count +=1 n -= 1 print(f'O boi mais gordo é o {nome} com {peso} quilos, Nº de identificação ({n_iden})') print(f'O boi mais magro é o {nome_menor} com {peso_menor} quilos, Nº de identificação ({n_iden_menor})') main()
a1c058ec923cd9351a6da054dfc25ce9a5eb8de8
jonhoward42/python101
/fundamentals/5.if_statements.py
540
4.40625
4
#!/usr/bin/env python variable = 15 ## Basic IF statement if variable < 10: # <- Note the ":" symbol print("Less than 10!") ## Else IF (elif) if variable > 16: # <- Greater than print("Greater that 16") elif variable < 10: # <- Less than print("Less than 10") elif variable == 15: # <- Equal to print("Number is 15") elif variable != 14: # <- Not equal to print("Definitely not 14!") ## Else temperature = 35 if temperature > 25: print("Time to put your shorts on") else: print("It's not greater than 25C, best wear trousers")
055577212d1fa5abd936ea7979f595d528f357a1
Manju321/FinalCode
/9_Code.py
1,402
4
4
"""Using Python 3.6 Ans for 9th Program : Write a Selenium script that fills the form www.practiceselenium.com/practice-form.html and submits the page. After submitting , verify that the page navigates to home page """ import os from selenium import webdriver from selenium.webdriver.support.ui import Select chromedriver_path = './chromedriver' # assuming chromedriver binary is in current directory os.environ['webdriver.chrome.driver'] = chromedriver_path driver = webdriver.Chrome(chromedriver_path) url = 'http://www.practiceselenium.com/practice-form.html' driver.get(url) driver.find_element_by_name('firstname').send_keys('Manju') driver.find_element_by_name('lastname').send_keys('Bhargavi') driver.find_element_by_id('sex-1').click() driver.find_element_by_id('exp-2').click() driver.find_element_by_id('datepicker').send_keys('01/11/2017') driver.find_element_by_id('tea1').click() driver.find_element_by_id('tool-0').click() driver.find_element_by_id('tool-2').click() select_elem = Select(driver.find_element_by_id('continents')) select_elem.select_by_visible_text('Asia') select_elem = Select(driver.find_element_by_id('selenium_commands')) select_elem.select_by_visible_text('Browser Commands') select_elem.select_by_visible_text('Wait Commands') driver.find_element_by_id('submit').click() assert driver.title == 'Welcome' driver.quit()
80b065ffc31b3e5dbb3df1524457106449c51062
soundzues/Python-Practice
/arr_sum.py
378
3.921875
4
#sum array from functools import reduce #initialize arr: arr = [] #take number of input from user num = int(input("please enter the number of elements you want to enter: ")) #range #take inputs from the user for i in range(num): x = int(input()) arr.append(x) #test print all var i#print(*arr) #sum all array elements: total = reduce(lambda x,y: x+y, arr) print(total)
bb00be8e0a70b596b740a3399c26be1c2e74b5db
clovery410/mycode
/Algorithm2/coin_change_greedy.py
1,961
3.6875
4
optimal = {} def greedy_change(total, choice): if total == 0: return # import pdb # pdb.set_trace() if total / choice[0] > 0: print('%s ' % choice[0]) return greedy_change(total - choice[0], choice) elif total / choice[1] > 0: print('%s ' % choice[1]) return greedy_change(total - choice[1], choice) else: print('%s ' % choice[2]) return greedy_change(total - choice[2], choice) best_solution = list() def dp_change(total, choice): if total <= 0: return 0 if total / choice[0] <= 0: return dp_change(total, choice[1:]) elif (len(choice) > 1): count_withFirst = dp_change(total - choice[0], choice) + 1 count_withoutFirst = dp_change(total, choice[1:]) if count_withFirst <= count_withoutFirst: return count_withFirst else: return count_withoutFirst if (len(choice) == 1): count = 1 + dp_change(total - choice[0], choice) return count c = {} def new_dp_change(total, choices): min_count = 9999 if total == 0: return 0 for coin in choices: if total < coin: continue else: count = new_dp_change(total - coin, choices) if count < min_count: min_count = count c[total] = coin return min_count + 1 if __name__ == '__main__': # total_money = 8 choice = [7, 6, 5, 4, 1] for total_money in range(1, 1000): print total_money if dp_change(total_money, choice) != new_dp_change(total_money, choice): print('value %s is different' % i) # greedy_change(total_money, choice) # num = dp_change(total_money, choice) # num = new_dp_change(total_money, choice) # print(num) # print(c) # while total_money > 0: # print(c[total_money]) # total_money = total_money - c[total_money]
086f4e6cac6f8b99f6e309254f77024ae7404691
LTUC/amman-python-401d4
/class-16/code_review/binary-tree/binary_tree/binary_search_tree.py
1,096
4.0625
4
from binary_tree.binary_tree import BinaryTree, Node # See you at 11:11 class BinarySearchTree(BinaryTree): def add(self, value): if not self.root: self.root = Node(value) return def _traverse(node, value): # O(log n) # if no root, add to the root # if value <= root.value add to the left # if value > root.value add to the right if value <= node.value: if not node.left: node.left = Node(value) return else: _traverse(node.left, value) else: if not node.right: node.right = Node(value) return else: _traverse(node.right, value) _traverse(self.root, value) def contains(self): pass if __name__=='__main__': bst = BinarySearchTree() bst.root = Node(15) assert bst.root.value == 15 print("All passed fine!!!") """ 26 26 26 """
272f85e353bc1fb0d8644dab4920dd9006f10893
lindo-zy/leetcode
/双指针/395.py
496
3.90625
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- class Solution: def longestSubstring(self, s: str, k: int) -> int: if len(s) < k: return 0 for c in set(s): if s.count(c) < k: return max(self.longestSubstring(t, k) for t in s.split(c)) return len(s) if __name__ == '__main__': sn = Solution() # s = "aaabb" # k = 3 s = "bbaaacbd" k = 3 # 3 # s = "ababbc" # k = 2 print(sn.longestSubstring(s, k))
bf4692216001d3a8f4f650dc22f909cd183e994c
superkuang1997/DataStructure-Python
/recursion/fractalTree.py
561
3.515625
4
import turtle def tree(branch_len): if branch_len > 25: t.forward(branch_len) t.right(45) tree(branch_len - 50) t.left(90) tree(branch_len - 50) t.right(67.5) tree(branch_len - 50) t.left(45) tree(branch_len - 50) t.right(22.5) tree(branch_len - 50) t.backward(branch_len) t = turtle.Turtle() t.speed(0) t.pensize(2) t.pencolor('green') t.left(90) t.penup() t.backward(120) t.pendown() # 到达预定位置 tree(180) turtle.done()
971c2e9b5e124029bbdb8b539036694835bf628d
ketkarmayank/Algorithms
/segment.py
2,674
4.1875
4
"""Learning how to work with Segment Trees. Also learning how to work with Docstrings """ class Node(object): """This will act as Node element Args: start_idx(int): Suggests where the range starts end_idx(int): Suggests where the range ends value(int): Stores sum till this point left(Node): Stores reference to left child right(Node): Stores reference to right child """ def __init__(self, start_idx=None, end_idx=None, value=None, left=None, right=None): self.start_idx = start_idx self.end_idx = end_idx self.value = value self.left = left self.right = right class SegmentTree(object): """Segment tree implementation to learn why ranges work better Args: None """ def __init__(self): self.root = None def populate(self, input_array=None): """Populates the tree with sum of range elements Args: input_array(int[]): input of array of elements Returns: None """ if input is None: raise Exception('Null input array') self.root = self.populate_node_helper(input_array, 0, len(input_array) - 1) def populate_node_helper(self, arr, start_idx, end_idx): """Helper to populate the segment tree Args: arr(int[]): Array to be converted to segment tree start_idx(int): Suggests where the range starts end_idx(int): Suggests where the range ends Returns: Node that is to be attached """ if start_idx == end_idx: return Node(None, None, arr[start_idx], None, None) mid = (end_idx + start_idx) // 2 left_child = self.populate_node_helper(arr, start_idx, mid) right_child = self.populate_node_helper(arr, mid+1, end_idx) value = left_child.value + right_child.value return Node(start_idx, end_idx, value, left_child, right_child) def printAll(self, node=None): """Print all nodes with start index and end index + sum Args: node(Node): node for the tree Returns: None """ if node is None: node = self.root print( ' series: ' + str(node.value) + ' start_index: ' + str(node.start_idx) + ' end_index: ' + str(node.end_idx) ) if node.left is not None: self.printAll(node.left) if node.right is not None: self.printAll(node.right) INPUT = [1, 3, 5, 6, 7] TREE = SegmentTree() TREE.populate(INPUT) TREE.printAll()
ebc1a2f78e19ffe82d1e6fe069ef1ee2e8e5b935
SouravDebnath09/AutomateBoringStuff_Pickki
/www.py
798
3.984375
4
#Hotel_Cost Function Start def hotel_cost(nights): return 140*nights #Hotel_Cost Function Ends #Plane_Ride_Cost Function Starts def plane_ride_cost(city): if city=="Charlotte": return 183 elif city=="Tampa": return 220 elif city=="Pittsburgh": return 222 elif city=="Los Angeles": return 475 #Plane_Ride_Cost Function Ends\ #Return_car_cost Function Starts def rental_car_cost(days): if days>=7: return (days*40)-50 elif days>=3: return (days*40)-20 else: return (days*40) #Return_car_cost Function Ends #trip_Cost Function Starts def trip_cost(city,days,spending_money): return "to "+ city+" for "+str(days)+" days with an extra "+str(spending_money)+" dollars of spending money" #trip_Cost Function Ends print trip_cost("Los Angeles",5,1955)
127988d509c3e89034416c123c2cd16d8d708fc1
sridivyapemmaka/PhythonTasks
/AllStringMethods1.py
711
4.28125
4
#capitalize() (converts the first charecter to upper case_ a="sridivya" b=a.capitalize() print(b) #case fold() (converts string into lower case) a="DIVYA" b=a.capitalize() print(b) #center() (returns center string) a="sridivya" b=a.center(12) print(b) #count() (return num of times specified value in a string) a="sridivya" b=a.count("s") print(b) #encode (returns encoded version of the string,returns binary value on a string) a="hello" b=a.encode() print(b) #end swith a="divya" b=a.endswith("d") print(b) #expandtabs a="D/ti/tv/ty/ta" b=a.expandtabs(5) print(b) #find a="divya" b=a.find("d") print(b) #index a="divya" b=a.index("v") print(b)
b9bb6ab35f6d5da6ef4cfcc669636cbe79b7cff0
Shad0wpf/python_study
/12_file.py
996
3.5625
4
#coding=utf-8 # 写通讯录 # f = open('D:\\Code\\Python\contact.txt','w') # f.write('姓名'+'\t性别'+'\t电话'+'\t\t地址'+'\n') flag = 'Y' # while flag.lower() == 'y' or flag == '': # name = input('请输入姓名:') # sex = input('请输入性别:') # phone = input('请输入电话号码:') # address = input('请输入联系地址:') # s = name + '\t' + sex + '\t' + phone + '\t' + address + '\n' # f.write(s) # flag = input('是否继续输入?(Y/n)') # f.close() # 读通讯录 # f = open('D:\Code\Python\contact.txt','r') # while True: # line = f.readline() # if line == '': # break # print(line) # f.close() # 写文件、然后读取文件长度 # s = 'a1@中国\n' # f = open('D:\\Code\\Python\\12_test.txt','w') # f.write(s) # f.seek(0,2) # length = f.tell() # print(length) # 读取文件5个字节 f = open('D:\Code\Python\contact.txt','r') text = f.read(5) print(text) print(len(text)) f.close()
01f36d2467ddeedb37a999676eea3024deacdb17
klm127/rpio-cli-state-machine
/src/Game/GameObject.py
4,361
4.03125
4
""" A Game object. Holds x and y positions """ class GameObject: """ A game object holding position and size info. x,y are top left coordinates for variable size object :param x: the x coordinates on the game map :type x: int :param y: the y coordinates on the game map :type y: int :param width: the width :type width: int """ def __init__(self, x, y, width=1): self.x = x self.y = y self.width = width def up(self, num=1): """ Decreases self.y Should only be called by Map object once move is determined valid, not used directly. :param num: y to decrease :type num: int """ self.y -= num def down(self, num=1): """ Increases self.y Should only be called by Map object once move is determined valid, not used directly. :param num: y to increase :type num: int """ self.y += num def left(self, num=1): """ Decreases self.x Should only be called by Map object once move is determined valid, not used directly. :param num: x to decrease :type num: int """ self.x -= num def right(self, num=1): """ Increases self.x Should only be called by Map object once move is determined valid, not used directly. :param num: x to increase :type num: int """ self.x += num def place(self, display): """ Should be overwritten by extending classes Places an appropriate character at an appropriate location on the display. :param display: Object holding characters to be displayed :type display: src.Game.Map.Display """ pass def update(self, state, interval): """ Will be called by a map or display object to update the display character if needed Only relevant for animated objects To be overwritten by extending classes :param state: A state holding info about what to display :type state: extends class src.Game.Map.GameStates.Game :param interval: The time since the last update :type interval: float """ pass class VisibleObject(GameObject): """ An object visible on the display screen :param width: The width of the object :type width: int :param text: The string to display width characters from left :type text: str :param x: the x coordinate of object :type x: int :param y: the y coordinate of object :type y: int """ def __init__(self, x, y, width=1, text=','): GameObject.__init__(self, x, y, width) self.text = text def place(self, display): """ Sets characters on display to correspond with this object :param display: Object holding characters to be displayed :type display: src.Game.Map.Display """ for i in range(0, self.width): if i < len(self.text): display.change(self.y, self.x + i, self.text[i]) class AnimatedObject(VisibleObject): """ Extends visible object with a method to change visible character Parent class, not to be used directly. :param x: the x-coordinate :type x: int :param y: the y-coordinate :type y: int :param interval: interval between animation changes :type interval: float """ def __init__(self, x, y, width, interval, string=','): VisibleObject.__init__(self, x, y, width, string) self.interval = interval self.time_since_last = 0 def update(self, state, interval): """ Checks if the interval calls for a change in this object :param state: state where object exists :type state: class GameState :param interval: time elapsed :type interval: float """ self.place(state.display) self.time_since_last += interval change_amount = int(self.time_since_last / self.interval) self.time_since_last -= self.interval * change_amount self.change(state, change_amount) def change(self, state, amount): """ Method to be overwritten. Changes the object in some way if the interval has passed. """ pass
9fd41262847ca60446ef24771c3ab225ec66721f
bengori/python
/homeworks/les1/task4.py
768
4.28125
4
""" Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. """ while True: number = input('Введите целое положительное число (n):\n >>> ') if int(number) <= 0: print('Надо ввести целое положительное число!') else: number = list(number) max_number = number[0] for number in number: if number > max_number: max_number = number print(f'Максимальная цифра в числе - {max_number}') break
0902604ed9152a0e1092b54680a2ec0d0bf01788
int-invest/Lesson3
/DZ6.py
855
3.921875
4
'''Задача 6 ''' ord_a = ord('a') ord_z = ord('z') ord_sp = ord(' ') def int_func(var_1): for el in var_1: org_el = ord(el) if org_el > ord_z or org_el < ord_a: return '' return var_1.title() var_1 = input('Введите слово маленькими латинскими буквами\n') print(int_func(var_1)) '''Задача 7 ''' def str_func(var_1): list_var = var_1.split(' ') result = [] for el in list_var: el_t = int_func(el) if len(el_t) == 0: return False result.append(el_t) print(' '.join(result)) return True while True: var_1 = input('Введите слова маленькими латинскими буквами разделенные пробелом\n') if not str_func(var_1): break print(str_func(var_1))
38c59fa0508f3d4e4d87a8a2a5d9bd3ac62b5b8a
taoddiao/introduction_to_algorithm
/quick_sort.py
335
3.5
4
def quick_sort(a, p, r): if p < r: q = partition(a, p, r) quick_sort(a, p, q - 1) quick_sort(a, q + 1, r) def partition(a, p, r): x = a[r] i = p for j in range(p, r): if x > a[j]: m = a[i] a[i] = a[j] a[j] = m i += 1 a[r] = a[i] a[i] = x return i a = [9,2,8,7,1,3,9] quick_sort(a, 0, len(a) - 1) print(a)
06a949a6edb6465592ecc6a4f5679fe0ec2ba732
dadnotorc/orgrammar
/leetcode/双指针/0023_Merge_k_Sorted_Lists/Solution.py
1,224
3.78125
4
class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if not lists: return None if len(lists) == 1: return lists[0] mid = len(lists) // 2 # 注意是 两条 / l1, l2 = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:]) return self.merge(l1, l2) # 变成简单地 merge two sorted list def merge(self, l1, l2): dummy = p = ListNode(-1) while l1 and l2: if l1.val < l2.val: p.next = l1 l1 = l1.next else: p.next = l2 l2 = l2.next p = p.next p.next = l1 or l2 return dummy.next # 另一种 recursion 的 merge 解法 def merge_recursion(self, l1, l2): if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = self.merge_recursion(l1.next, l2) return l1 l2.next = self.merge(l1, l2.next) return l2 class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next
7103714dbac529832a8654b37370501ba2ab016d
xiaoniuv/python_demo
/45.py
2,069
3.84375
4
# def __setattr__(self,name,value): # self.__dict__[name] = value + 1 # def __setattr__(self,name,value): # super().__setattr__ = value + 1 # class C: # def __getattr__(self, name): # print(1) # def __getattribute__(self,name): # print(2) # def __setattr__(self, name, value): # print(3) # def __delattr__(self, name): # print(4) # c = C() # c.x = 1 # print(c.x) # class C: # def __getattr__(self,name): # print(1) # return super().__getattr__(name) # def __getattribute__(self, name): # print(2) # return super().__getattribute__(name) # def __setattr__(self, name, value): # print(3) # super().__setattr__(name, value) # def __delattr__(self, name): # print(4) # super().__delattr__(name) # c = C() # c.x # class Counter: # def __init__(self): # self.counter = 0 #这里会触发__setattr__ # def __setattr__(self,name,value): # self.counter += 1 #既然需要__setattr__调用后才能真正设置self.counter的值,所以这时候self.counter 还没有定义,所以没法 += 1,错误的根源 # super.__setattr__(name,value) # def __delattr__(self, name): # self.counter -= 1 # super().__delattr__(name) # class Demo: # def __getattr__(self,name): # return "该属性不存在!" # demo = Demo() # print(demo.c) # class Demo: # def __getattr__(self,name): # self.name = "FishC" # return self.name # demo = Demo() # print(demo.x) # demo.x = "X-man" # print(demo.x) class Counter: def __init__(self): super().__setattr__('counter',0) def __setattr__(self,name,value): super().__setattr__('counter', self.counter + 1) super().__setattr__(name,value) def __delattr__(self, name): super().__setattr__('counter', self.counter - 1) super().__delattr__(name) c = Counter() c.x = 1 print(c.counter) c.y = 1 c.z = 1 print(c.counter) del c.x print(c.counter)
baf6958a8aef54fe3f94a73b42b0122bf93eab74
tuanderful/project-euler
/012.py
2,675
3.515625
4
# Highly divisible triangular number # Problem 12 # The sequence of triangle numbers is generated by adding the natural numbers. # So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first # ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: 1,2,5,10 # 15: 1,3,5,15 # 21: 1,3,7,21 # 28: 1,2,4,7,14,28 # We can see that 28 is the first triangle number to have over five divisors. # What is the value of the first triangle number to have over five hundred divisors? # Answer: # 76576500 TRIANGLES = [0, 1] # ------------------------------------------------------------------------------ def getPrimeFactors(n): # loop from 2 to n/2 (i) # if n % i == 0, then set n to n/i i = 2 factors = [] while i <= n: # if i is a factor, it must be prime, since we've checked (and divided out) all factors less than i if (n % i == 0): n = n / i factors.append(i) else: # Can we optimize this by incrementing by 2? i += 1 return factors # ------------------------------------------------------------------------------ def countDivisors(n): # Consider prime factorization: # n = a^p + b^q + ... + c^r # only check up to c where c = sqrt(n) # Then n has z factors, where z = (p+1) * (q+1) * (r+1) z = 1 primeFactors = getPrimeFactors(n) uniqueFactors = set(primeFactors) for i in uniqueFactors: # count how many times it appears occurences = primeFactors.count(i) z = z * (occurences+1) # print primeFactors # print uniqueFactors return z # ------------------------------------------------------------------------------ def triangle(n): # If we already have a value calculated if n < len(TRIANGLES): return TRIANGLES[n] # If not already calculated, then calc and return # First, check if the immediately previous triangle has been calc. if (n-1) < len(TRIANGLES): lastTriangle = TRIANGLES[n-1] else: lastTriangle = triangle(n-1) thisTriangle = n + lastTriangle TRIANGLES.append(thisTriangle) return thisTriangle; # ------------------------------------------------------------------------------ def problem_012(): answerFound = False i = 1 while answerFound != True: thisTriangle = triangle(i) divisors = countDivisors(thisTriangle) if (divisors > 500): print `i` + ": " + `thisTriangle` + " has " + `divisors` + " divisors." answerFound = True else: i += 1 # ------------------------------------------------------------------------------ # Execute standalone problem_012()
cc61475f585ac8ba23fd3f0792435d6d3170c59d
cryogenic-dreams/PythonFunFolder
/Basic/vulcano.py
284
3.875
4
def vulcano(row): """ This program makes a vulcano with the rows you want. But, since row = 8, you will need a bigger screen to see the vulcano." """ n = 1 while n < 2 ** row: print (((2 ** row) / 2) - n) * " " + "**" * n n = n * 2
1101a765d36e0b21a0af05624782d8879b2892bf
nanareyes/CicloUno-Python
/Ciclo For/ejercicio2_for.py
250
3.671875
4
# 2. Leer 5 personas y pedir salario. Imprimir sumatoria de salario. suma_salario = 0 for i in range(5): salario = int(input("Ingrese el salario: ")) suma_salario = suma_salario + salario print("La suma de los salarios es: ", suma_salario)
d463b083ab5a6c82adc569af0c911ce937cf0863
Samk208/Udacity-Data-Analyst-Python
/Lesson_3_data_structures_loops/top_three.py
611
4.5
4
# Write a function, top_three, that takes a list as its argument, and returns a list of the three largest elements. # For example, top_three([2,3,5,6,8,4,2,1]) == [8, 6, 5] def top_three(input_list): """ :param input_list: list :return: Returns a list of the three largest elements input_list in order from largest to smallest. If input_list has fewer than three elements, return input_list element sorted largest to smallest/ """ # TODO: implement this function sorted_list = sorted(input_list, reverse=True) return sorted_list[:3] print(top_three([2, 3, 5, 6, 8, 4, 2, 1]))
dc15a7bcfccd5bee2c09ffa611a4eef90b4be485
Souriish/Bubble-Sort-Using-Python
/arrays bubbleSort.py
321
4.25
4
def bubbleSort(arr): o=len(arr) for i in range (o-1): for j in range (0, o-i-1): if arr[j]<arr[j+1]: arr[j], arr[j+1]= arr[j+1], arr[j] arr=[9,1,2,7,5,8,6,4,0] bubbleSort(arr) print("Array in descending order:") for i in range (len(arr)): print (arr[i])
230732936e0454d328fb11b227d11e652fdbc5ba
codevr7/samples
/LCM.py
363
3.8125
4
# LCM def lcm(n,m):# Defining a function for LCM and its inputs inp_1 = []# 2 empty lists inp_2 = [] if n < m: larger = m small = n else: larger = n small = m for i in range(1,11): val = larger*i val_1 = small*i inp_1.append(val_1) inp_2.append(val) return inp_1,inp_2
1de71dd4a3ec7e117b84c6ad0f3d755e080a7057
sigurjono18/daemaverkefni2
/Lausn.py
1,448
4.125
4
#Exercise no. 44 in chapter 4 in the textbook. #You should output the result in a table, formatted in the following manner: #The first line contains the word "Upper case", right justified, 15 spaces wide, followed by the count of upper case characters, right justified, 5 spaces wide. #The second line contains the word "Lower case", right justified, 15 spaces wide, followed by the count of lower case characters, right justified, 5 spaces wide. #The third line contains the word "Digits", right justified, 15 spaces wide, followed by the count of digits, right justified, 5 spaces wide. #The fourth line contains the word "Punctuation", right justified, 15 spaces wide, followed by the count of punctuation characters, right justified, 5 spaces wide. #The input prompt should be: "Enter a sentence. " #Example input/output: import string sentence = input("Enter a sentence: ") U = 0 L = 0 D = 0 P = 0 lengd = len(sentence) for i in range(lengd): if sentence[i].isupper(): U += 1 if sentence[i].islower(): L += 1 if sentence[i].isnumeric(): D += 1 if sentence[i].isspace(): #if i in sentence.punctuation: P += 1 R = lengd - U - L - D - P upper = "Upper case" lower = "Lower case" digits = "Digits" punct = "Punctuations" import math print("{:>15}{:>5}".format(upper,U)) print("{:>15}{:>5}".format(lower,L)) print("{:>15}{:>5}".format(digits,D)) print("{:>15}{:>5}".format(punct,R))
44d2eb543f7ae62e20666e84073d281ba812c3ca
jradd/pycookbook
/ch1/cookbook1_17.py
637
4.125
4
'1.7 Extracting a Subset of a dictionary' '''Problems You want to make a dictionary that is a subset of another dictionary. ''' prices = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } # Make a dictionary of all prices over 200 p1 = { key:value for key, value in prices.items() if value > 200 } print (p1) # Make a dictionary of tech stocks tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'} p2 = {key:value for key, value in prices.items() if key in tech_names} print(p2) p1 = dict((key, value) for key, value in prices.items() if value > 200) print(p1) #> it's kinda like dict comprehension
d792bbac99a4649247ffb673779199ff06e3fddc
paweldrzal/python_codecademy
/flat_list.py
239
4.0625
4
#flattening a list n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] def flatten(lists): results = [] for li in lists: for m in li: results.append(m) return results print flatten(n) #output [1, 2, 3, 4, 5, 6, 7, 8, 9]
2018cbe1902f22a10d56c2d1aca7989f497b8721
scidam/algos
/algorithms/intervieweing.io/minsumsubarr.py
473
3.5625
4
# Find subarray of a given size and having minimum sum of elements arr = [1,4,2,6,7,3,1,2,2,3] size = 3 def find_min(arr, size=size): ss = sum(arr[:size]) i = 0 j = size - 1 mem = (i, j) while j < len(arr) - 1: j += 1 i += 1 probe = ss - arr[i - 1] + arr[j] print(ss, probe, i, j, arr[i - 1], arr[j]) if probe < ss: mem = (i, j) return (*mem, sum(arr[mem[0]:mem[1] + 1])) print(find_min(arr))
caf4387424151c18fb3021f668e7af3b9939c259
muyisanshuiliang/python
/function/InheritDemo.py
2,414
4
4
from types import MethodType class People(object): def run(self): print("我是父类的方法") # 子类如果有该方法,则调用子类方法,没有则直接调用父类方法 class Student(People): def run(self): print("我是一个学生") class Worker(People): name = "张三" def eat(self): print("工人需要吃肉") def run_twice(people): people.run() people.run() student = Student() student.run() worker = Worker() worker.run() run_twice(student) run_twice(worker) # 判断一个变量是否是某个类型可以用isinstance()判断: if isinstance(student, Student): print("student 是学生") else: print("student不是学生") if isinstance(worker, People): print("worker 是人") else: print("worker 不是人") # 获取一个数据的类型 print("student的类型 %s" % (type(student))) print(type(Student)) print("类的属性:%s" % Worker.name) print("实例的属性:%s" % worker.name) # 修改的是类属性值 Worker.name = "李四" print("类的属性:%s" % Worker.name) print("实例的属性:%s" % worker.name) # 修改的是实例属性值 worker.name = "王五" print("类的属性:%s" % Worker.name) print("实例的属性:%s" % worker.name) print("============实例绑定方法================") # 为实例绑定方法,self参数不可缺少 def print_work_instance(self, workName): print("我是一个 %s 工人" % workName) worker.print_work = MethodType(print_work_instance, worker) worker.print_work("木匠") print("==========类的属性和方法绑定方式============") # 为类例绑定方法,self参数不可缺少 def print_work_class_first(self): print("我是类的第一种绑定方法") def print_work_class_second(self): print("我是类的第二种绑定方法") # 第一种方式 Worker.print_work_class_first = MethodType(print_work_class_first, Worker) newWork = Worker() newWork.print_work_class_first() # 第一种方式 Worker.print_work_class_second = print_work_class_second anotherWorker = Worker() anotherWorker.print_work_class_second() print("========限制类属性的名称==========") class Animal(object): # 限制只能对name、age进行修改 __slots__ = ('name', 'age') pass dog = Animal() dog.name = "张川西" dog.age = 100 print("我家小狗的名字是%s,年龄是%s" % (dog.name, dog.age))
19fd3260b6d4cde4dfb65546177e8dfb895d2856
satishhirugadge/BOOTCAMP_DAY11-12
/Task3_Question3.py
493
4.28125
4
# 3. Write a program to get the sum and multiply of all the items in a given list. list=[1,2,3,4,5] # we have to perform the sum and multiple of this all number. def sum(): result=0 # here we stareted with 0 be cause e want to add it for i in list: result+=i print(result) sum() #Multiplication. list1=[1,2,3,4,5] def mul(): result=1 # if we put 0 then anything multiply by 0 will give 0 for j in list1: result*=j print(result) mul()
70a0950ce287f2523f20a5cad1f4e6006a53a669
manesioz/hill-cipher
/Hill Cipher - Encryption .py
1,317
4.0625
4
''' A simple implementation of a Hill Cipher, which is a polygraphic substitution cipher which uses linear algebra ''' import random import math import numpy as np #make encryption matrix X = np.random.randint(1, 26, size=(2, 2)) def det_checker(A): if ((np.linalg.det(A))%2 != 0) or ((np.linalg.det(A))%13 != 0): return A else: A = np.random.randint(1, 26, size=(2, 4)) det_checker(A) det_checker(X) #prepare the string for computation N = 2 unencrypted_msg = str(input("Enter the message you would like to encrypt: ")) unencrypted_msg = unencrypted_msg.replace(" ", "") if len(unencrypted_msg)%2 != 0: unencrypted_msg = unencrypted_msg + unencrypted_msg[-1] num_list = [ord(char) - 96 for char in unencrypted_msg] num_vector = [num_list[i:i+N] for i in range(0, len(num_list), N)] encrypted_list = [] for j in range(len(num_vector)): encrypted_list.append(np.matmul(det_checker(X), num_vector[j])) encrypted_modlist = [] for k in range(len(num_vector)): encrypted_modlist.append(encrypted_list[k]%26) total_list = [] for a in encrypted_modlist: for b in a: total_list.append(b) print(total_list) final = [] for num in total_list: final.append(chr(num + 96)) final_encrypt = "".join(final) print(final_encrypt)
9747a57f97b56bc04ecd6d117a555dcbdf1a758a
Mimoona/Python_Homework
/Lesson-7/Lesson7-HW.py
1,682
4.09375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 21:51:08 2020 @author: Mimoona Raheel """ print("Exercise 1:") print("~~~~~~~~~~~") number_1=input('Please enter a number:') number_2=input('Please enter another number:') if number_1 > number_2: print(f'{number_1} is bigger than {number_2}.') else: print(f'{number_2} is bigger than {number_1}.') #%% print("\nExercise:2") print("~~~~~~~~~~~~") number=int(input('Please enter a number:')) if (number%2) == 0: print(f'Number {number} you have entered is an even.') else: print(f'Number {number} you have entered is an odd.') #%% print("\nExercise 3:") print("~~~~~~~~~~~~~") name = input('What is your First Name? ') surname = input(f'{name} please write your surname. ') if name[0] == surname[0]: print(f'Hello {name} {surname}, your first name and surname starts with the same letter.') else: print(f'Hello {name} {surname}, your first name and surname doesn\'t start with the same letter.') #%% print("\nExercise:4") print("~~~~~~~~~~~~") length_name = len(name) length_surname = len(surname) total_letters = length_name+length_surname print('Printing the count of characters in user name') print(total_letters) if (total_letters%3 == 0): print(f'Your full name has {total_letters} characters and it is divisible by 3') else: print(f'Your full name has {total_letters} characters and it is not divisible by 3') #%% print("\nExercise:5") print("~~~~~~~~~~~~~") print('Let see if your name has even number of characters.') if (length_name%2 == 0 and length_surname%2 == 0): print('Total number of characters in your full name is even') else: print('Total number of characters in your full name is odd')
94b14bf0d4015297a2162eb9be7e3671bc7b1147
UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018
/students/NatalieRodriguez/Lesson07/db/populate_db.py
5,541
3.703125
4
""" Learning persistence with Peewee and sqlite delete the database to start over (but running this program does not require it) """ from create_db import * from datetime import datetime, timedelta from dateutil.parser import parse import pprint import logging def date_converter(date): return datetime.strptime(''.join(date.split('-')), '%Y%m%d') def dates_diff(date2, date1): return (date_converter(date2)-date_converter(date1)).days def populate_persons(): """ add person data to database """ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) database = SqliteDatabase('personnel_database.db') logger.info('Working with Person class') PERSON_NAME = 0 LIVES_IN_TOWN = 1 NICKNAME = 2 people = [ ('Luke', 'Peoria', 'Lukey'), ('River', 'Dubuque', 'Ropey'), ('Virgil', 'Tulsa', 'Pigman'), ('Kibson', 'Springfield', 'PJ'), ('Natalie', 'Newark', None), ('Marceline', 'Lawrence', 'Marcy') ] logger.info('Creating Person records: iterate through the list of tuples') try: database.connect() database.execute_sql('PRAGMA foreign_keys = ON;') for person in people: with database.transaction(): new_person = Person.create( person_name = person[PERSON_NAME], lives_in_town = person[LIVES_IN_TOWN], nickname = person[NICKNAME]) new_person.save() logger.info('Database add successful') logger.info('Print the Person records we saved...') for saved_person in Person: logger.info(f'{saved_person.person_name} lives in {saved_person.lives_in_town} ' +\ f'and likes to be known as {saved_person.nickname}') except Exception as e: logger.info(f'Error creating = {person[PERSON_NAME]}') logger.info(e) finally: logger.info('database closes') database.close() def populate_depts(): """ add departments data to database """ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) database = SqliteDatabase('personnel_database.db') logger.info('Working with Department class') DEPT_NUM = 0 DEPT_NAME = 1 DEPT_MGR = 2 depts = [ ('HR', 'Human Resources', 'Emma Burgess'), ('ENG', 'Engineering', 'Emily OConnor'), ('BUS', 'Business', 'Kate Rodriguez') ] try: database.connect() database.execute_sql('PRAGMA foreign_keys = ON;') for dept in depts: with database.transaction(): new_department = Department.create( department_number = dept[DEPT_NUM], department_name = dept[DEPT_NAME], department_manager = dept[DEPT_MGR],) new_department.save() logger.info('Print the Department records we saved...') for dept in Department: logger.info(f'{dept.department_number} : {dept.department_manager} ' +\ f'manages {dept.department_name}') except Exception as e: logger.info(f'Error creating = {dept[DEPT_NAME]}') logger.info(e) finally: logger.info('database closes') database.close() def populate_jobs(): """ add job data to database """ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) database = SqliteDatabase('personnel_database.db') logger.info('Working with Job class') logger.info('Creating Job records: just like Person. We use the foreign key') JOB_NAME = 0 START_DATE = 1 END_DATE = 2 SALARY = 3 PERSON_EMPLOYED = 4 DEPARTMENT = 5 jobs = [ ('Asset Manager', '2008-06-05', '2016-10-03',72000, 'Natalie', 'BUS'), ('Business Analyst II', '2013-01-22', '2018-12-22', 63000, 'River', 'BUS'), ('Technical Recruiter', '2014-04-16', '2017-11-11', 55000, 'Kibson', 'HR'), ('VP Human Resources', '2018-03-01', '2018-09-15', 177000, 'Virgil', 'HR'), ('Eng Recruiter', '2014-11-14', '2018-02-28', 90000, 'Virgil', 'HR'), ('Env. Consultant', '2014-11-14', '2018-02-28', 90000, 'Luke', 'ENG'), ('VP Engineering', '2014-11-14', '2018-02-28', 162000, 'Marceline', 'ENG') ] try: database.connect() database.execute_sql('PRAGMA foreign_keys = ON;') for job in jobs: with database.transaction(): new_job = Job.create( job_name = job[JOB_NAME], start_date = job[START_DATE], end_date = job[END_DATE], duration = dates_diff(job[END_DATE], job[START_DATE]), salary = job[SALARY], person_employed = job[PERSON_EMPLOYED], job_department = job[DEPARTMENT]) new_job.save() logger.info('Reading and print all Job rows (note the value of person)...') for job in Job: logger.info(f'{job.job_name} : {job.start_date} to {job.end_date} for {job.person_employed} in {job.job_department}') except Exception as e: logger.info(f'Error creating = {job[JOB_NAME]}') logger.info(e) finally: logger.info('database closes') database.close() if __name__ == '__main__': populate_persons() populate_depts() populate_jobs()
8a21a85e4ee72b413fdc24a675f86d8a11ddd505
Dflorez015/Exercism_python
/scrabble-score/scrabble_score.py
439
3.765625
4
def score(word): scrabble_pieces = { "A" : 1, "E" : 1, "I" : 1, "O" : 1, "U" : 1, "L" : 1, "N" : 1, "R" : 1, "S" : 1, "T" : 1, "D" : 2, "G" : 2, "B" : 3, "C" : 3, "M" : 3, "P" : 3, "F" : 4, "H" : 4, "V" : 4, "W" : 4, "Y" : 4, "K" : 5, "J" : 8, "X" : 8, "Q" : 10, "Z" : 10 } total = 0 for value in word.upper(): total += scrabble_pieces[value] return total
df70b561030cc040a74a351956be3c3b0f4689b8
baidongbin/python
/疯狂Python讲义/codes/06/6.1/self_in_constructor.py
415
3.78125
4
class InConstructor: def __init__(self): # 在构造方法中定义一个foo变量(局部变量) foo = 0 # 使用self代表该构造方法正在初始化的对象 # 下面代码将会把该构造方法正在初始化的对象的foo实例变量设置为6 self.foo = 6 # 所有使用InConstructor创建的对象的foo实例变量将设为6 print(InConstructor().foo)
51303b6674613fcdc68d3123359a71542fdca5e7
frankie9793/Algorithms-and-Data-Structures
/Sorting/insertionSort.py
243
4.03125
4
# Time O(N^2) | Space O(1) def insertionSort(array): for i in range(len(array)): j = i while j > 0 and array[j] < array[j - 1]: array[j], array[j - 1] = array[j - 1], array[j] j -= 1 return array
4811396f8ea43bf4f4092d646726e8aabdd202c3
wldolan/CS590-python
/table_dict_count_search.py
1,224
3.78125
4
import os, sys, csv filename = sys.argv[1] #counting lines of file# def count_lines(filename): num_lines=0 with open(filename) as file: for line in file: lines = line.split() num_lines += 1 print ('this file contains {} lines'.format(num_lines)) #creating a dictionary# file = csv.DictReader(open('SampleAnnot.csv')) #for row in file: #look at dictionary contents # print row #searching a column# def count_mnix(file, value): count = 0 struct_acro = [] for row in file: mni_x = int(row["mni_x"]) if mni_x <= value: count = count + 1 struct_acro.append(row["structure_acronym"]) print ('there are {} entries with mni_x <= {}'.format(count,value)) print ('their structure acronyms are {}'.format(struct_acro)) #unique structure acronyms# def unique_structacro(file): output = set() for row in file: output.add(row["structure_acronym"]) print ('list of all unique structure acronyms:{}'.format(output)) ## MAIN ## filename = sys.argv[1] file = csv.DictReader(open(filename)) count_lines(filename) count_mnix(file, -35) file = csv.DictReader(open(filename)) unique_structacro(file)
025cd6969efcd12658001b31240b9b670e5afcfa
nicholasippedico/Python-Coding
/Filemanager.py
2,838
3.5
4
# -*- coding: utf-8 -*- """ @author: Nicholas Ippedico, Nick Braga, Alec Mitchell """ import csv, DatabaseManager class FileManager: def __init__(self, dbm): self.data={} self.dbm = dbm #loads the csv file def load_csv(self, fn): with open(fn) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 keys = [] flight_counter = 0 #increment when we see a valid flight for row in csv_reader: if line_count == 0: #replace spaces with dashes for i in range(len(row)): #print('DEBUG: i =', i) keys.append(row[i].replace(' ', '_')) #print('DEBUG: keys =', keys) line_count += 1 else: flight_id = row[0] if flight_id.isnumeric(): flight = {} #iterating with index #print("DEBUG: line =",linenum) if (len(row) < len(keys)): continue #print('DEBUG: row=', row) for i in range(len(row)): #print('DEBUG: i=', i) try: flight[keys[i]] = row[i] except(IndexError): #print('DEBUG: i=', i) pass self.dbm.create_flight( flight['ID'], flight['Airline'], flight['Location'], flight['Date'], flight['Time'], flight['SeatingChoice'], flight['AirlineMiles'], flight['Price'] ) flight_counter += 1 line_count += 1 print('loaded', flight_counter, 'flights from', fn) #saves selected data to csv file def save_csv(self,fn): # select all the data in the database #self.dbm.select_all() with open(fn,mode='w') as outfile: self.dbm.print_selection_to_file(outfile) print('saved flights to', fn) if __name__ == '__main__': import DBManager2 dbm = DBManager2().DatabaseManager() dbm.reset() fm = FileManager() fm.load_csv('flights.csv') dbm.select_by_id(['22']) fm.save_csv('test.csv')
1643394266dfed7b75403d6ebca07ef60d6cf6b2
brianhuynh2021/Python_fundamentals
/cat_amount.py
158
3.84375
4
def getCatAmount(): numCats = input('How many cats do you have?') if int(numCats) < 6: print('You should get more cats.') cat = getCatAmount()
139221d3ae34bdf563605b5d8fcb330f6164f146
Darlley/Python
/LIVRO_CursoIntensivoPython/Capitulo_3/ex06.py
1,228
3.75
4
#3.6 – Mais convidados: Você acabou de encontrar uma mesa de jantar maior, #portanto agora tem mais espaço disponível. Pense em mais três convidados para o #jantar. #• Comece com seu programa do Exercício 3.4 ou do Exercício 3.5. Acrescente #uma instrução print no final de seu programa informando às pessoas que você #encontrou uma mesa de jantar maior. #• Utilize insert() para adicionar um novo convidado no início de sua lista. #• Utilize insert() para adicionar um novo convidado no meio de sua lista. #• Utilize append() para adicionar um novo convidado no final de sua lista. #• Exiba um novo conjunto de mensagens de convite, uma para cada pessoa que #está em sua lista. convidados = ['Alvin Plantinga', 'William Lane Craig', 'Francis Collins'] print(convidados[0]+", "+convidados[1]+", "+convidados[2]+".\nConsegui uma mesa maior e convidei mais pessoas a nos acompanhar.\n") convidados.insert(0, "John Walton") convidados.insert(2, "Bertrand Russell") convidados.append("Leibniz") print(convidados) mensagem_saudação = "Olá senhores " mensagem_convite = ".\nGostaria muito da presença dos senhores em nosso jantar.\n" print("\n"+mensagem_saudação + convidados[0] + ", " + convidados[2] + " e " + convidados[5]+mensagem_convite)
26d07c998e39a0ba695510ff2c4b6d70285b68dc
callaunchpad/MOR
/environments/robot_arm/maddux/robots/link.py
5,545
3.734375
4
""" A Link object holds all information related to a robot link such as the DH parameters and position in relation to the world. """ import numpy as np from ..plot import plot_sphere import math class Link: def __init__(self, theta, offset, length, twist, q_lim=None, max_velocity=30.0, link_size=0.1, connector_size=0.1): """Link init :param theta: Link angle, variable :type theta: int :param offset: Link offset, constant :type offset: int :param length: Link length, constant :type length: int :param twist: Link twist, constant :type twist: int :param q_lim: Joint coordinate limits :type q_lim: numpy.ndarray or None :param max_velocity: Maximum radians the link can rotate per second :type max_velocity: int :param link_size: The size of the link (used in collision detection and plotting) :type link_size: int :param connector_size: The size of the link connector :type connector_size: int :rtype: None """ self.offset = offset self.length = length self.twist = twist self.q_lim = q_lim self.max_velocity = max_velocity self.link_size = link_size self.connector_size = connector_size self.set_theta(theta) self.velocity = 0 # Link's current velocity # This is updated once we add it to an arm self.base_pos = None self.end_pos = None def set_theta(self, theta): """Sets theta to the new theta and computes the new transformation matrix :param theta: The new theta for the link :type theta: int :rtype: None """ self.theta = theta self.transform_matrix = self.compute_transformation_matrix(theta) def update_velocity(self, accel, time): """Updates the current velocity of the link when acted upon by some acceleration over some time :param accel: The acceleration acting upon the link (radians per second^2) :type accel: int :param time: The time the accelration is applied over (seconds) :type time: int :rtype: None """ new_velocity = self.velocity + (accel * time) if new_velocity <= self.max_velocity: self.velocity = new_velocity new_theta = self.theta + (new_velocity * time) new_theta = math.atan2(math.sin(new_theta), math.cos(new_theta)) self.set_theta(new_theta) def compute_transformation_matrix(self, q): """Transformation matrix from the current theta to the new theta :param q: the new theta :type q: int :returns: Transformation matrix from current q to provided q :rtype: 4x4 numpy matrix """ sa = np.sin(self.twist) ca = np.cos(self.twist) st = np.sin(q) ct = np.cos(q) T = np.matrix([[ct, -st * ca, st * sa, self.length * ct], [st, ct * ca, -ct * sa, self.length * st], [0, sa, ca, self.offset], [0, 0, 0, 1]]) return T # TODO: Abstract this to take dynamic objects as well as static ones def is_in_collision(self, env_object): """Checks if the arm is in collision with a given static object :param env_object: The object to check for collisions with :type env_object: maddux.objects.StaticObject :returns: Whether link hits the provided env_object :rtype: bool """ intersects_joint = env_object.is_hit_by_sphere(self.base_pos, self.link_size) # If the link sphere is in collision we do not need to # check anything else if intersects_joint: return True # If the link is just a joint we only needed to check sphere, # and since we would have already returned, we know we're safe if self.length == 0 and self.offset == 0: return False # Otherwise we need to check if the object intersects with # the arm connector, so we vectorize it and call is_hit lamb = np.linspace(0, 1, 100) v = self.end_pos - self.base_pos positions = self.base_pos + lamb[:, np.newaxis] * v return env_object.is_hit(positions) def display(self): """Display the link's properties nicely :rtype: None """ print 'Link angle: {}'.format(self.theta) print 'Link offset: {}'.format(self.offset) print 'Link length: {}'.format(self.length) print 'Link twist: {}'.format(self.twist) def plot(self, ax): """Plots the link on the given matplotlib figure :param ax: Figure to plot link upon :type ax: matplotlib.axes :rtype: None """ if self.base_pos is None or self.end_pos is None: raise ValueError("Base and End positions were never defined") plot_sphere(self.end_pos, self.link_size, ax, color='black') # If there's no length associated, we don't have to draw one if self.length == 0 and self.offset == 0: return ax pts = np.vstack((self.base_pos, self.end_pos)) return ax.plot(pts[:, 0], pts[:, 1], pts[:, 2], color='b', linewidth=3)
dbe1111d8ebe75f659f08be974cab4af2a56b12b
SBNC-Bavlab/ML-Algorithms-Visualization-and-Positioning
/Bokeh/Decision_Tree/ID3_Decision_Tree/bucheim.py
6,437
3.6875
4
##################################################################################################### # Implementation of "Drawing rooted trees in linear time(Buchheim, Jünger and Leipert, 2006)"# # constant for distance between two nodes distance = 5 def tree_layout(node): """ main function """ first_walk(node) second_walk(node, 0-node.mod) def first_walk(node): """ Calling FIRSTWALK(node) computes a preliminary x-coordinate for node. Before that, FIRSTWALK is applied recursively to the children of node, as well as the function APPORTION. After spacing out the children by calling EXECUTESHIFTS, the node is placed to the midpoint of its outermost children. """ if node.decision: # if node is a leaf node.prelim = 0 if node.parentPointer and node.parentPointer.children[0] != node: # if node has a left sibling index_node = node.parentPointer.children.index(node) node.prelim = node.parentPointer.children[index_node-1].prelim + distance else: default_ancestor = node.children[0] for child in node.children: first_walk(child) default_ancestor = apportion(child, default_ancestor) execute_shifts(node) midpoint = (node.children[0].prelim + node.children[-1].prelim)/2 if node.parentPointer and node.parentPointer.children[0] != node: # if node has a left sibling index_node = node.parentPointer.children.index(node) node.prelim = node.parentPointer.children[index_node - 1].prelim + distance node.mod = node.prelim - midpoint else: node.prelim = midpoint def apportion(node, default_ancestor): """ The procedure APPORTION (again following Walker’s notation) is the core of the algorithm. Here a new subtree is combined with the previous subtrees. As in the Reingold–Tilford algorithm, threads are used to traverse the inside and outside contours of the left and right subtree up to the highest common level. """ if node.parentPointer and node.parentPointer.children[0] != node: index_node = node.parentPointer.children.index(node) left_sibling = node.parentPointer.children[index_node-1] node_in_right = node_out_right = node node_in_left = left_sibling node_out_left = node_in_right.parentPointer.children[0] mod_in_right = node_in_right.mod mod_out_right = node_out_right.mod mod_in_left = node_in_left.mod mod_out_left = node_out_left.mod while next_right(node_in_left) and next_left(node_in_right): node_in_left = next_right(node_in_left) node_in_right = next_left(node_in_right) node_out_left = next_left(node_out_left) node_out_right = next_right(node_out_right) node_out_right.ancestor = node shift = (node_in_left.prelim + mod_in_left) - (node_in_right.prelim + mod_in_right) + distance if shift > 0: move_subtree(ancestor(node_in_left, node, default_ancestor), node, shift) mod_in_right = mod_in_right + shift mod_out_right = mod_out_right + shift mod_in_left = mod_in_left + node_in_left.mod mod_in_right = mod_in_right + node_in_right.mod mod_out_left = mod_out_left + node_out_left.mod mod_out_right = mod_out_right + node_out_right.mod if next_right(node_in_left) and next_right(node_out_right) is None: node_out_right.thread = next_right(node_in_left) node_out_right.mod = node_out_right.mod + mod_in_left - mod_out_right if next_left(node_in_right) and next_left(node_out_left) is None: node_out_left.thread = next_left(node_in_right) node_out_left.mod = node_out_left.mod + mod_in_right - mod_out_left default_ancestor = node return default_ancestor def next_left(node): """ It returns the successor of node on this contour.This successor is either given by the leftmost child of node or by the thread of node. The function returns None if and only if node is on the highest level of its subtree. """ if node.children: # if node has a child return node.children[0] else: return node.thread def next_right(node): """ The function works analogously. """ if node.children: # if node has a child return node.children[-1] else: return node.thread def move_subtree(node_left, node_right, shift): """ Shifting a subtree can be done in linear time if performed as explained above. Calling MOVESUBTREE(wl,wr,shift) first shifts the current subtree, rooted at wr. This is done by increasing prelim(wr) and mod(wr) by shift. All other shifts, applied to the smaller subtrees between wl and wr, are performed later by EXECUTESHIFTS. To prepare this, we have to adjust change(wr), shift(wr), and change(wl). """ subtrees = node_right.order_number - node_left.order_number shift_subtrees = float(shift) / subtrees node_right.change -= shift_subtrees node_left.change += shift_subtrees node_right.shift += shift node_right.prelim += shift node_right.mod += shift def execute_shifts(node): """ The function only needs one traversal of the children of v to execute all shifts computed and memorized in MOVESUBTREE. """ shift = 0 change = 0 for child in node.children[::-1]: # all children from right to left child.prelim += shift child.mod += shift change += child.change shift += child.shift + change def ancestor(node_in_left, node, default_ancestor): """ The function ANCESTOR returns the left one of the greatest distinct ancestors of vil and its right neighbor. """ if node_in_left.ancestor in node.parentPointer.children: # if the ancestor is a sibling of the node return node_in_left.ancestor else: return default_ancestor def second_walk(node, m=0): """ The function is used to compute all real x-coordinates by summing up the modifiers recursively. """ node.coord = (node.depth, node.prelim + m + 2) for child in node.children: second_walk(child, m + node.mod)
fefa5bb0cdb9a427b18496e81f36ea0e6c33d400
AymanNasser/Python-For-Everybody-Specilization
/Access Web Data/Week2/Regular expression.py
285
3.609375
4
import re fh = open('../../romeo.txt','r') accum = 0 # Program that extract all digits from text & convert extracted string(digits) to ints for line in fh: line = line.strip() tempList = re.findall('[0-9]+',line) accum = accum + sum(list(map(int,tempList))) print(accum)
a279da51992f3d15ba5dbe460d3c6a998eb56a9e
atrivedi8988/DSA-Must-Do-Questions
/01_Fizz Buzz/Ideal Solutions/fizzBuzz.py
461
4.09375
4
# Print "Fizz" for multiple of 3 and print "Buzz" for multiple of 5 def fizzBuzz(N): for value in range(1, N + 1): # For multiple of 3 ----> Print "Fizz" if value % 3 == 0: print("Fizz") continue # For multiple of 5 ----> Print "Buzz" if value % 5 == 0: print("Buzz") continue print(value) if __name__ == "__main__": # Static Input N = 7 fizzBuzz(N)
4be4628954923ac3d05337c9f86d5f63fe073063
pianowow/various
/giftedmathematics.com/sum to 24/thread test.py
1,246
3.765625
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: CHRISTOPHER_IRWIN # # Created: 14/01/2013 # Copyright: (c) CHRISTOPHER_IRWIN 2013 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, delay, counter): super().__init__() self.threadID = threadID self.name = name self.delay = delay self.counter = counter print(name,"created") print(self.name,"created") def run(self): print ("Starting " + self.name) print_time(self.name, self.delay, self.counter) print ("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: time.sleep(delay) print (threadName, time.ctime(time.time())) counter -= 1 # Create new threads thread1 = myThread(1, "a", 1, 5) thread2 = myThread(2, "b", 2, 3) # Start new Threads thread1.start() thread2.start() thread1.join() thread2.join() print ("Exiting Main Thread")
953dc20852482cdf7931de39b5e559546b1e9945
macraiu/software_training
/leetcode/py/33_Search_in_Rotated_Sorted_Array.py
1,040
4.09375
4
""" You are given an integer array nums sorted in ascending order (with distinct values), and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). If target is found in the array return its index, otherwise, return -1. Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3: Input: nums = [1], target = 0 Output: -1 """ def search(nums, target): l = 0 r = len(nums) - 1 while (r - l > 1): m = (r + l) // 2 if nums[m] < nums[r]: if nums[m] < target <= nums[r]: l = m else: r = m else: if nums[l] <= target < nums[m]: r = m else: l = m if nums[l] == target: return l elif nums[r] == target: return r else: return -1 print(search(nums = [4, 11, 100, 1000, -10, -4, -1], target = 1000))
3edc40d6c15b4caf0758b2afff0141e86b7066e9
chan032/PS
/1629.py
436
3.828125
4
''' 모듈러 성질 : (a * b) mod c = (a mod c * b mod c) mod c ''' a, b, c = map(int, input().split()) def pow(base, exponent): if exponent == 1: return base else: half = exponent // 2 halfPow = pow(base, half) if exponent % 2 == 0: # even return (halfPow % c) * (halfPow % c) else: # odd return (halfPow % c) * (halfPow % c) * base print(pow(a, b)%c)
841ed16f5853175da956b8bfb6606aefa35d1f02
gyoscha/PythonPY100
/Занятие2/Лабораторные_задания/task2_4/main.py
507
3.9375
4
if __name__ == "__main__": # постарайтесь не использовать "магические" числа, # а по возможности дать переменным осмысленные названия и использовать их lesenka = 'Hello,world' for index, value in enumerate(lesenka, start=5): index = ' ' * index # пробел умножаю на индекс: 5, 6 и тд print(index, value) # 5 пробелов + значение
8237a49c13453a7af06bef2f77632abccc54fe8a
tanni-Islam/test
/module.py
104
3.515625
4
import re item = [] for i in dir(re): if "find" in i: item.append(i) print sorted(item)
4f4c09e361c707b01307fdd6ebe9aafe545819f1
iatecookies/LearnPython
/studenttest.py
1,792
3.71875
4
""" Chapter 11 Grading Students Practicing sets """ file1 = open("studenttests.txt") file2 = open("studentpassedtests.txt") studenttests = file1.read().splitlines() studentpassedtests = file2.read().splitlines() list2 = [] for (i, j) in zip( studenttests, studentpassedtests): studenttests = i.split(":") studentpassedtests = j.split(":") studentpassedtests_numbers = studentpassedtests[0] studentpassedtests_courses = studentpassedtests[1] studentpassedtests__courses_splitlist = studentpassedtests_courses.split(',') studenttests_numbers = studenttests[0] studenttests_courses = studenttests[1] studenttests_courses_splitlist = studenttests_courses.split(',') studentpassedtests_set = set(studentpassedtests__courses_splitlist) studenttests_set = set(studenttests_courses_splitlist) setResult = studenttests_set - studentpassedtests_set #amount of courses failed # print(studentpassedtests_set, studenttests_set) studenttests_set_value = 0 if studenttests_set == {''}: studenttests_set_value = 0 else: studenttests_set_value = len(studenttests_set) #print(studenttests_set, studenttests_set_value, len(setResult)) try: scoreStudent = studenttests_set_value/len(setResult) #print (studenttests_numbers, scoreStudent) except Exception as ex: #print(studenttests_numbers, ex) scoreStudent = studenttests_set_value*2 #print (studenttests_numbers, scoreStudent) list1 = [] list1.append(str(studenttests_numbers)) list1.append(scoreStudent) list1.append(len(setResult)) list2.append(list1) # puts in a new list # print(list1) # this will also print it nice but not sorted sortedList = sorted(list2) for i in sortedList: print (i)
25237e1aac4fa404aa529a189641d0e864683c30
peterocean/python_tutorial
/list_as_queue.py
298
3.78125
4
#!/usr/bin python3 #-*- coding:utf-8 -*- from collections import deque fruits = ['orange', 'apple', 'pear', 'banana', 'apple', 'banan'] queue = deque(["Eric", "John", "Michael"]) print(queue); queue.append("Terry") print(queue) queue.append("Graham") print(queue) queue.popleft() print(queue)
088e70c0dba72155cda10de965a7671bea8fb2f7
luiz-vinicius/URI-Online-Judge
/problems/1017.py
71
3.78125
4
x = int(input()) y = int(input()) r = "%.3f" % ((y / 12) * x) print(r)
12bf93f8741ae96055c8f077d8df991b8564527a
FerFabbiano/Algoritmos-I
/Clase 12-04.py
1,541
4.34375
4
"""Si lo que voy a agregar es un elemento suelto, uso append, si lo que le voy a agregar es otra lista, uso extend.""" """Ejemplo: l1 representa p(x)=3+x-2x^2+5x^3. l2 representa p(x)=2+0x+x^2+x^3. Hacer una funcion que le paso p1 y p2, y devuelve la suma.""" def sumarpolinomios(lista1, lista2): indice2 = 0 lista3 = [] if len(lista1) == len(lista2): for numero in lista1: numero += lista2[indice2] lista3.append(numero) indice2 += 1 return lista3 lista1 = [3, 1, -2, 5] lista2 = [2, 0, 1, -1] #print(sumarpolinomios(lista1, lista2)) def sumapolinomio(p1, p2): lista = [] while len(p1 != len(p2)): print(len(p2)) if len(p1) > len(p2): p2.append(0) else: p1.append(0) for i in range(len(p1)): lista.append(p1[i] + p2[i]) return lista """No imprimo ni cargo las listas dentro de la función.""" p1 = [3, 1, -2, 5] p2 = [2, 0] print(sumarpolinomios(p1, p2)) def f2(l): l.append(8) l = [4, 3, 2] f2(l) #print(l) """Ejercicio: Definir una función a la que se le pasa una lista de enteros y un número, devuelve la posición en la que está el número o -1 si no la encuentra. Sin usar in ni count.""" def verificarPosición(lista, numero): cantidad = len(lista) for i in range(cantidad): if lista[i] == numero: return i return -1 print(verificarPosición([1, 2, 3], 1)) """algoandres@yahoo.com"""
9de40b0e719ab2c8f27287c49c3114dc74bfc4bd
Prathmesh311/Data-Structures-and-Algorithms-Specialization
/Algorithmic Toolbox/Algorithmic Warm Up/Fibonacci Number/fibonacci_number.py
550
4.125
4
# python3 def fibonacci_number_naive(n): assert 0 <= n <= 45 if n <= 1: return n return fibonacci_number_naive(n - 1) + fibonacci_number_naive(n - 2) def fibonacci_number(n): assert 0 <= n <= 45 if n == 0: return 0 if n == 1: return 1 numbers = [] numbers.append(0) numbers.append(1) for i in range(2,n+1): numbers.insert(i,numbers[i-1] + numbers[i-2]) return numbers[n] if __name__ == '__main__': input_n = int(input()) print(fibonacci_number(input_n))
63fcaa6ede97a0b9b213650cd940a30eae406f60
ian-james-johnson/time_series_exercises
/acquire.py
4,354
3.75
4
# Time Series: Data Acquisition Exercises #Function for Exercise #1 #------------------------ # 1. Using the code from the lesson as a guide # and the REST API from https://python.zgulde.net/api/v1/items as we did in the lesson, # #create a dataframe named items that has all of the data for items. #This function acquires data from a REST API at the url above and returns a dataframe containing all the items def get_items(): import pandas as pd import requests # Define base url to obtain api from url= 'https://python.zgulde.net' # create response containing the contents of the response from the api response = requests.get(url + '/api/v1/items') #Turn that .json content into a dictionary for use with Python data = response.json() #Create a dataframe containing the dictionary created from the .json sent by the api df_items = pd.DataFrame(data['payload']['items']) return df_items #Function for Exercise #2 #------------------------ # 2. Do the same thing as #1, but for stores (https://python.zgulde.net/api/v1/stores) #This function acquires data from a REST API at the url above and returns a dataframe containing all the stores def get_stores(): import pandas as pd import requests # Define base url to obtain api from url= 'https://python.zgulde.net' # create response containing the stores from the api response_stores = requests.get(url + '/api/v1/stores') #Turn that .json content into a dictionary for use with Python data_stores = response_stores.json() #Create a dataframe containing the dictionary created from the .json sent by the api df_stores = pd.DataFrame(data_stores['payload']['stores']) return df_stores #Function for Exercise #3 #------------------------ # 2. Extract the data for sales (https://python.zgulde.net/api/v1/sales). # There are a lot of pages of data here, so your code will need to be a little more complex. # Your code should continue fetching data from the next page until all of the data is extracted. #This function acquires data from a REST API at the url above and returns a dataframe containing all the sales def get_sales(): import pandas as pd import requests # Define base url to obtain api from url= 'https://python.zgulde.net' #Iterating thru every page and concatenating the sales info from each page, we create a loop #acquire .json from url response_sales = requests.get(url + '/api/v1/sales') #turn .json content into dictionary data_sales = response_sales.json() #turn dictionary into a dataframe df_sales = pd.DataFrame(data_sales['payload']['sales']) #Get ready to iterate thru all pages num_pages = data_sales['payload']['max_page'] # loop thru the iterations for i in range(1,num_pages): response_sales = requests.get(url + data_sales['payload']['next_page']) data_sales = response_sales.json() df_sales = pd.concat([df_sales, pd.DataFrame(data_sales['payload']['sales'])]) return df_sales #Function for Exercise #4 #------------------------ #4. Save the data in your files to local csv files so that it will be faster to access in the future. #This function calls the get_sales function and creates a .csv with sales data and saves it locally def create_sales_data_csv(): df_sales = get_sales() #create a csv from sales data and store locally df_sales.to_csv('sales.csv') #Function for Exercise #5 #------------------------ # Combine the data from your three separate dataframes into one large dataframe. #This function calls 3 functions that get sales, stores, and items and concatenates and returns all the data in one dataframe def combine_sales_stores_items_data(): import pandas as pd df_sales = get_sales() df_stores = get_stores() df_items = get_items() df_sales_and_stores = pd.merge(df_sales, df_stores, how='left', left_on='store' , right_on='store_id') df_all = pd.merge(df_sales_and_stores, df_items, how='left', left_on='item', right_on='item_id') return df_all #Function for Exercise #6 #------------------------ #This function reads data from a link to a .csv file and returns a dataframe def csv_to_df(url): import pandas as pd df_from_csv = pd.read_csv(url) return df_from_csv
8e4623bc5e69701b66c330484e36750f65df8ef0
mosel123/codePython
/elementosBasicos/operaciones.py
462
3.796875
4
import os numero1 = 10 numero2 = 10 resultado = numero1 + numero2 print("El resultado de la suma es: ",resultado) numero1 = 10 numero2 = 10 resultado = numero1 - numero2 print("El resultado de la resta es: ",resultado) numero1 = 10 numero2 = 10 resultado = numero1 * numero2 print("El resultado de la multipliacion es: ",resultado) numero1 = 10 numero2 = 10 resultado = numero1 / numero2 print("El resultado de la division es: ",resultado) os.system("PAUSE")
b0b35fd1726c5bfca3fd8e357e894b0f59893220
trollius/work
/load_csv_sql.py
859
3.671875
4
import csv import sqlite3 # Create the database connection = sqlite3.connect('test.db') connection.text_factory = str cursor = connection.cursor() # Create the table cursor.execute('DROP TABLE IF EXISTS prices') cursor.execute('CREATE TABLE prices ( myid integer, parent_id integer, hlevel integer, name text, description text, publications text, tool_ver text) ') connection.commit() # Load the CSV file into CSV reader csvfile = open('mytools.txt', 'rb') creader = csv.reader(csvfile, delimiter=';', quotechar='|') # Iterate through the CSV reader, inserting values into the database for t in creader: cursor.execute('INSERT INTO prices VALUES (?,?,?,?,?,?,?)', t ) # Close the csv file, commit changes, and close the connection csvfile.close() connection.commit() connection.close() #myid,parent_id,hlevel,name,description,publications,tool_ver
284a4e14c64c73fe81874d8e57eae4b55eca1c95
keviv202/Python-Code
/intersection_part2.py
231
3.796875
4
class find: def find(self,i,j): n = [] for i1 in i: if i1 in j: n.append(i1) print(n) j=[2, 2] i=[1,2, 2,1] f = find() if len(j)>len(i): f.find(i,j) else: f.find(j,i)