blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a0485f1dc91d36a9f91a4c2e5970dfe1bbdb1180
DamianRubio/advent-of-code
/2020/12/solution.py
5,576
3.6875
4
from collections import defaultdict from copy import deepcopy input_file = '2020/12/input.txt' ship_instructions = open(input_file).read().strip('\n').split('\n') ordered_positions = ['north', 'east', 'south', 'west'] def compute_manhattan_distance(movement_dict): return abs(movement_dict['north']) + abs(moveme...
edf5f02ad075fcac802302e8f71bc62746d6d051
jacob-brown/programming-notes-book
/programming_notes/_build/jupyter_execute/python_basic.py
4,747
4.46875
4
# Python: Basics ## Lists Methods: * `append()` * `clear()` * `copy()` * `count()` * `extend()` * `index()` * `insert()` * `pop()` * `remove()` * `reverse()` * `sort()` demoList = ["apple", "banana", "orange", "kiwi"] print(demoList) Adding/Removing items demoList.append('cherry') print(demoList) demoList.inse...
7eb47946afa1c65507691501706ada044e96ef87
gaurav-singh-au16/Online-Judges
/Leet_Code_problems/227. Basic_Calculator_II.py
2,229
3.953125
4
""" 227. Basic Calculator II Medium 1992 321 Add to List Share Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. Example 1: Input: s = "3+2*2" Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: ...
96cabaad6a9f3978946dfd671f30e5afc0290b17
r0ckburn/d_r0ck
/The Modern Python 3 Bootcamp/4 - Boolean and Conditional Logic/making_decisions_with_conditional_statements.py
948
4.53125
5
# Conditional Statements # Conditional logic using if statements represents different paths a program can take based on some type of comparison of input # if some condition is True: # do something # elif some other condition is True: # do something # else: # do something # You need 1 if, can have as m...
8fda6ea6e3ccd3964e2548bce70897a2ad409555
glenpike/dbscode
/minecraft/experiments/text/letters.py
1,843
3.828125
4
from dbscode_minecraft import * from pixelfont_04B_03 import chars """ Simple functions to write text in Minecraft This only works in the x-plane - need to figure out how to make it directional. Also uses a "font" which is an object containing a 2D list for each char. This could be refined to generate the characte...
2dd11f83de1b6d2ea30a2fcdba69edc05d8bfc88
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/knxchi001/question2.py
188
4.15625
4
#Assignment 3 # Question 2 height= eval(input("Enter the height of the triangle:\n")) gap= height-1 for i in range(1,(height*2),2): print(gap*" ","*"*i, sep="") gap=gap-1
ab90586c9714d21d4f172ec5b257a06ddb89968c
gabriellaec/desoft-analise-exercicios
/backup/user_139/ch133_2020_04_01_11_10_28_772568.py
363
4.03125
4
r1 = input ('Está funcionando?') if r1 == 's': print ('Sem problemas!') elif r1 == 'n': input ('Você sabe corrigir?') if r1 == 's': print('Sem problemas!') elif r1 == 'n': input ('Você precisa corrigir?') if r1 == 's': print ('Apague tudo e tente novamente') e...
23fe0a018af1fb218bea63056c98f94dba6b21c0
wadi-1000/News-API
/app/tests/articles_test.py
664
3.71875
4
import unittest from models import articles Articles = articles.Articles class ArticlesTest(unittest.TestCase): ''' Test Class to test the behaviour of the Articles class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_article = Artic...
8bc01590860830c34a2cffcff77c1104b7043657
ebachmeier/School
/Python/TriangleArea.py
388
4.5
4
# Eric Bachmeier # This program is used to input dimensions and calculate the area of a triangle. # Date Completed: September 9, 2011 print "Area of a Triangle Program" print height = float (raw_input ("Enter the Height of the Triangle: ")) base = float (raw_input ("Enter the Base of the Triangle: ")) print p...
f70d2039588c81dda2d5e3a88c77bd1e524165fa
avantikaaa/wtef-codes
/assessment1/encrypt.py
416
3.953125
4
def encrypt(input_word): # YOUR CODE HERE d = {'a':0, 'e':1, 'o':2,'u':3} print d input_word = list((input_word)[::-1]) print input_word for i in range(len(input_word)): if input_word[i].lower() in d: print i input_word[i] = str(d[input_word[i].lower()]) print...
179a4f69762c1d1b26855166e5bb48e716dc8f50
paljsingh/bloxorz
/pos.py
947
3.609375
4
from __future__ import annotations from orientation import Orientation class Pos: def __init__(self, x: int, y: int, orientation: Orientation = Orientation.STANDING): self.x = x self.y = y self.orientation = orientation def __hash__(self): return hash((self.x, self.y, self.or...
36531bc8af8a2ec2eec54c89423f88ac8aa6528d
rafaelperazzo/programacao-web
/moodledata/vpl_data/11/usersdata/97/5475/submittedfiles/jogo.py
574
3.78125
4
# -*- coding: utf-8 -*- from __future__ import division import math Cv=input('Digite o número de vitórias do cormengo:') Ce=input('Digite o número de empates do cormengo:') Cs=input('Digite o saldo de gols do cormengo:') Fv=input('Digite o número de vitórias do flaminthias:') Fe=input('Digite o número de empates do fl...
8be09a8eba6d428fd3e8e30e3d7c8f1b461dbaa2
hemanthk97/airflow-k8s-autoscaling
/fruit.py
275
3.546875
4
import sys import time fruits = ["apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry","apple", "banana", "cherry"] for x in fruits: time.sleep(3) print(x)
2e03bbfe1e56e04b295ebb473fda5645b6902ee5
MatthieuSarter/AdventOfCode
/AoC_2019/Day13/__init__.py
2,967
3.5
4
import ast, os import sys from collections import defaultdict from time import sleep from typing import Dict, List from Day10 import Point from Day9 import run_program, NewProgram GameMap = Dict[Point, int] def count_tiles(program, tile_type): # type: (NewProgram, int) -> int ''' Count the number of tile...
51da2c8673034ec9f9f2153bd4ddffb05617d51c
shtaag/Community-StartHaskell2011
/exercises/chapter04/solutions/Exercise16.py
133
3.78125
4
from math import sqrt # calculate the length of the hypotenuse of a right triangle def pythag(a, b): return sqrt(a * a + b * b)
2a47c61685c7b1988f358242d61c6bd71a68d4e3
SahaanaIyer/dsci-greyatom
/student_mgmt.py
868
3.796875
4
# Prepare the student roster class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) ...
316d43fb9c46ba060fbd8d3c062503bef7a5cf6a
agentreno/diveintopython
/chapter5/regex.py
1,479
3.625
4
import re s = '100 BROAD ROAD APT. 3' # Raw strings don't have any escape chars: print(r"re.sub substitutes, \b is a word boundary") print(re.sub(r'\bROAD\b', 'RD.', s)) # Compact regular expression for roman numeral validity pattern = """ ^ # beginning of string M{0,3} # thousands - 0...
764b8b38ac36f3eb7942777e2bbfa0ed63bead27
koteshrv/Python
/APSSDC_Training/Packages/Module.py
220
3.96875
4
# even or odd function def even(n): if n % 2 == 0: return True return False # max of three def unique(lst): l = [] for i in lst: if lst.count(i) == 1: l.append(i) print(l)
4e1bab5ab064086d3573c7b8b78ba37f13a0c6ef
jcp510/movie-trailer-website
/media.py
806
3.578125
4
import webbrowser # Data structure to store favorite movies. class Movie: """"Store favorite movies, include title, storyline, box art, and trailer. Attributes: title (str): movie title. storyline (str): movie plot. poster_image_url (str): url for movie box art. ...
61f59bfb98d45e1b4b6d4c048045522212809345
scric/Python3.x-2017
/begginger/2017-03-12/第七章-Web开发-集成在一起/Athlete.py
571
3.609375
4
import sanitize class AthleteList(list): def __init__(self, a_name, a_dob=None, a_times=[]): list.__init__([]) self.name = a_name self.dob = a_dob self.extend(a_times) def top3(self): return sorted(set([sanitize.sanitize(t) for t in self]))[0:3] # 新类代码的使用 # vera = At...
a23ad694b266cd4a3e4f586c0c423e62bf090798
gabrieldsumabat/DocSimilarity
/tests/TestCleanText.py
509
3.59375
4
import string import unittest from code.CleanText import clean_text class TestCleanText(unittest.TestCase): def test_clean_text(self): bad_text = string.punctuation self.assertEqual(clean_text(bad_text), "%") symbol_text = "-- J.R.R. Tolkien, \"The Lord of the Rings\"" self.asser...
2c3800619ef2018ad3ad342201d3ff5ef939cc5c
Cfoley23/100-Days-Of-Code
/Month 01/Week 04/Day 25/Katie's Turtle.py
2,316
3.828125
4
from turtle import Turtle, Screen francis = Turtle() screen = Screen() turtle_shape = ((0, 16), (-2, 14), (-1, 10), (-4, 7), (-7, 9), (-9, 8), (-6, 5), (-7, 1), (-5, -3), (-8, -6), (-6, -8), (-4, -5), (0, -7), (4, -5), (6, -8), (8, -6), (5, -3), (7, 1), (6, 5), (9, 8), (7, 9), (4, 7), (1, 10), (2, 14), (0, 16)) bigg...
5158d0ee070a9d7d1959d921e30386fa9a397289
kuroalabo/coding_problems
/Python/30-Days-of-Code/Day8/Day8.py
417
3.640625
4
#!/usr/bin/env python3 number_of_entries = int(input()) phoneBook = {} arr = [] for i in range(0, number_of_entries): arr = list(map(str, input().rstrip().split())) phoneBook[arr[0]] = arr[1] while True: try: query = input() if query in phoneBook: print(query + "="...
faf20c8fe991f3eb0d125e697f1db874cb1052d0
gunjan-madan/Python-Solution
/Module3/1.3.py
1,638
4.625
5
# In one of the previous lessons, you used the print statement to create text art. # Imagine using the while loop command and the print statements to generate some really awesome text art. # Let's help Sam create some great text art. All set to give it a try! '''Task 1: Pattern Printing''' print("**** Task 1: ****") ...
66257e7db5febd8750257e454d783714df635164
rustom/leetcode
/Miscellaneous/Length of Last Word.py
261
3.609375
4
class Solution: def lengthOfLastWord(self, s: str) -> int: string = s.strip() pieces = string.split(' ') try: return len(pieces[-1]) except: return 0 sol = Solution() print(sol.lengthOfLastWord('a '))
9b887c49052e20619fad39bd1b35b8d054530d96
aaaaaaaaaaaaaaaaace/cp2019
/p02/q05_find_month_days.py
692
4.125
4
month = int(input('Enter month:')) year = int(input('Enter year:')) months = ["January","February","March","April","May","June","July","August","September","October","November","December"] if month == 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0): print('February' + ' ' + str(year) + ' has 29 days....
222c1b96decb07eb9fb4fa62a0d188c4d815d338
nicolargo/pythonarena
/typing/multipletype.py
485
4
4
#!/usr/bin/env python3 from typing import overload class Foo(object): def __init__(self, name): self.name = name def __str__(self): return self.name @overload def put(self, name: int) -> int: self.name = int(name) return self.name def put(self, name): se...
2e1e275dd7191f8b18fe73af0a8d7cde49c95289
gaurangalat/SI506
/Gaurang_DYU2.py
1,163
4.3125
4
#Week 2 Demonstrate your understanding print "Do you want a demo of this week's DYU?\nA. Yes B. Not again\n" inp = raw_input("Please enter your option: ") #Take input from user if (inp =="B" or inp =="b"): print "Oh well nevermind" elif(inp == "A" or inp =="a"): #Check Option print "\nHere are a few comic...
5ae0f82c011f9ac232a1f95ff1f2163fa230d631
WhaleJ84/com404
/1-basics/4-repetition/8-nested-loop/bot.py
387
4.4375
4
# Ask the user how many rows and columns they want print("How many rows should I have?") rows = int(input()) print("How many columns should I have?") columns = int(input()) asciiFace = ":-) " # Print an ascii face in the rows and columns defined above print("Here I go:") for count in range(rows): for number in rang...
edbfbe9b68b1398a75f7ec63fb3d32013bf9c6a6
astabrq12/Istabrq12.github.io
/exercises.py
410
3.578125
4
import turtle n = turtle.Turtle() def c1(x,z): n.speed(25) for i in range(180): n.forward(100) n.color(z) n.right(30) n.forward(20) n.left(60) n.color(x) n.forward(50) n.color(x) n.right(30) n.penup() n.setp...
af793a40a576e1cf876640c1c6817198d0a15229
bitscuit/perceptron
/main.py
3,784
3.578125
4
import numpy as np import pprint ITERATIONS = 200 LEARNING_RATE = 0.01 BIAS = 1 count = 0 # reads the dataset from CSV file and normalizes it def getData(filename): data = np.loadtxt(filename, delimiter=',') # load csv file into numpy array # normalize data (ignore last column because that is desired outp...
75878ab810fcb7d02f077efbd70221c90369eeeb
rockpz/leetcode-py
/algorithms/reverseWordsInAString/reverseWordsInAString.2.py
689
3.75
4
# Source : https://oj.leetcode.com/problems/reverse-words-in-a-string-ii/ # Author : Ping Zhen # Date : 2017-04-17 '''********************************************************************************** * * Given an input string, reverse the string word by word. A word is defined as a sequence of non-space charact...
34ad8e36c73dae6b9c7a60dd5e42999044a839f7
lucasptcastro/projetos-curso-em-video-python
/ex044.py
936
3.6875
4
p = float(input('Informe o valor do produto: ')) print(' ') print('Tecle [\033[34m1\033[m] para pagamento à vista \033[34mdinheiro\033[m/\033[34mcheque\033[m: \033[33m10% de desconto\033[m') print('Tecle [\033[34m2\033[m] para pagamento à vista no \033[34cartão\033[m: \033[33m5% de desconto\033[m') print('Tecle [\033[3...
cbf7cdc91452c9259134b98d21d8ff626712a7e2
harshraj22/problem_solving
/solution/leetcode/2302.py
1,552
3.53125
4
# https://leetcode.com/problems/count-subarrays-with-score-less-than-k/ import enum class Solution: def possible(self, i, j, nums, pref_sum, k) -> bool: sum = pref_sum[j] - pref_sum[i] + nums[i] length = j - i + 1 return k > length * sum def binary_search(self, index, nums, pref_sum,...
33ef01b21f309551627809b3edda3750597ea7cb
CL129/my-travel-plans
/单元测试/szys.py
524
3.578125
4
import random n1 = random.randint(1, 100) n2 = random.randint(1, 100) def add(n1, n2): while n1 + n2 >=100: n1 = random.randint(1, 100) n2 = random.randint(1, 100) return n1 + n2 def sub(n1, n2): n1, n2 = max(n1, n2), min(n1, n2) return n1 - n2 def multi(n1, n2): while n1 * n2 >=...
b71ad33c352eb586beaa5c6ba1c011de2fa4d421
imgeekabhi/HackerRank
/interview-preparation-kit/ctci-is-binary-search-tree.py
455
3.8125
4
""" Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def checkNode(node, min, max): if node == None: return True if node.data <= min or node.data >= max: return False return checkNode(node.left, min,...
bd1f8129b35d3a95896985949efc82a2cbd02270
liwengyong/p1804_workspace
/p1/p10/blin.py
84
3.75
4
a=int(input('输入')) s=1 while a> 0: print(' '*a ,' *'*s) a=a-1 s=s+1
357e6ccdb1d29ea306b11d3c14e19183014a17cd
Dbajj/music-map
/app/model/connection.py
567
3.5625
4
# A connection describes a way two nodes can be related. # It contains a string type, as well as a dictionary of additional keys # containing extra information about the connection. class Connection(object): def __init__(self, type_desc, extras=None): if type(type_desc) is not str: raise Type...
a6cbda0f07201c5e946c6c24fe118b3766275672
python-kurs/exercise-2-RobFisch
/second_steps.py
2,017
4.21875
4
# Exercise 2 # Satellites: sat_database = {"METEOSAT" : 3000, "LANDSAT" : 30, "MODIS" : 500 } # The dictionary above contains the names and spatial resolutions of some satellite systems. # 1) Add the "GOES" and "worldview" satellites with their 2000/0.31m resolution...
fd5445f6b8f8e7e9e00ba85d2126b7d39162ae0a
rafaelperazzo/programacao-web
/moodledata/vpl_data/389/usersdata/328/72262/submittedfiles/poligono.py
88
3.640625
4
# -*- coding: utf-8 -*- n=int(input('número de lados do poligono:')) print('%.1f'%nd)
a02c9376d32693dca1a9b5730efd6e75e1a48ece
vgaurav3011/Regression-Algorithms
/Ridge_Regression.py
1,285
3.578125
4
#importing necessary files import numpy as np import pandas as pd from pandas import Series, DataFrame from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt #importing test and train file train = pd.read_csv('Train.csv') test = pd.read_csv('Test.csv') #Ridge Regression from sklearn.line...
d82bbd7e1a577905b406ec3fc82ee5c9d9ad3df1
shifubear/CryptWing
/cipher.py
1,086
3.6875
4
# # CS106 Final Project # CryptWing # # classical ciphers # # Shion Fukuzawa (sf27) # December 15, 2016 # # This file implementations the base cipher class. # # Algorithms referenced from # http://practicalcryptography.com/ # class Cipher: """ Cipher base class. Implements the main constructor, string m...
3f4342d27ef18010a68dbd4cca59a867b9a69a38
RBrignoli/Testes-python
/pythonarquivos/somacaracter.py
128
3.90625
4
n = int(input("digite um numero inteiro: ")) res = 0 while n != 0: a = n % 10 n = n // 10 res = a + res print (res)
7b35e5ebbd6417e765d76793b745f042228368a9
MRS88/python_basics
/week_5_tuples_cycles_lists/sum_of_factorials.py
394
3.90625
4
'''По данному натуральному n вычислите сумму 1!+2!+3!+...+n!. В решении этой задачи можно использовать только один цикл. Формат ввода Вводится натуральное число n.''' from math import factorial res = 0 for i in range(1, int(input())+1): res += factorial(i) print(res)
504441c49e32f2ed2196f2155c59797a4007dba9
marcos-saba/Cursos
/Curso Python/PythonExercicios/ex078.py
539
3.84375
4
valores = list() print('\033[30m='*50) for c in range(0, 5): valores.append(int(input(f'Digite o valor na posição {c}: '))) print('='*50) print(f'Você digitou os valores {valores}') print(f'O maior valor digitado foi {max(valores)} nas posições ', end='') for p, v in enumerate(valores): if v == max(valores): ...
a2c7e7174514aa2ab0535b20133fee97453a8464
imgagandeep/hackerrank
/python/math/004-mod-power.py
532
4.125
4
""" Task You are given three integers: a, b, and m, respectively. Print two lines. The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). Input Format The first line contains a, the second line contains b, and the third line contains m. Constraints 1 ≤ a ≤...
da87ef613bde2015392b25d8bf2dfae2c1295217
helloworld767/alogrithm
/612 k closest points.py
1,306
3.625
4
points = [[-1,-1],[1,1],[100,100]] origin = [0,0] k = 2 # points = [[point.x, point.y] for point in points] points.sort() def comp(point1, point2, origin): d1 = (point1[0] - origin[0]) ** 2 + (point1[1] - origin[1]) ** 2 d2 = (point2[0] - origin[0]) ** 2 + (point2[1] - origin[1]) ** 2 if d1 == d2: ...
aa68052988e7d6bac51c1840391c17507c629a60
abaumgarner/simplePythonEncryption
/main.py
604
3.546875
4
#!/usr/bin/env python3 """ Author: Aaron Baumgarner Created: 12/14/20 Updated: 12/14/20 Notes: Simple main to run all files needed for simple text incryption and decryption """ import menu encrypt = [] decrypt = [] """ Infanate loop to run the program until the user selects the 0 exit option """ while Tr...
9851d1f451d3c5a4ed2ba72e03c4248c10147a20
olivianauman/intro_to_cs
/.join.py
965
3.796875
4
#Get the index where myChar occurs replace the calue in myWord at that index #with the string "$$", i.e. reassign the value at that index as "$$". def problem4(myWord,myChar): charList = list(myWord) if myChar not in myWord: return ("Character not found.") else: while myChar in charLi...
3c7c3aa7d211258ad9cc684a22892759361d3da4
xiangz201/Learning-Notes
/python/algorithm/quicksort.py
705
3.84375
4
# -*-coding:utf-8-*- """ 快速排序 """ import numpy as np def create_array(num): return np.random.randint(20, size=num) def partition(arr, left, right): pivot = arr[right] i = left - 1 for j in range(left, right): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] ...
c87696ef9263d690711f1acb4cb3d6033ce889e4
caio-coutinho/learning_python
/EstruturaDeDecisao/9.py
1,359
4.1875
4
"""Faça um Programa que leia três números e mostre-os em ordem decrescente.""" number_one = input("Digite o primeiro numero:") number_two = input("Digite o segundo numero:") number_tree = input("Digite o terceiro numero:") if not number_one.isnumeric(): print("Entrada Invalida") exit() if not number_two.isnu...
35bd65c512aae27006c934dc97d36370424a5434
mmontone/acme
/acme/util.py
235
3.5
4
def all_subclasses(klass): subclasses = [] for cls in klass.__subclasses__(): subclasses.append(cls) if len(cls.__subclasses__()) > 0: subclasses.extend(all_subclasses(cls)) return subclasses
303fd2e5844338df9c8a13b49dfe71eb4ae6e039
rupaku/codebase
/DS/string/palindromic.py
1,574
4.15625
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example: "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Return 0 / 1 ( 0 for false, 1 for true ) for this problem ''' def sentencePalindrome(s): l, h = 0, len(...
df8d3c1cafa10ca2d2fb63c8c4ca7e8118f91e12
denvaar/Euler
/Problem7/p7.py
1,022
4
4
# By listing the first six prime numbers: # 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. # What is the 10001st prime number? import timeit import math # I learned that you don't have to go over # each of the primes, only up to the sqrt(index) # which saves considerable time. def solution(index): pr...
977c4015a95d1784e92b9df84982f3c60f795a35
rehassachdeva/UDP-Pinger
/UDPPingerServer.py
834
3.546875
4
import random import sys from socket import * # Check command line arguments if len(sys.argv) != 2: print "Usage: python UDPPingerServer <server port no>" sys.exit() # Create a UDP socket # Notice the use of SOCK_DGRAM for UDP packets serverSocket = socket(AF_INET, SOCK_DGRAM) # Assign IP address and port num...
b99df8f753e9ffde7eb29476b2b1b363e23ec5fb
digant0705/Algorithm
/LeetCode/Python/080 Remove Duplicates from Sorted Array II.py
1,356
3.921875
4
# -*- coding: utf-8 -*- ''' Remove Duplicates from Sorted Array II ====================================== Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of num...
a1b8b81cf2abf09b188d39a346ce1d98f0f11049
prashant97sikarwar/leetcode
/Tree/FindCorrespondingNodeOfaBinaryTreeInACloneofThatTree.py
825
3.828125
4
#Problem Link:- https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ """Given two binary trees original and cloned and given a reference to a node target in the original tree.The cloned tree is a copy of the original tree.Return a reference to the same node in the cloned t...
1b829121f9efe27436c1667c314f5a252e5e7c2d
agbischof/PythonPractice
/chaos.py
435
4.15625
4
# File: chaos.py # A simple program illustrating chaotic behavior def main(): print "This program illustrates a chaotic function" x1, x2 = input('Enter 2 numbers between 0 and 1 separated by commas: ') # x2 = input('Enter another number between 0 and 1: ') print "input ", x1, " ", x2 for i in range(10):...
4898a4907c0a8ae873f295c15e7a9f5ee2380164
figgynwtn/Total-Sales
/Ch7Ex1.py
953
4.0625
4
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> def main(): salelist = [] print("The store's sales for each day of the week: ") for i in range(7): print("The store sale of the day", (i + 1),...
13cab3d84d0f347940a9439a9395a5a3927cf88f
Inolas/python
/edX(MIT)/ProblemSets/ProblemSet4/chk.py
355
3.546875
4
import random VOWELS='AEIOU' CONSONANTS='QWRTYPLKJHGFDSZXCVBNM' n=5 hand={} numVowels = int(n / 3) for i in range(numVowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(numVowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand....
15e873ca10c30daba08a8b5c9b34b335bde902dc
kiccho1101/atcoder
/abc/249/b.py
302
3.96875
4
S = input() st = set() is_upper = False is_lower = False no_dup = True for s in S: if s.isupper(): is_upper = True if s.islower(): is_lower = True if s in st: no_dup = False st.add(s) if is_upper and is_lower and no_dup: print("Yes") else: print("No")
bd728d29792c749c60735234702f34b474f5e346
aviato/programming_for_everyone
/7.2.py
494
4
4
#~~~~~~~~~~~~~~~~~~~Coursera assignment 7.2~~~~~~~~~~~~~~~~~~~ prompt = raw_input("please enter filename: ") open_file = open(prompt) num_list = [] count = 0 total = 0 keyword = "X-DSPAM-Confidence:" for line in open_file: if keyword in line: line = line.split() num = float(line[1]) num_list.append(num...
86d6540761c44958a0c93f1662d30e0198b911a1
FrankXuxe/Dictionaries
/CSV_file_read_and_write.py
275
4
4
import csv customers = open('customers.csv', 'r') customer_file = csv.reader(customers, delimiter= ',') next(customer_file) for record in customer_file: print(record) print('First Name: ', record[1]) print('Last Name: ', record[2]) input()
f828282a76361624c22339e5f298515bd20d13b6
coltodu123/Password-gen
/test.py
386
3.609375
4
#!/usr/bin/python import itertools #from sys import argv user_list = raw_input("Enter the aflksdjfalsdf: ") user_list = (s.strip() for s in user_list.split(',')) with open('datafile') as infile, open('output', 'w') as outfile: for r in itertools.product((l.rstrip() for l in infile), user_list): mixed = ''...
b909b14d942744779ceb009a6e3e98cc018aecd5
Julianpse/python-exercises
/.~c9_invoke_2pcUWE.py
399
4.0625
4
""" #1. 1 to 10 for numbers in range(1,11): print(numbers) #2. n to m n = int(input("Start from #: ")) m = int(input("End at #: ")) for number in range(n,(m+1)): print(number) #3 Odd Numbers print(num) if numbers % 2 != 0: print(numbers) #4 Print a Square counter = 0 star = "*" wh...
ed417e91271bd1cded60a2ef707867452adc680b
BokaDimitrijevic/Exercises-in-Python
/power_list.py
354
4.25
4
def power_list(numbers): """Given a list of numbers, return a new list where each element is the corresponding element of the list to the power of the list index""" new_list=[ numbers**index for index,numbers in enumerate(numbers,start=0) ] return new_list print (po...
9cc76a640167d5e48113759865093939357f2fd0
christian-miljkovic/interview
/Algorithms/RandomizedQuickSort.py
1,539
4.25
4
# Randomized Quick Sort algorithm on a list of integers import random """ Time complexity Worst Case: O(n^2) when at every step the partition procedure splits an n-length array into arrays of size 1 and n−1 or when the array is already sorted Expected Case: O(nlogn) since you have to at least go through every value on...
487984effee6f8f169ac733af77bf31aadd8c449
chinahugh/python_workspace
/python_leaning/study/class.py
2,961
4.15625
4
# -*- coding: utf-8 -*- class MyClass(object): """一个简单的类实例""" __i = 12345 def f(self): return 'hello world' def __init__(self,a): self.data=[] self.__a=a print(self) @property def __geta(self): return self.__a @classmethod def classdef(cls): ...
54d5b8666d82eb11c7b99c34256e7c95fc357971
ygorvieira/exerciciosPython
/ex012.py
130
3.625
4
#Calculando desconto (5%) p = float(input('Digite o preço: R$')) print('O valor com desconto é R${:.2f}'.format(p - (p*0.05)))
43f68055976c5548b46d35e5da8cb0cfe7006b14
ZCT-512/Python-study-notes
/SectionB/part_2_modules/09_exercise_calculator.py
7,007
3.6875
4
# Author 张楚潼 # 2020/8/12 13:12 import re # # 计算二元运算式 def step_operation(short_str): """ 函数用来计算二元运算式,即a(+-*/)b,这个最底层的运算。 输入和返回值均为字符串类型。 a b 均可正可负,一共2*4*2=16种组合, 即支持"-1.2+-5.6", "-1.2--5.6", "-1.2*-5.6", "-1.2/-5.6 这些输入。 """ # 先处理 +-, --, *-, /- 四种情况 if re.findall("\\+-", short_...
150c6942f2f6cd1e33c9fec384c9d075a84250a5
polyglotm/coding-dojo
/coding-challange/leetcode/medium/147-insertion-sort-list/147-insertion-sort-list.py
866
3.6875
4
# 147-insertion-sort-list # leetcode/medium/147. Insertion Sort Listx # URL: https://leetcode.com/problems/insertion-sort-list/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(...
1268cf91d716456d637b92d7ef08fe9f3fb22e63
kristenphan/BinaryTreeTraversal_inOrder_preOrder_postOrder
/tree-orders.py
5,780
3.953125
4
# python3 import sys, threading sys.setrecursionlimit(10**6) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size # this class represents a node in a binary tree class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left ...
e5e5d4fe5c6737457c9e794cc1c09ed99a99096f
gabriellaec/desoft-analise-exercicios
/backup/user_370/ch46_2019_11_18_14_04_33_399646.py
422
3.71875
4
pergunta=input("Escreva uma palavra e caso queira parar digite 'fim': ") lista_palavras=[] while pergunta != "fim": lista_palavras.append(pergunta) pergunta=input("Escreva uma palavra e caso queira parar digite 'fim' ") print(lista_palavras) lista_final=[] i=0 while i < len(lista_palavras): if lista_...
1f3ec2d97b2a0a232d9bdaf64ff83d0b98e58eb7
GregPhi/l2s3
/Codage/TP6/repeat_three_times.py
2,984
4.4375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- def encode(byte): """ Encode the byte using repetition coding Parameters: byte (int) – The byte to encode Returns: A list of three bytes equal to byte Return type: list UC: 0 <= byte < 256 Examples: >>> encode(123) [123, 123, 123] >>>...
f474217c34b0dc6522f8137abe00cb0e4113b3e5
Malcolm314159/Python-math
/math6.py
321
3.921875
4
#math6 print("Hello World") #variables sum = 0 sum1 = 0 for i in range(1, 101): sum += i sum1 += i**2 square = sum**2 difference = square - sum1 print("The sum of the squares is "+str(sum1)) print("The square of the sum is "+str(square)) print("The difference between those two is "+str(difference)...
f43369fa6391d8d99698105f0e8716893cfbe44a
noorulameenkm/DataStructuresAlgorithms
/DynamicProgramming/longest_common_subsequence.py
1,224
3.8125
4
def maximum(a,b): return a if a > b else b def LCS(x,y,x_length,y_length): table = [[0 for i in range(x_length + 1)] for j in range(y_length + 1)] for i in range(y_length + 1): for j in range(x_length + 1): if i == 0 or j == 0: table[i][j] = 0 elif y[i-1] == ...
a582580bf78ae9efebdc7f4c86e73938e8559680
TaurusCanis/ace_it
/ace_it_test_prep/static/scripts/test_question_scripts/math_questions/Test_1/math_2/math_T1_S2_Q9.py
1,909
4.21875
4
import random trap_mass = random.randint(125,175) mouse_mass = random.randint(3,6) answer = trap_mass - (mouse_mass * 28) - 1 question = f"<p>The mass required to set off a mouse trap is {trap_mass} grams. Of the following, what is the largest mass of cheese, in grams, that a {mouse_mass}-ounce mouse could carry and...
739ea906e1f8acd0a43313e0b890a7937de11c2a
jeanpierrethach/Design-Patterns
/src/main/python/patterns/chain-of-responsability/chain_of_responsability.py
1,458
3.796875
4
from abc import ABC, abstractmethod class Handler(ABC): def __init__(self, balance): self._successor = None self._balance = balance def set_successor(self, handler): self._successor = handler def can_handle_request(self, amount): return self._balance >= amount def han...
14e8fc7a9b96ae38c48f8c13d709a4efd90f4300
saradhimpardha/Jupyter_notebooks_AMS
/Computer_Animation/Vorlesung_7/videofiledisp.py
571
3.53125
4
import numpy as np import cv2 import sys #Program to open a video input file in argument and display it on the screen. #command line example: python videofiledisp.py video.mts #Gerald Schuller, march 2015 cap = cv2.VideoCapture(str(sys.argv[1])) while(cap.isOpened()): ret, frame = cap.read() cv2.imshow('Vi...
e4f143b4bf52d56d26d34a228b4c5c987c66b02a
BotondSiklosi/Calendar
/cal.py
3,867
3.609375
4
import sys import ui # printing data, asking user for input import storage # saving and loading files MEETING_TITLE = 0 HOW_LONG = 1 STARTING_TIME = 2 def edit_meeting(table, items_to_edit): new_line = [] new_line_option_list = ["Enter a new meeting title", "Enter a new duration in hours (1 or 2)", "Enter ...
36382d14f4c5ba35d44a7a1e155235e9e3db7ce0
betelgeuse06/BrokenGoodac_CodingMaker
/BrokenStar/Rock Scissors Paper.py
626
3.796875
4
import random for i in range(5): num=int(input("0.가위 1.바위 2.보 중 하나를 선택하세요>>\n")) com=random.randrange(1,3) if num>2: print("잘못 누르셨습니다") elif num==com: print("비겼습니다") elif num+1==com or (num==2 and com==0): print("컴퓨터 승리") else: print("내가 승리") ...
b26ce85c9688fe09256d81394479544d895dfc5d
YoyinZyc/Leetcode_Python
/Google/Event Queue.py
1,356
3.921875
4
''' 设计一个event queue。 要求给 定一个event,判断在这个 event之前的一个固定时间段里 有没有出现大于k个event。 event可能是按时间顺序来也可 能是随机来 random: 用heap 顺序: 一个长度为k的queue,小于k,加入;大于k,弹出老的,放入新的 ''' import heapq from collections import deque class EventQueue(object): def __init__(self,k,time): self.queue = deque() self.k = k self.time =...
2612a1ba7a0ace3cf7083c1e143124702bc4ef72
TCavalcanti/JudgeCode
/listasDescompactadas/110066518/3.py
357
3.5625
4
if __name__ == '__main__': [x, y] =[int(i) for i in raw_input().split()] if x > y: maior = x menor = y else: menor = x maior = y lista = [k for k in range(menor, maior)] lista.append(maior) soma = 0 for x in lista: if x%13 != 0 : ...
278664fd2b898eabf50f4d5f37d4f03d7c3868df
vijayroykargwal/Infy-FP
/OOPs/Day1/src/Assign9.py
2,109
3.703125
4
#OOPR-Assgn-9 ''' Created on Mar 5, 2019 @author: vijay.pal01 ''' #Start writing your code here class Student: def __init__(self): self.__student_id = None self.__age = None self.__marks = None self.__course_id = None self.__fees = None def get_course_i...
9e4946435fcd7495435ea7fa168718b5a119fa79
ibbur/PCC
/bicycles.py
1,352
3.796875
4
# Aaron Frankel 2019-6-19 # The purpose of this file is to exercise lists bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) print(bicycles[0]) print(bicycles[0].title()) print(bicycles[1]) print(bicycles[1].title()) print("\n") print(bicycles[1].title()) print(bicycles[3].title()) ...
80771648ba45e3b7999f1f403e1b160769ac5ae4
sibylle69/CS50-Harvard-course-exercises
/sibylle69-cs50-problems-2020-x-readability/sibylle69-cs50-problems-2020-x-readability/readability.py
682
3.875
4
import math from cs50 import get_string def main(): string = get_string("Text: \n"); word = 0; ltrs = 0; stce = 0; i = 0; for i in range(len(string)): if string[i].isalpha(): ltrs += 1 elif string[i] == ' ': word += 1 elif string[i] == '!' ...
6ca5a677a76ff287e1edabfb46b6f898e5965492
dmnhwjin/Python
/leapYear.py
655
3.671875
4
#!c:\python\python.exe import sys import string if len(sys.argv)<2: print "Usage:leap.py year,year,year..." sys.exit(0) for i in sys.argv[1:]: try: y=string.atoi(i) except: print i,"Is not a year." continue leap="no" if y % 400 ==0: leap = "Yes" elif y %1...
449e1d30bea8359340dbeb02d69d6fb63dafbcd1
samlobel/PROJECT_EULER_SOLUTIONS
/064/solution.py
338
3.53125
4
""" So, 23: Between 4 and 5. 4 + (√23 - 4). √23-4 = 1.25.... so, 4, 1 1/(ans-1) = 3.89... 4,1,3 We've got some interesting stuff here. But the harder part is that we need to actually keep the actual symbolic solving, not the float. """ def solve(n, so_far, dict_so_far): i_n = int(n) b = 1.0/(n - i_n) ...
8fb8af942b244d181cb12f8b2abae188593beef7
Tejas-Naik/Tic-Tac-Toe
/main.py
3,841
4.09375
4
instruction_board = {'7': '7', '8': '8', '9': '9', '4': '4', '5': '5', '6': '6', '1': '1', '2': '2', '3': '3', } the_board = {'7': ' ', '8': ' ', '9': ' ', '4': ' ', '5': ' ', '6': ' ', '1': ' ', '2': ' ', '3': ' ', }...
17dc3dd3909a38ef5b2d6e95f8c6469ced70b0eb
Rhapsody0128/python_learning
/base/07.dictionary.py
5,032
3.859375
4
# 字典和json非常像,但是從本質上講,字典是一種數據結構,而json是一種格式; # 字典有很多內置函數,有多種調用方法,而json是數據打包的一種格式,並不像字典具備操作性,並且是格式就會有一些形式上的限制,比如json的格式要求必須且只能使用雙引號作為key或者值的邊界符號,不能使用單引號,而且“key”必須使用邊界符(雙引號),但字典就無所謂了。 # * 存取字典中的值 # 在python中字典是一系列的鍵-值對,每一個鍵都有一個對應的值,與鍵相關的可以是數值、串列、也可以是另一個字典,在python中字典是用大括號{ }括住一系列的鍵-值對,鍵和值之間是用冒號來分隔,鍵-值對之間是用逗號分開,如果想存取鍵相關的值,...
83fddeb3ea7d770e181922942213e691984b4182
JoamirS/Exercicios-Python
/Udemy/Class_02.py
255
3.71875
4
first_variable = 'Joamir' second_variable = 'Maria' third_variable = 'José' string = f'a={first_variable} b={second_variable} a={third_variable} c={first_variable}' formato = string.format(first_variable, second_variable, third_variable) print(formato)
0db2e16aac49991b2be1f3c3278593a37c728cdd
anmolrajaroraa/CorePythonMarch
/while_loop.py
375
4.3125
4
#choice = "" #while choice != "no": while True: num = int(input("Enter a number to check for odd and even : " )) if num == 0: print("Please don't enter 0") continue elif num % 2 == 0: print(num, "is even") else: print(num, "is odd") choice = input("Do you want to c...
3291e6be9dfadf357d7b9aa2dff94d9ec5bdcc70
wanax/Leetcode
/facebook/tree/199. Binary Tree Right Side View.py
1,110
3.5
4
''' Xiaochi Ma 2018-11-12 ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def rightSideView(self, root): dic = {} max_depth = -1 stack = [(root, 0)] while stack: ...
0dc7fbf2ac1bde319db1968a157746b77262c6de
williamlopez/Choose-Your-Own-Adventure-
/ChooseYourOwnAdventure.py
1,651
4.4375
4
# Choose.py # by [Marcos,William,Justin,Luis] # Description: starter code for the Choose Your # Own Adventure Project #asdlf;j # Import Statements from tkinter import * import tkinter.simpledialog import tkinter.messagebox root = Tk() w = Label(root, text="Choose Your Own Adventure") w.pack() def intro(): """ In...
3183d30be025bcaceaeeb62c6c0895d1c223db96
louisuss/Algorithms-Code-Upload
/Python/FastCampus/recursion/1074+.py
661
3.53125
4
def z_func(n, r, c): global number # 2가 최소값임 if n == 2: if r == R and c == C: print(number) return number += 1 if r == R and c+1 == C: print(number) return number += 1 if r+1 == R and c == C: print(number) ...
44689b280347835c761723ef508035ac81b1b646
valeriekamen/python
/palindrome.py
4,786
3.578125
4
import math """ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] Input: "aabaa" Output: [["a","a","b","a","a"],["a","a","b","aa"],["a","aba","a"],["aa","b","a","a"],["aa"...
6a685a0427854028c5541a13f18bdfcd0b9e2925
PuttTim/MundaneUnevenBug
/hour min.py
93
3.640625
4
hour=0 minute=0 for hour in range (11+1): for minute in range (59+1): print(hour, minute)
43db3d24815b7928657c03061650deb2fa687b5e
Jiangstte/treasure-house
/t2.py
498
3.6875
4
people = { 'lg' : { 'phone': '12345', 'add': '71905', }, 'lh' : { 'phone' : '23456', 'add' : '71904', }, 'lj' : { 'phone' : '34567', 'add' : '71903', }, } #jieshi = { #'p' : 'phone', #'a' : 'addres', #} name = raw_input('the name is:') request = raw_in...
45a82527d6560beaeb597f6c84a2d895aa67a527
davidlu2002/AID2002
/PycharmProjects/Stage 2/day18/thread_1.py
665
3.515625
4
""" thread_1.py 线程使用1 """ from threading import Thread from time import sleep import os a = 1 # 主线程的变量 def fun(): for i in range(3): print(os.getpid(),"运行程序1") sleep(2) print("程序1运行完毕") global a print("a =",a) a = 10000 # 分支线程内改变主线程的变量 # 创建线程对象 t = Thread(target=fun) ...
1d05e8ed17a6204a1355ce5c26b6bfdc040a781b
lexiaoyuan/PythonCrashCourse
/python_08_class/user.py
745
3.578125
4
class User(): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user(self): print(self.first_name) print(self.last_name) def greet_user(self): print("Hello," + self.first_n...