blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
f5db3390483024c448d23539a08648f714547d6a
Mshohid/Python-Misc
/bananarama.py
220
3.796875
4
import random banana = (random.randint(0,10)) print (int(banana)) if banana >= 5: print ("bunch is large") elif banana <5 and banana >0: print ("bunch is small") else: banana == 0 print ("No bananas")
a0361f8dcf052c07cc19ebb342338b16359a6153
daniel-reich/ubiquitous-fiesta
/BuwHwPvt92yw574zB_22.py
109
3.78125
4
def list_of_multiples (num, length): m = [] for n in range(1,length+1): m.append(num*n) return m
4dec737bd6f4f289517800ceb81f1107fb47e4a3
pusparajvelmurugan/ral
/104.py
98
3.828125
4
s=input("Enter 2 numbers:") num1=int(s.split(" ")[0]) num2=int(s.split(" ")[1]) print(pow(n1,n2))
b3dd8a6c559ce6ff1efa0037fb6de735ed3581e3
Nikhil483/ADA-lab
/selection_sort.py
272
3.671875
4
#selection sort def sel_sort(a): for i in range(0,len(a)-1): mini = i for j in range(i+1,len(a)): if a[j]<a[mini]: mini = j a[mini],a[i] = a[i],a[mini] print(a) a = [5,4,3,2,1] sel_sort(a)
86f5c9fcba0f68a28d3b489ae4455b223b70e3d1
valleyceo/code_journal
/1. Problems/j. DP/0. Template/a. Path - Optimal Path - The Pretty Printing Problem.py
1,326
3.921875
4
# The Pretty Printing Problem (need to review) ''' - Given a set of words to create a paragraph and max line length - Create a paragraph such that messiness is minimized - Messiness is measured by sum of number of blanks squared at end of each line ''' # O(nL) time | O(n) space def minimum_messiness(words: List[str], ...
e2e280168d33d4b04b3ff6b63d10233625b6b1a6
paulopradella/Introducao-a-Python-DIO
/Aula_4/Aula4_3.py
278
3.734375
4
# #Descobrir se é primo for dentro de for a = int(input('Entre com um valor')) for num in range(a + 1): div = 0 for z in range(1, num + 1): resto = num % z #print(z, resto) if resto == 0: div += 1 if div == 2: print(num)
6031c1ae9f5eeaab62c5b4eb2aa6706b4c60470d
Jinah-engineer/j-python-practice
/doit_python/chapter02/1-1_string_operator.py
386
3.9375
4
# 문자열 더해서 연결하기 (Concatenation) head = 'python ' tail = 'is fun!' print(head + tail) # 문자열 곱하기 a = 'python' print(a * 2) # 문자열 곱하기 응용 --> 프로그램 제목을 출력할 때 이런 형식으로 많이 표기한다 print('=' * 50) print('my program~!') print('=' * 50) # 문자열 길이 구하기 a = 'Life is too short' print(len(a))
5e69c76323df044d373e8f04d0f0761bc3292b52
rajatthosar/leetcode
/108_sorted_array_to_BST.py
732
3.796875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedArrayToBST(self, nums: list) -> TreeNode: if not nums: return med = len(nums) // 2 ro...
c1be493a0e506e3c2113d18cfe3780a63f006ff7
tinitiate/python-machine-learning
/scatter-plot.py
1,346
3.703125
4
import matplotlib.pyplot as plt import numpy as np import scipy, pylab """ # Creating a Scatter Plot # ----------------------- marker=['O','X','^'] plt.scatter( [1,2,3] ,[4,5,6] ,500 ,color=['red','green','blue'] ,marker) plt.scatter( [1,2,3,4,5,...
4c6a59f06913429f9c4615518e726307dab0254d
czhang475/molecool
/molecool/visualize.py
3,809
3.6875
4
""" Module containing functions for visualization of molecules """ import numpy as np import matplotlib.pyplot as plt from .atom_data import * def draw_molecule(coordinates, symbols, draw_bonds=None, save_location=None, dpi=300): """ Draws a picture of a molecule using matplotlib. Parameters --------...
3bfecdd5b707737218985a13c24bd3f4ae4521b2
vsamanvita/APS-2020
/Amicable_pair.py
475
3.609375
4
import math def getfact(n) : c = 0 d=[] for i in range(1,math.floor(math.sqrt(n))+1) : if n%i == 0 : if n/i == i : d.append(i) else : d.append(i) d.append(int(n/i)) return(sum(d)-n) def amicable(a,b): ...
d6085813aae65d87ff8ae0e33ab801e856a180ba
johnakitto/project_euler
/euler_004.py
287
3.515625
4
import time start_time = time.time() biggest = 0 for n1 in range(100,1000): for n2 in range(n1,1000): x = n1 * n2 if str(x) == str(x)[::-1]: if x > biggest: biggest = x print() print('solution: '+ str(biggest)) print('runtime: %s sec' % (time.time() - start_time)) print()
81c27a304811a75e046d26c78a0f55df28937a70
JRappaz/Panorama
/notebooks/utils/visualization.py
2,456
3.5
4
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import matplotlib.dates as mdates import seaborn as sns import pandas as pd def plotTweetPerDay(df, title, rolling_window=1, vertical_line_x=None, vertical_line_label="", col_count="published", interval=2): # Prettier plotting with seaborn ...
6b3752fd45300fe40db80b0ba1b8022450ac3af4
karolisdedele/password_generator
/password_generator.py
1,435
4.09375
4
import random import string def pw_generator(): password_length=int(input("How long will your password be? ")); i=0; password=[]; while (i<password_length): i+=1; rand_num_for_if=random.randint(0,100); if(rand_num_for_if%2==0): number=random.randint(0,9); password.append(str(number)); ...
8c60f7e892cb5147183a0ba2645a65a226322f05
Ramanagamani1/Pythoncourse2018
/unit4tests/factormath.py
907
3.53125
4
def get_hcf(list1,list2): res=[] list1.extend(list2) list1.sort() for i in range(len(list1)-1): if list1[i][0] == list1[i + 1][0]: if list1[i][1] < list1[i + 1][1]: res.append(list1[i]) return res def get_lcm(list1,list2): list1.extend(list2) ...
161fc96025d8d227a4e8b51e9c63be26d7552513
tHeMaskedMan981/coding_practice
/theory/data_structures/trie/prefix_set.py
1,068
3.53125
4
import collections class Node(): def __init__(self): self.c = [None]*10 self.end = False root = Node() def insert(key): l = len(key) p = root for i in range(l): index = ord(key[i])-ord('a') if not p.c[index]: p.c[index] = Node() p ...
4e4cd98efb1d900ccf422339aa54513a22580f9c
RuzhaK/PythonOOP
/SOLID/SudentTaxes.py
661
3.640625
4
from abc import ABC,abstractmethod class StudentTaxes(ABC): def __init__(self,name, semester_fee,average_grade): self.average_grade = average_grade self.semester_fee = semester_fee self.name = name @abstractmethod def get_discount(self): pass # if self.average_grade>=...
30f96056447ecfd52f7e2d7ca7d854a064a9bf28
rshatkin/python_eightball
/magic8ball_new.py
337
3.546875
4
import random NO_QUESTION = "" OUTCOMES = open("outcomes.txt", "r").readlines() while True: question = raw_input( "Ask the magic 8 ball a question: " + "(type question and press enter or just enter to quit) ") if question == NO_QUESTION: break print OUTCOMES[random.randint(0, l...
bf91c775632d433032c33f01d96481ba8ce0ad34
aguerra/exercises
/dynamic_programming/finonacci.py
777
3.875
4
""" f(0) = 0, f(1) = 1 f(n) = f(n-1) + f(n-2) """ from functools import cache @cache def memoized(n): """Return the nth Fibonacci number. >>> memoized(0) 0 >>> memoized(1) 1 >>> memoized(2) 1 >>> memoized(5) 5 >>> memoized(9) 34 >>> memoized(17) 1597 """ ...
471580a6943a2febdd9ecb587d6385a91637233a
weak-head/leetcode
/leetcode/p0124_binary_tree_maximum_path_sum.py
598
3.578125
4
import math class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def maxPathSum(root: TreeNode) -> int: """ Time: O(n) Space: O(h) n - number of nodes h - max height of the tree """ m = -...
90c864f595292f9a93b8961f570155ce53ae0524
EdwardDixon/floods
/floodstats.py
712
3.890625
4
#!/usr/bin/python import pandas as pd mydf = pd.read_csv('data/number-of-severe-floods-in.csv', names = ["Year", "Severity"], skiprows=1) print("Dataframe content:") print(mydf) print("Select minimum value row:") min = mydf['Severity'].min() min_df = mydf.loc[mydf['Severity'] == min ] print(min_df) print("Select ...
5a43fa12fb9f8a0fce81e60f130f57035d04e11b
lernerbruno/python-trainning-itc
/Pycharm and debuging/encrypt_for_decrypt_1.py
406
3.703125
4
""" Encryptor for the decrypt_1 exercise Author: Omer Rosenbaum """ from random import randint MY_SECRET = "I used something else..." def encrypt(string): encrypted = "" for character in string: offset = randint(0, 9) encrypted += str(offset) encrypted += chr(ord(character...
695355269bae1334c7370ee5b99c7d67aa1fc42b
ShanYouGuan/python
/Algorithm/bubble_sort.py
286
4.125
4
def bubble_sort(list): for i in range(0, len(list)): for j in range(len(list)-i-1): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] lista = [1, 3, 6, 5, 4, 2] bubble_sort(lista) for i in range(0, len(lista)): print(lista[i])
95e7968efdc592dd82766198ec2372d2d7bff212
Nagendra-NR/HackerRank_Python
/Collections/Counter.py
623
3.515625
4
from collections import Counter earning = 0 #First line = X = number of shoes X = int(input()) #Second line = list of all shoe size in shop shoe_size_list = list(map(int, input().split())) shoe_size_count = dict(Counter(shoe_size_list)) #print (shoe_size_count) #third line = N = number of customers N = int(input()) ...
7a6b240cf7b97ed04685ce9b86910d3ee79c24c7
PullBack993/Python-OOP
/6.Polymorphism - Lab/2.Instruments.py
494
3.96875
4
# class Guitar: # def play(self): # print("playing the guitar") # # def play_instrument(instrument): # return instrument.play() # # guitar = Guitar() # play_instrument(guitar) from abc import ABC, abstractmethod class Instrument(ABC): @abstractmethod def play(self): pass def play_...
60506356d9c2afd1b97cf8cbfefb884e5bcc371b
Beishenalievv/python-week-sets_2020
/3/slash_figure.py
456
3.875
4
h = 22 s = '\\' m = 0 s1 = '/' m1 = 0 for _ in range(6): print(s * m, end='') m += 2 for _ in range(h): print("!", end='') print(s1 * m1, end='') m1 += 2 print('') h -= 4 h = 22 s = '\\' m = 0 s1 = '/' m1 = 0 for _ in range(6): print(s * m, end='') ...
e5b43f3a7a837869c5805787002a38385ee89308
oussamafilani/Python-Projects
/list_nombres_premiers.py
240
3.671875
4
n = int(input("entre un nombre ")) for i in range(2, n) : premier = True for j in range(2, i) : if i % j == 0 : premier = False break if premier: print(i)
87c28d3d584fd70dc995d4a4958da77b3bd6e9ff
ProgFuncionalReactivaoct19-feb20/clase02-Shomira
/Ejercicios/ejemplo4.py
394
3.96875
4
#Ejemplo y ussus del lambda #Cada elemento de datos, tiene(edad, estatura) datos = ((30, 1.79), (25, 1.60), (35, 1.68)) #Funcion anonima Lambdab que recoge la posicion 2 dato = lambda x: x[2] #Funcion anonima Lambdab que recoge la posicion 0 edad = lambda x: x[1] *100 ''' Envio de parametros a las funciones realiza el...
1ad74249d657b1a98c9aa4b55b0efd5569603c9f
friessm/math-puzzles
/p0010.py
966
3.765625
4
""" Solution to Project Euler problem 10 https://projecteuler.net/problem=10 """ def sieve_of_eratosthenes(number): """ Sieve of Eratosthenes Return the sum of all prime numbers from 2 to number. Standard implementation of Sieve with some optimisations. https://en.wikipedia.org/wiki/Sieve_o...
c784c74ddd750cc8ba50a077e1f8dea84691b6d2
vltian/some_example_repo
/lesson_3_func/hw_34.py
711
3.984375
4
"""4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. """ def my_func(x, y)...
49293a74b1b01fdce9183dbf36f15c753d5c92d6
jashby360/Python-Playground
/PythonEx2/ch5.20.py
580
3.75
4
print("Patter A") for i in range(1, 7): for j in range(1, i + 1): print(j, end=" ") print() print("\nPatter B") for i in range(6, 0, -1): for j in range(1, i + 1): print(j, end=" ") print() print("\nPatter C") for i in range(1, 7): num = 1 for j in range(6, 0, -1...
4427195e4cf1aff71fb33206cce1af7c86497943
Fernando-Psy/geekUniversity
/secao4/10-km_para_metros.py
330
4.03125
4
while True: try: km = float(input('Digite a velocidade (Km/h): ')) m = km / 3.6 #formula de conversão except ValueError: print('Digite apenas valores númericos...') else: print(f'Quilômetro/hora: {km} km/h') print(f'O mesmo em metros por segundo: {m:.2f} m/s') ...
2bdeb07f4ad64c682c35dda4b5de9b0846f72bfe
ljragel/Learning-to-program-with-Python
/store_names_and_dates of births.py
922
4.15625
4
""" Crea un programa que sea capaz de guardar los nombres de tus amigos y sus años de nacimiento. """ #Hay algún tipo de bug qye hace que la primera persona no funcione toma el valor del dato de la segunda persona works = False data = dict() while not works: user_action = input("¿Qué deseas hacer? [Añadir fech...
d2855098e3552080412f6d0cdeba4c17c2ad76a0
arunatuoh/assignment-code
/factorial_of_no.py
144
4
4
def factorial_of_no(n): if (n == 1 or n == 0): print(1) else: n=int(input("enter a number:")) factorial_of_no(n)
01076f5e926d04df688fbc91a433fb676adff806
qiuyuguo/bioinfo_toolbox
/coursework/online_judge_practice/lintcode/validate-binary-search-tree/non-recursive version.py
962
4
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if the binary tree is BST, or false """ def isValidBST(self, root): # write...
88e6eb03eb1716384b8da4697bfac89ddf2b0ddd
Jackroll/aprendendopython
/exercicios_udemy/Orientacao_Objetos/agregacao/classes.py
1,158
3.984375
4
#Agregação #Class CarrinhoDeCompras existe serm a classe Produto, mas precisa da classe produto para funcionar perfeitamente class CarrinhoDeCompras: def __init__(self): self.produtos = [] #Insere um produto que já esta cadastrado na classe Produto def inserir_produto(self, produto): s...
fd8f51c528251b27037342270ddd15a916fcab16
ALSchwalm/sparqllib
/sparqllib/formatter.py
1,625
3.515625
4
import abc import re class Formatter: @abc.abstractmethod def format(self, query): ''' Should return a human-readable version of the query string ''' pass class BasicFormatter(Formatter): ''' Provides a basic default formatting for query strings This formatter provides only in...
5e3de29a8c0909a5e6f2650893554653feba9b5e
standrewscollege2018/2019-year-13-classwork-padams73
/functions.py
298
4.34375
4
def is_even(check_number): """ This function calculates whether a number is even, returning True or False""" if check_number % 2 == 0: return True else: return False number = int(input() if is_even(number)==True: print("Even") else: print("Odd")
31d4f52fa1ec86895955a341d239736f0ca269d9
harshita219/PythonPrograms
/smoothing.py
1,051
4.28125
4
""" The temperature of the air is measured each hour so that after several days a long sequence of values is obtained. This data is required to be more smooth to avoid random jumps in values. To achieve this, every value is to be substituted by the average of it and its two neighbors. For example, if he have the sequen...
7d49b80275ac4e1dc826696d915f0e4fe1aa1669
zcliang97/toy-social-media
/startClient.py
4,274
3.625
4
from Client import Client def login(client): while True: print 'WELCOME TO SOCIAL MEDIA' # LOGIN/CREATE USER print "===== To create user [0]" print "===== To login to existing user [1]" action = raw_input() if action == "0": firstNam...
933edf9c38f2ded226269e851ada79c5e859d7be
krishna9477/pythonExamples
/CountRepeatedCharactersFromAString.py
437
3.875
4
x = input("enter a string:") dic = {} for chars in x: dic[chars] = x.count(chars) for keys, values in dic.items(): print(keys + " " + str(values)) """ # Count Repeated Characters From A Given String. import collections str1 = 'theeeLLLLL23567744444' d = collections.defaultdict(int) for c in str1: ...
685f6aed5e002c3d8f7db87072e44b7b8294dc39
bastoche/adventofcode2017
/day_2.py
2,159
3.578125
4
def part_one(input): return sum([max_difference(line) for line in parse(input)]) def max_difference(numbers): return max(numbers) - min(numbers) def parse(input): return [to_number_list(line) for line in input.splitlines()] def to_number_list(string): return list(map(int, string.split())) def pa...
68b8ebe6731f0263e6d97093b18129303a031edc
CQCL/pytket
/examples/python/circuit_generation_example.py
11,156
3.578125
4
# # Circuit generation: tket example # This notebook will provide a brief introduction to some of the more advanced methods of circuit generation available in `pytket`, including: # * how to address wires and registers; # * reading in circuits from QASM and Quipper ASCII files; # * various types of 'boxes'; # * compos...
aafe9a829b0d8898e985e86c33c1850ce0f10855
TVareka/School-Projects
/CS_162/Project 8- Decorator Functions/sort_timer.py
2,737
4.34375
4
# Author: Ty Vareka # Date: 5/18/2020 # Description: This program creates a decorator function and then calls bubble count/insertion count within that # decorator function. The decorator allows us to see how long it takes to run either bubble or insertion count. We # then have a function that compares those times...
b8823df15aace81d2910453dd39aa5a3e47cfbea
MRosenst/MyProjectEuler
/pe14.py
512
3.8125
4
def collatz(n): count = 1 while n != 1: if n % 2 == 0: n /= 2 else: n = n * 3 + 1 count += 1 return count def main(): largestCount = 0 largestNum = 0 for n in range(1000000, 1, -1): count = collatz(n) if count > largestCount: ...
4f3f90017e6a637a040a09ef2560bd24bbc0de08
samwestwood/advent-of-code
/2016-python/1.py
912
3.546875
4
#!/usr/bin/env python3 """ Advent of Code 2016 solution - part 1 """ import os.path DIR_NAME = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) FILE_NAME = open(DIR_NAME + "/2016-inputs/1.txt") FILE_LINE = FILE_NAME.readline() DATA = [str.strip(x) for x in FILE_LINE.split(',')] def solve(data): """R...
e25443f6bb23b3cb39630f9160ab38a2b0a0055e
DrZaius62/LearningProgramming
/Python/Scripts/countCharacters.py
546
4.15625
4
#this is a file to count the number of characters in a string #using the method dictionary.setdefault() import pprint message = 'It was a bright cold day in April, an the clocks were striking thirteen.' count = {}#creates the empty dictioanry count for character in message: count.setdefault(character, 0)#adds eac...
4cf7d99a87c99f55ea5dd565043f6d3c6ad7aac9
Pavel-Kravchenko/Python-scripts-for-everything
/HW/Kravchenko_pr7_hello.py
136
3.796875
4
a = "What is your name?" print a inp = raw_input("Write your name and press Enter") b = str(inp) c = "Hello," d = "!" print c, b,d
66ee6533b021b4567f9a772bbbb11843278a30dd
intmod/learn_tensorflow_by_MNIST
/mnist-1_0-fullconn-1layer.py
3,301
3.5
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # https://www.tensorflow.org/get_started/mnist/...
fa210f5a0358dd08b9e23365be85bcbf858790cb
jhn--/sample-python-scripts
/python3/thinkcs-python3/4-functions.py
271
3.734375
4
#! /usr/bin/env python import turtle def draw_square(t, sz): for i in range(4): t.forward(sz) t.left(90) wn = turtle.Screen() wn.bgcolor("light green") wn.title("wn blahblahblah whatever") alex = turtle.Turtle() draw_square(alex, 50) wn.mainloop()
afeb387efef9ca580f613210e5c9040fb76c0e7d
Rwothoromo/hashcode
/2020/slice_practice/slice.py
1,550
3.78125
4
import sys def knapsack(items, capacity): selected_pizzas = [] possible_count = 0 for item in items: if item not in selected_pizzas: possible_count += item selected_pizzas.append(item) if possible_count > capacity: # print(possible_count, select...
d679f98babceb7f11c6c7d75947f29757f5a5d68
ziaurjoy/Python-w3Schools
/Python_Loops/foor_loop.py
542
4.125
4
fruits = ["apple", "banana", "cherry"] # for i in fruits: # print(i) # # country = "Bangladesh" # for i in country: # print(i) # break statement fruits = ["apple", "banana", "cherry"] for i in fruits: if i == "banana": break else: print(i) # continue statement fruits = ["apple", "bana...
85f5c1062e54bed0d4ed0be893101deeaee1ce5b
Runnrairu/record
/ball.py
621
3.625
4
# coding: utf-8 # 自分の得意な言語で # Let's チャレンジ!! import math def o_mod(x,y): if math.fmod(x,y) <0: return math.fmod(x,y)+y else: return math.fmod(x,y) a,b,x,y,r,theta,L=[int(i) for i in raw_input().split()] theta = theta/360.0*2*math.pi X = L*math.cos(theta)+x-r Y = L*math.sin(theta)+y-r a_num = ...
9440d82168abd78397fd503d1cbd452f3cd37c17
nekapoor7/Python-and-Django
/SANFOUNDRY/Basic Program/Sum Digits.py
280
4.21875
4
"""Python Program to Find the Sum of Digits in a Number""" """Python Program to Count the Number of Digits in a Number""" num = int(input()) sum = 0 count = 0 while num > 0: digits = num % 10 sum = sum + digits num = num // 10 count += 1 print(sum) print(count)
2c43581eec95f3d036b77e12fe7211cf3639831b
Shred18/Notes
/zero to hero python bootcamp/Helpful_Syntaxes.py
601
4.3125
4
#This is the sytax for asking for an input, and if the input #is incorrect, you will return a statement saying so (using try/except) def ask_for_int(): while True: try: #this is trying the input result = int(input("Please provide a number: ")) except: #if the i...
1bc3dbad20f4364f367f61b2421e1c30197ff2ae
Tabsdrisbidmamul/PythonBasic
/Chapter_7_user_inputs_and_while_loops/02 restaurant_seating.py
441
4.5
4
# a program that asks the user how many are dining tonight message = 'How many are dining today? ' # convert the inputted numerical value into a integer dining_group = abs(int(input(message))) # a statement to see if the amount wanting to dine is more than 8, # then print said message, otherwise print this message if ...
0a5288fad2549177222ac402f6892a5950eb1b71
NoroffNIS/Python_Examples
/src/week 1/day 2/debug.py
216
3.9375
4
user_name = input('What is your name? : ') print('Hello,', user_name, '!') number_one = input('Type in a number: ') number_two = input('Type in a number: ') print('The number is:', number_one, 'and', number_two)
aa4533e8ec6a3afa8b4273506db8a79ae27506ec
pavanpandya/Python
/OOP by Telusko/08_Mutlilevel_Inheritance.py
1,257
4.15625
4
# Inheritance = Parent-Child Relationship '''MULTI-LEVEL INHERITANCE''' # IN THE EXAMPLE BELOW: # CLASS A IS SUPER CLASS OR GRAND-PARENT CLASS, # CLASS B IS SUB CLASS OR CHILD CLASS OF A AND PARENT CLASS OF C, # CLASS C IS SUB CLASS OR CHILD CLASS OF B. class A: def feature1(self): print("Feature-1 is ...
46323fecf5c03404d61d773ec57cfb6300957eaf
candyer/leetcode
/constructArray.py
1,260
3.65625
4
# https://leetcode.com/problems/beautiful-arrangement-ii/description/ # 667. Beautiful Arrangement II # Given two integers n and k, you need to construct a list which contains n different positive integers ranging # from 1 to n and obeys the following requirement: # Suppose this list is [a1, a2, a3, ... , an], the...
5acde7d8537eee221bb0125e03751f5deb28f9b4
JunaidQureshi05/FAANG-ques-py
/19_validate_binary_search_tree.py
607
3.921875
4
# O(n) Time | O(d) Space Where d is the depth of BST(Binary search tree) def validate_binary_search_tree_helper(node,min,max): if node.value >=max or node.value <=min: return False if node.left: if not validate_binary_search_tree(node.left, min, node.value): return False if node...
5578c01722dc64115300a3fedfbcbeaab2dd5497
karuparthijaswanth/python
/game.py
753
4
4
import random n=str(input("enter your choice :")) l=["STONE", "PAPER", "SCISSOR"] m=random.choice(l) print(m) if (n=="STONE" and m=="PAPER"): print("COMPUTER WINS") elif(n=="STONE" and m=="SCISSOR"): print("YOU WINS") elif(n=="STONE"and m=="STONE"): print("MATCH DRAW!!!!") elif(n=="PAPER" and m=="SCI...
a7d45e0f44b5e8e956cfbf04ddc86d346d668b4e
Johndsalas/decoding_activity
/group2.py
326
3.5625
4
def multiply_letters_decryption(message, multiplier = 5): count = 0 new_message ='' for letter in message: if letter.isalpha(): count += 1 if count % multiplier == 0: new_message += letter else: new_message += ' ' return new_m...
6ace89cd4aa4db6d65f2953269ffa5df501d9181
XiangHuang-LMC/ijava-binder
/CSC276/book/ch04-OOP-code/ABA_OOP_A.py
615
4.15625
4
#ABA_OOP_A.py: very simple object-oriented design example. # Entry and non-persistent storage of name. def addressBook(): aba = ABA_OOP_A() aba.go() class ABA_OOP_A: def go(self): book = [] name = input("Enter contact name ('exit' to quit): ") while name != "exit": ...
d158efb52c1d979489aad3a74ef934d79340346c
saksham715/Hacktoberfest2020
/multiThreading.py
645
3.96875
4
from time import sleep from threading import Thread class Hello(Thread): def run(): for i in ramge(5): print("Hello") sleep(1) class Hi(Thread) def run(): for i in range(5): print("Hi") sleep(1) hello = Hello() hi = Hi() hello.start() sleep(0.2) hi.start() hello....
7670e6e3fc6c1ebc6d770ad5088680424e18ea4f
dominicflocco/CSC-121
/quiz_6.py
3,581
4.125
4
""" Solutions to the programming problems from quiz #6. Author: Dominic Flocco """ def simon_says(instructions): """ Returns the instructions that would be obeyed in a game of Simon Says. Parameters: instructions - a list of strings, where each element is an instruction i...
eb145a00ef7828173d55f742d1e0421942267980
LeoGraciano/python
/ERRO leia float.py
970
3.734375
4
from os import replace def leiaint(MSG): while True: try: V = int(input(MSG)) except (ValueError, TypeError): print("\033[31mERRO!! Digite um valor inteiro valido\033[m") except KeyboardInterrupt: print("\nUsuário preferiu não digitar o valor")...
649f71472d0c68efd9c46dd3004d073b1649426c
Zahidsqldba07/PythonExamples-1
/for_loops/descarta2.py
553
3.65625
4
# coding: utf-8 # Aluno: Héricles Emanuel # Matrícula: 117110647 # Atividade: Descarta coincidente descartados = [] aceitos = [] qtd_numeros = int(raw_input()) for i in range(qtd_numeros): descarta = False num = raw_input() for n in range(len(num)): if int(num[n]) == n: descarta = True if descarta: descarta...
d86f1ff3a12683b6b76979f53494d9faccfb5c66
kristjan/turtle
/chaos_triangle.py
1,146
3.828125
4
#!/usr/bin/env python3 import math import random import sys import turtle SCREEN_WIDTH = 800 SCREEN_HEIGHT = 800 TRIANGLE_SIZE = 10 screen = turtle.Screen() screen.setup(SCREEN_WIDTH + TRIANGLE_SIZE*4, SCREEN_HEIGHT + TRIANGLE_SIZE*4) t = turtle.Turtle() def halfway(a, b): return ( (a[0] + b[0]) / 2...
200951dcb80a93c07f7977e6e3ded87a7fd904f1
AnhellO/DAS_Sistemas
/Ene-Jun-2022/adrian-led-vazquez-herrera/practica_5/P5_2_1.py
872
4.21875
4
#DAS Práctica 5.2.1 from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def num_of_sides(self): pass class Triangle(Polygon): def __init__(self): self.sides=3 def num_of_sides(self): return self.sides class Square(Polygon)...
c3a49ba9a3ddfeb78b1c2cb2ef10132a3800d1e6
edrielleduarte/jogo-senha-porta-magica
/main.py
1,202
3.703125
4
from jogo_porta_magica import saudacoes, novo_jogo, checagem_palpite_user, palpite_em_int def main(): global resposta_palpite import numpy as np saudacoes() contador = 0 rodadas = 7 # Quantidade de rodadas segredo_senha = np.random.randint(1, 101, 1) print(segredo_senha) while cont...
9595ee35f3107ded429592e17972964e95f6b06e
Abhishek-IOT/Data_Structures
/DATA_STRUCTURES/DSA Questions/Strings/wordbreak.py
899
4.1875
4
""" Word Break Problem | DP-32 Difficulty Level : Hard Last Updated : 02 Sep, 2019 Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, als...
c666446d187973b4361711a5e64baddf0ed0d245
wjzz/dev-notes
/numerical_analysis/exp/calc_e.py
913
3.609375
4
import decimal import math from decimal import Decimal math_e = math.e # taylor series # # e := sum (k = 0 -> inf) [1 / k!] # we reach the limit of the float type # after 20 iterations, ie. n_20 = n_21 = n_22 = ... def taylor_e(): approx = 0 term = 1.0 k = 0 while True: approx += term ...
db027d14b1995a2ab088ae4bbbbec03544d1d800
JaiJun/Codewar
/7 kyu/Duplicate sandwich.py
919
3.984375
4
""" Task: In this kata you will be given a list consisting of unique elements except for one thing that appears twice. Your task is to output a list of everything inbetween both occurrences of this element in the list. I think best solution: def duplicate_sandwich(arr): start, end...
145b747adc42a57710acadb702f1adae4c2930a8
RammasEchor/google-code-jam
/solutions/reversort/python/reversort_cost.py
1,155
3.6875
4
class Case: def __init__(self, list_length, my_list): self.list_length = list_length self.my_list = my_list self.cost = 0 def compute_cost(self): for i in range(self.list_length-1): min_idx = self.my_list.index(\ min(self.my_list[i:])) ...
1825cedf6b5555874a29518ec0aa4decca595115
nikk7007/Python
/Exercícios-do-Curso-Em-Video/51-100/074.py
443
3.8125
4
from random import randint numbers = (randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9)) # menor = maior = numbers[0] # for i in numbers: # print(i, end=' ') # if i > maior: maior = i # elif i < menor : menor = i # maior = sorted(numbers)[4] # menor = sorted(numbers)[0]...
e911ef50f4032187cce28661ea5d39a37465e00a
Sajid16/World-of-Python-and-Machine-Learning
/Basic_python_Practice/ifCondition.py
802
4.3125
4
print("Enter the average number:\n") # taking input here a = input() # converting input from string to integer a = int(a) a = a+2 # a = 80 if a >= 80: print('Congratulations!\nYou have got A+') elif a>=75: print('Congratulations!\nYou have got A') elif a >= 70: print('Congratulations!\nYou have got A-'...
992c7ad24e7f61d466eb2a9672c4782e24c2c06b
dg5921096/Books-solutions
/Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/P9_21.py
1,395
3.515625
4
# After closing time, the store manager would like to know how much business was # transacted during the day. Modify the CashRegister class to enable this functionality. # Supply methods getSalesTotal and getSalesCount to get the total amount of all sales # and the number of sales. Supply a method resetSales that reset...
eb2047aa7d10feeedd14582b29b077085c19a350
kwahome/udacity-robotics-ai
/particle-filters/moving_robot.py
710
3.890625
4
# Make a robot called myrobot that starts at # coordinates 30, 50 heading north (pi/2). # Have your robot turn clockwise by pi/2, move # 15 m, and sense. Then have it turn clockwise # by pi/2 again, move 10 m, and sense again. # # Your program should print out the result of # your two sense measurements. # # Don't modi...
1cc8e8cac3b792be5c31b1bc5ec5e9a5387ed0f1
khasherr/SummerOfPython
/RecursionFirstIndexNumber.py
1,775
3.78125
4
#Sher #This program finds the first occurence of a numver in list # Test 0 - false 1 - true # def FirstIndex (arr, number): # l = len(arr) # #means if the list is empty # if l == 0: # return 0 #if array at 0th index is the number we want t find then return the number # if arr[0] == numbe...
498e4cf78103cd8493a2f67c30a887f07113e858
mashikro/code-challenges
/ll_prac.py
795
4.125
4
# Make a Node class class Node(object): def __init__(self, data): self.data = data self.next = None def __repr__(self): return "<Node: {}>".format(self.data) # Make some instances of Node apple = Node('apple') print(apple) berry = Node('berry') cherry = Node('cherry') apple.next=be...
6ea72479a9dd87c7a9041c05eea473165ed5e67d
spencer-mcguire/Algorithms
/eating_cookies/eating_cookies.py
1,171
4.1875
4
#!/usr/bin/python import sys # The cache parameter is here for if you want to implement # a solution that is more efficient than the naive # recursive solution def eating_cookies(n, cache=None): # fib setup fn = f(n-1) + f(n+2) # __base_case__ # if n = 1 return 1 # if n = 0 return 0 if cache is ...
f139edcf5d24c0824b560d616fbb814f950c5c3b
fjoalland/metaheuristic-project
/fonctions/population.py
6,047
3.578125
4
import csv import pandas as pd import random import parametre as parametre #********************************** #******GENERER UNE POPULATION****** #********************************** def genererPopulation(taille): #Contiend la liste de tous les individus d'une nouvelle population nouvellePopulationListe = [] #O...
6e60b1b7e655d928edbdfd344ff96740e15d1713
rohitgupta24/leetcode
/sliding_window.py
402
3.59375
4
def max_sum(arr, k): size = len(arr) if size < k : print("Invalid Operation") return -1 window_sum = sum([arr[i] for i in range(k)]) max_sum = window_sum for i in range(size-k): window_sum = window_sum - arr[i] + arr[i+k] max_sum = max(window_sum,max_sum) ...
f1efb98f221fd4693d1e913f0c95037a1228f002
marcoscarvalho9/LusofonaPG
/moo_Exercicio 4.py
736
4.21875
4
#!/usr/bin/python3 # coding: utf-8 # Exercício 4 # * Criar um programa que consiga gerar uma password aleatória, com os seguintes parâmetros: # - Tamanho da password (entre 8 a 32 caracteres, deve pedir input ao utilizador) # - Uppercase and Lowercase # - Caracteres especiais # - Digitos # Requisitos Exercício 4: # *...
3bafbd62c535571dc037b99979296c1dafd4496f
FranciscoGMercado/generala
/funciones.py
378
3.765625
4
# 1 el print va dentro del def # 2 append para pasar los nombres a una lista vacia. # Funciones. def jugadores(): j = [] #J por jugadores. n = int(input('Ingrese el numero de jugadores para esta partida: ')) for i in range(0,n): jugador = str(input('ingrese el nombre del jugador: ')) j.app...
4761367dbc60327f3b3aa447e1270b0926d49807
inwk6312winter2019/openbookfinal-nayakdrashtant
/task15.py
724
3.546875
4
# Sub task 5 of Task 1 mydict = dict() def histgram(Book): fopen = open(Book,"r") for re in fopen: re = re.strip() re = re.split() if len(re) != 0: for r in re: r = r.lower() if r[:1] == 'a' or r[:1] == 'e' or r[:1] == 'i' or r[:1] == 'o' or r[...
8982b717b4eb1817e64ce6186a7db6736a721b11
ahnaf-zamil/async-covid
/example.py
1,786
3.78125
4
# -*- coding: utf-8 -*- """Sample example used for testing purposes """ from async_covid import Covid import asyncio async def johnhopkinsdata(covid): print("John Hopkins University data\n\n") deaths = await covid.get_total_deaths() confirmed = await covid.get_total_confirmed_cases() recovered = awai...
16bff159d8119a16b112225ee9012fa0a621c7a3
M1c17/ICS_and_Programming_Using_Python
/Week4_Good_Programming_Practices/Lecture_4/get_stats.py
888
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 19 18:39:17 2019 @author: MASTER """ # assume were given a class list for a subject: each entry is a list of two # parts # a list of first and last name for a student # a list of grades on assigments # create a new class list, with name,grades, a...
1a3fd6329adff58c2d03aae2922f458873ce5e17
JuanPuyo1/8_Puzzle_DLS_DFS_BFS
/Busquedas_API.py
5,511
3.8125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Busquedas.py Es una API que se podra utilizar en diferentes proyectos que este en la misma ruta de esta #con el fin de poder acceder a los metodos de construcción de las estructuras de datos usados en las #busquedas de solución informadas y no informadas # Definición...
842b4b0ffe713a4aa1a6c9929ac82fc169a06d4e
goutam1206/DataScienceMasters_Assignment4.1
/Assignment4.1.py
1,146
3.640625
4
class Shape: def __init__(self, a,b,c): self.a = a self.b = b self.c = c self.sides=[] def setsides(self): self.sides = [self.a,self.b,self.c] return self.sides class Triangle(Shape): def __init__(self,a,b,c): Shape.__init__(self...
d19e1b5c7b3e7d8552b972fba628157dbe77f79e
kunzhang1110/COMP9021-Principles-of-Programming
/Labs/Lab_7/test.py
414
3.71875
4
def check_sublist(ls1, ls2): # sublist ls1 and list ls2 list_1 = ls1.copy() list_2 = ls2.copy() for item in list_1: found = 0 for i in range(len(list_2)): if item == list_2[i]: list_2.pop(i) found = 1 break if not found:...
24b7b94a0bd4a470cf53b3037ace7ad5c7647604
dieg0varela/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
160
3.640625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): test = [] for i in matrix: test.append(list(map(lambda x: (x*x), i))) return (test)
59a0441049b9d8a83c3e07ec0bb0c6c25bd6ce55
Madhumitha-Pragalathan/Code-Kata
/largest.py
522
4
4
import sys for i in sys.stdin : num1 = i break for i in sys.stdin : num2 = i break for i in sys.stdin : num3 = i break if(num1 > num2) and (num1 > num3) : num1 = str(num1) num2 = str(num2) num3 = str(num3) print (num1+" is greater than "+num2+" and"+num3) elif(num2 > num1) and (num2 > num3) : num1 = str(num1...
8cc7d97abdcc2960a0d6d1bc148639586f18ffef
euribates/advent_of_code_2020
/day01/second.py
275
3.75
4
import itertools with open("input", "r") as f: numbers = [int(x.strip()) for x in f.readlines() if x] for a, b, c in itertools.permutations(numbers, 3): if a + b + c == 2020: print(f"{a}+{b}+{c} = {a+b+c}") print(f"Solution: {a}*{b}*{c} = {a*b*c}")
0d5f0f2503e375895622c191f8736695b2e81440
knee-rel/CSCI-21-Lab2
/lab2b.py
956
3.828125
4
# Nirel Marie M. Ibarra # 192468 # March 8, 2021 # I have not discussed the Python language code in my program # with anyone other than my instructor or the teaching assistants # assigned to this course # I have not used Python language code obatained from another student # or any other unauthorized source, either mo...
546463ceefa55acaeb49c28d61c2dd31ad956534
nathanpanchal/courses
/6.00/ps01aSC.py
1,925
4.21875
4
# Problem Set 1 # Name: Nathan Panchal # Collaborators: n/a # Time Spent: # balance = float(raw_input('Enter the outstanding balance on the credit card: ')) annual_rate = float(raw_input('Enter the annual interest rate: ')) min_payment_rate = float(raw_input('What is minimum monthly payment rate: ')) #test case 1 # ...
674470bcac02ee52f3b7fde63a4887ba5b1d0ad8
Gogka/ANN
/ANNLayer.py
829
3.75
4
from ANNNeuron import * class ANNLayer(): ### Artificial Neural Network Layer ### # Initializing # number_of_inputs - amount inputs for each neuron in layer to generic weights # number_of_neurons - amount neurons in layer # parent_layer - parent layer if self layer doesn't beginner def __init_...
5175bb68508159210dffac3595f9c071bb357fe6
JoannaEbreso/PythonProgress
/SecondPlot.py
320
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue May 26 22:13:26 2020 @author: DELL USA """ import math import pylab y_values = [] x_values = [] number = 0.0 while number < math.pi * 2: y_values.append(math.sin(number)) x_values.append(number) number += 0.1 pylab.plot(x_values,y_values,'ro') pylab.show() ...
90b66700830719b5dc75ddd90658fc8f495f21ab
sunn-u/CodingTest
/Programmers/Lv1/add_twovalues.py
537
3.546875
4
# 두 개 뽑아서 더하기 def solution(numbers): answer = [] for front_idx, num_front in enumerate(numbers): for back_idx, num_back in enumerate(numbers): if front_idx == back_idx: continue tmp = num_front + num_back answer.append(tmp) # another solution(best...
2bcbe0becc4d80fd963a4e6ff1d143c25caa81a2
SindhuMuthiah/100daysofcode
/acc3.py
197
3.53125
4
'''se=set()''' arr=[] n=int(input()) for i in range(n): num=input() arr.append(num) '''for j in range(n): se.add(arr[j])''' se=set(arr) print(se) k=len(se) print(k)