blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
b825f1d76605fce12876d5a0bb1d57e82cb54a50
niyaspkd/python-unit-test-example
/sort.py
327
3.796875
4
class ElementTypeError(Exception):pass class TypeError(Exception):pass def sort(l): if type(l) != list: raise TypeError,"Input must be list" for i in l: if type(i) != int: raise ElementTypeError,"Invalid list element" for i in range(len(l)): for j in range(i,len(l)): if l[i]>l[j]: l[i],l[j]=l[j],l[i] ret...
ee60c5f80a219159605ae413834ce60e2c4ab4a7
sumanth-hegde/Conversions
/speech-to-text-via-microphone.py
493
3.5
4
# Speech recognition using microphone # importing speech_recognition module import speech_recognition as sr r = sr.Recognizer() # Using microphone as source with sr.Microphone() as source: print("Talk now") audio_text = r.listen(source) print("Times up") try: print("Text: "+r.recognize_google...
e371e74a4207ade3b0d5f5e152b71be78bb0ff3f
Ryuk17/LeetCode
/Python/394. Decode String.py
939
3.5
4
class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ num_stack = [] char_stack = [] res = "" t = '' for c in s: if c == '[': char_stack.append(c) num_stack.append(int(t)...
dca69aca43dac3f61cbab1b286ecd2e260b2b405
Ryuk17/LeetCode
/Python/448. Find All Numbers Disappeared in an Array.py
515
3.5625
4
class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.insert(0, 0) res = [] for i in range(1, len(nums)): while nums[i] != i and nums[i] != nums[nums[i]]: tmp = nums[nu...
4c6e1574243bee2e3bf997da8d728f52ee2973d2
Ryuk17/LeetCode
/Python/297. Serialize and Deserialize Binary Tree.py
1,318
3.515625
4
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root is None: return [] queue = [root] res = [] while len(queue) > 0: node = queue.pop(0) if nod...
07bb7a86ff930cb9f0d955b2c5569838836526dc
Ryuk17/LeetCode
/Python/141. Linked List Cycle.py
535
3.578125
4
class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None: return False p = head.next q = head.next.next while p.next is not None and q is not None: if q.n...
b7ad81e0c65022aa16a1a817b0c520252f7cfefc
skmamillapalli/fluentpython-exercises
/Ch01/Frenchcard.py
1,129
4.0625
4
#!/usr/bin/env python import collections import random # card can have suit(Heart, Diamond, Spade, Club) and rank card = collections.namedtuple('Card', ['suit', 'rank']) class FrenchDeck: """Represents Deck of cards""" def __init__(self): self._cards = [card(rank, suit) for rank in ['Heart', 'Diamond', '...
e516ba068e730f8c2337acf71d762018c6822975
edvin328/EDIBO
/Python/dec2bin.py
536
3.9375
4
#!/bin/python3.8 n=int(input("Please enter decimal number: ")) given_dec=n #jauna massīva array izveidošana array=[] while (n!=0): a=int(n%2) # array.append komanda pievieno massīvam jaunu vērtību array.append(a) n=int(n/2) string="" # lai nolasītu massīvu array no gala izmanto [::-1] for j in array[::-1]...
bb4af43132c6d9246049362f3f5b554ad9a629cf
prashanthag/webDevelopment
/fullstack/projects/capstone/heroku_sample/starter/database/models.py
3,569
3.5
4
import os from sqlalchemy import Column, String, Integer from flask_sqlalchemy import SQLAlchemy import json from flask_migrate import Migrate db = SQLAlchemy() ''' setup_db(app) binds a flask application and a SQLAlchemy service ''' def setup_db(app): db.app = app db.init_app(app) migrate = Migrat...
8be8e2bb46caf8a70c82b41172390c7403733085
RajatVermaz/pytho
/madlibs.py
293
3.578125
4
# Madlibs game based on string concatination adj1 = input('Adjective : ') adj2 = input('Adjective : ') verb1 = input('Verb : ') verb2 = input('Verb : ') print(f'Computer programming is so {adj1} it makes me {verb1}, and some day it will be {adj2} and \ computer will {verb2}.')
5d702c3b01d662249f704099ee85a8cc703d1c02
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/NumericalIntegration/python/program1.py
1,001
3.71875
4
# -*- coding: utf-8 -*- #Example of numerical integration with Gauss-Legendre quadrature #Translated to Python by Kyrre Ness Sjøbæk import sys import numpy from computationalLib import pylib #Read input if len(sys.argv) == 1: print "Number of integration points:" n = int(sys.stdin.readline()) print "Integ...
1fbcf671cd4884007549a8e1c08685329c616e30
CompPhysics/ComputationalPhysics
/doc/Programs/PythonAnimations/animate2.py
876
3.5
4
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def data_gen(t=0): cnt = 0 while cnt < 1000: cnt += 1 t += 0.1 yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) def init(): ax.set_ylim(-1.1, 1.1) ax.set_xlim(0, 10) del xdata[:] de...
df00204272fad9115ea527d137cb7a06df1f16cd
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/PDE/python/2dwave/pythonmovie.py
2,018
3.5
4
#!/usr/bin/env python # This script reads in data from file with the solutions of the # 2dim wave function. The data are organized as # time # l, i, j, u(i,j) where k is the time index t_l, i refers to x_i and j to y_j # At the end it converts a series of png files to a movie # file movie.gif. You can run this movi...
54fa124eaace5d831d897f932615c57182404218
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/MCIntro/python/program1.py
628
3.90625
4
# coding=utf-8 #Example of brute force Monte Carlo integration #Translated to Python by Kyrre Ness Sjøbæk import math, numpy, sys def func(x): """Integrand""" return 4/(1.0+x*x) #Read in number of samples if len(sys.argv) == 2: N = int(sys.argv[1]) else: print "Usage:",sys.argv[0],"N" sys.exit(0)...
23b5fb07ddbe64e1434cb1bfcfdb35d883dc3a6f
raymag/forca
/mag-forca.py
6,486
4.34375
4
#Sendo o objetivo do programa simular um jogo da forca, #Primeiramente importamos a biblioteca Random, nativa do python #Assim podemos trabalhar com números e escolhas aleatórias import random #Aqui, declaramos algumas váriaveis fundamentais para o nosso código #Lista de palavras iniciais (Default) palavras = ['abacat...
e9158dd3a5cd39959a07f8244e3268da819d253e
dustylee621/PythonBootCamp
/inheritance.py
523
3.78125
4
class Animal: def __init__(self, name, species): self.name = name self.species = species def __repr__(self): return f"{self.name} is a {self.genus}" def make_noise(self, sound): print(f"this animal says {sound}") class Snake(Animal): def __init__(self, name, genus, toy): super().__init__(name,...
58473b9b8f3bef88617060c78c084b85be492631
irfan-ansari-au28/Python-Pre
/Lectures/lecture9/dictinary.py
527
4.03125
4
""" dict = { "BJP":32, "Congress": 12, "AAP": 29 } print(dict) print (dict.items()) print(dict.keys()) print(dict.values()) """ parties = ["BJP", "AAP", "Congress", "BJP","AAP", "BJP", "BJP"] party_dict = {} for party in parties: if party in party_dict: party_dict[party] += 1 else: ...
5a6b0d985d1dcbaffc0702939d0fe91aeba778af
irfan-ansari-au28/Python-Pre
/Lectures/lecture8/tuples.py
179
3.859375
4
""" tuple is immutable that means it can't be change once create list can be typecast into tuple type >>> A = list() >>> B = tuple(A) to reverse an array >>> Array[::-1] """
5688123f5e2c4791f8f177a6642df1088138b35f
irfan-ansari-au28/Python-Pre
/Interview/RandomQuestions/binary_search.py
419
3.84375
4
# for binary search array must be sorted A = [1,7,23,44,53,63,67,72,87,91,99] def binary_search(A,target): low = 0 high = len(A) - 1 while low <= high: mid = (low + high) // 2 if target < A[mid]: high = mid - 1 elif target > A[mid]: low = mid + 1 e...
594fee53a4e627a3897888522fb425d365b94d56
irfan-ansari-au28/Python-Pre
/hands_on_python/1.Intro/dictionary.py
773
4.0625
4
""" >>> sorted() -- Does not change the original ordering but gives a new copy """ vowel =['a', 'e', 'i','o' ,'u'] # word = input("provide a word to search for vowels:") word = "Missippi" found = [] for letter in word: if letter in vowel: if letter not in found: found.appen...
2b9c010fcbc0c77d42919128b13fe285a4fa94e2
irfan-ansari-au28/Python-Pre
/Interview/RandomQuestions/matrix_prob.py
1,105
3.796875
4
""" # A = [ # ['#', '#', '#'], # ['#', '', '#'], # ['#', '#', '#'], # ] for 3 X 3 gap = 1 idx =[ (1,)] for 4 X 4 gap = 2**2 idx = [(1,1),(1,2),(2,1),(2,2)] for 5 X 5 gap = 3**3 idx = [((1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3))] """ ip= int(input('Enter row or co...
02b826027ec3d85ddc982ee11df3966527eb041f
irfan-ansari-au28/Python-Pre
/Doubt/week08_day01.py
311
3.84375
4
#Q-1) Next Greater Element #Answer:- def find_next_ele(A): for i in range(len(A)): next_ele = -1 for j in range(i+1,len(A)): if A[j]>A[i]: next_ele = A[j] break print(next_ele,end =" ") if __name__ == "__main__": A= [2,6,4,7,8,3,5,9] # 0 1 2 3 4 5 6 7 8 find_next_ele(A) # t(n) : O(n**2)
fb745ae55b2759660a882d00b345ae0db70e60d2
irfan-ansari-au28/Python-Pre
/Interview/DI _ALGO_CONCEPT/stack.py
542
4.28125
4
""" It's a list when it's follow stacks convention it becomes a stack. """ stack = list() #stack = bottom[8,5,6,3,9]top def isEmpty(): return len(stack) == 0 def peek(): if isEmpty(): return None return stack[-1] def push(x): return stack.append(x) def pop(): if isEmpty(): ret...
bcca7baa2d01e320b8a0c2257cbb1c9b2a0db405
irfan-ansari-au28/Python-Pre
/ClassPractice/W4D3/main.py
324
3.796875
4
from student import Student if __name__ == '__main__': name = input('Enter the name of the student') age = int(input('Enter the age of the student')) birth = int(input('Enter the birth date of the student')) pradeep = Student(name,age,birth) print(pradeep.name) print(pradeep.age) pradeep.re...
4cebce3d1fd394fb85db8ad4bee95f51b1e50dda
irfan-ansari-au28/Python-Pre
/Lectures/lecture4/nested_loop.py
96
3.546875
4
for i in range(3): for j in range(3): for k in range(3): print(i,j,k)
d74a82478b26a11505f547aefe6dcdea9efebce0
TSG405/Simple-Games
/main/Rock Paper Scissor/rock_paper_scissor_2_players.py
1,568
3.84375
4
s1=0 s2=0 # LOGICAL FUNCTION def winner(p1, p2): global s1 global s2 if (p1 == p2): s1+=1 s2+=1 return "It's a tie!" elif (p1 == 'r'): if (p2 == 's)': s1+=1 return "First Player wins!" else: s2+=1 return "Second ...
c6d3d321cbe9cc790a109506c8b80f9d11397462
mattblk/Study
/Python/level1/level1_이상한문자만들기.py
397
3.578125
4
def solution(s): _list = s.split(" ") answer = '' def sub(string): k=0 sub_ans='' for i in string: if i==' ' : sub_ans+=' ' elif k%2 == 0 : sub_ans+=i.upper() else : sub_ans+=i.lower() k=k+1 return sub_ans for i ...
e6ae535a8661e08d94cbb21e812a1f2580f29f09
mattblk/Study
/Python/level2/level2_가장큰수.py
929
3.59375
4
# a=[1,3,4,56,4,2,23,12,89,9,888,999,331,1000] a=[3, 30, 34, 5, 9] def solution(arr): def str_arr(arr): str_arr="" for i in range(0, len(arr)): str_arr= str_arr + str(arr[i]) return str_arr def quick_sort(arr): if len(arr) <= 1: return arr ...
785495eea588f1ac26f5bb49457648c072e3346b
mattblk/Study
/Python/level1/level1_두개뽑아서더하기.py
545
3.765625
4
numbers = [0,0] def solution(numbers): # 두개의 수 합 array arr_sum=[] # 두개의 수 합을 구하는 함수 추가 def add_sum(nums): # 배열 backward num_foward = nums[0] arr_backward=nums[1:len(nums)] for i in arr_backward : arr_sum.append(num_foward + i) if l...
672038829fa89be5aeb711cff4d9b26289028f5c
Vanderson10/Codigos-Python-UFCG
/mtp4/FuncionarioMes/funcionariomes.py
842
3.890625
4
#Receber a quantidade de chinelos produzidos por cada funcionario nos vários turnos dele. #Saida: descobrir quem vendeu mais chinelos. #obs:. não haberá empates #1)receber cada usuario e realizar a soma do quanto eles venderam #2)colocar cada soma numa lista #3)colocar o nome numas lista #4) analisar quem vendeu mais...
88ea10bba74dc895a0cddb587de8f81f808e19ea
Vanderson10/Codigos-Python-UFCG
/4simulado/ar.py
155
3.671875
4
x = int(input()) y = int(input()) if x>y: print("---") exit() menos = y-x for i in range(0,menos+1): atu = x+i print(f'{atu} {atu*atu}')
8259b3a8301dac20fd5cf5d83f0a1dbb93aa0fda
Vanderson10/Codigos-Python-UFCG
/uni4/melhordesempenho/melhordesempenho.py
568
3.5625
4
#calcular qual aluno teve mais "." no miniteste #se tiver empate coloca o primeiro #se n acertar nenhuma questão é pra imprimir -1 quant = int(input()) #encontrar qual teve mais "." maior = 0 lista = [] for i in range(quant): exercicio = input() soma = 0 for t in range(0,len(exercicio)): if exerc...
7fedccbfa707a0a01b76ab3b65d91683abb1967e
Vanderson10/Codigos-Python-UFCG
/uni3/natalina/natalina.py
1,699
3.703125
4
#gratificação de natal #dados: 235 dias, G = (235 - número de dias que faltou) * valor-da-gratificação-por-dia-trabalhado #caso ele não tenha faltado nenhum dia tem a gratificação também #entrada: codigo do cargo, dias que faltou cod = int(input()) #caso1 if cod == 1: print('Deverá receber em dezembro R$ 25000.00...
511b43f80a63e424aa9403ac3a9d21529eca3082
Vanderson10/Codigos-Python-UFCG
/4simulado/tabelaquadrados/Chavesegura/chavesegura.py
1,009
4.125
4
#analisar se a chave é segura #se não tiver mais que cinco vogais na chave #não tem tre caracteres consecultivos iguais #quando detectar que a chave não é segura é para o programa parar e avisar ao usuario #criar um while e analisar se tem tres letras igual em sequencia #analisar se tem mais que cinco vogais, analis...
c1f33cd31e1dd2237b7b4ad92268858864ed9f7f
Vanderson10/Codigos-Python-UFCG
/uni4/SOMAIMPARES/somai.py
798
3.734375
4
#recebe uma sequencia e calcula a soma dos ultimos impares até atingir o valor limite #obs. o valor limite não entra na soma #ex. 3,1,6,4,7 com limite 9, soma = 8 (1+7) obs. de tras pra frente #1-entrada: quantos itens, limite, nuns da sequencia quant = int(input()) limite = int(input()) #nuns dentro do for #coloc...
5e91680b3e38d6d2798d93a6c327cf64c5b8af8f
FloVnst/Python-Challenge-2020
/solutions/road_trip.py
2,499
3.796875
4
# Processing def road_trip(distance, speed, departure): durationMinutes = int((distance / speed) * 60) durationHours = durationMinutes // 60 durationMinutes -= durationHours * 60 # Generate the text for the departure time if departure[1] < 10: departureResult = "Départ à {}h0{}".for...
d43a0da77a1fa9164087b0a4dbc9b3be38c33d82
venkataniharbillakurthi/python-lab
/ex-2.py
263
4.0625
4
a=int(input('Enter the number:')) b=int(input('Enter the number:')) c=int(input('Enter the number:')) sum=a+b+c average=(a+b+c)/3 print('sum = ',sum,'\naverage = ',average) Enter the number:23 Enter the number:45 Enter the number:67 sum = 135 average = 45.0
b0f286afb0b68bc79aa25c4808abf5ad406cd582
KAPILSGNR/KapilSgnrMath
/KapilSgnrMath/MyRectangle.py
239
3.625
4
class Rectangle: def __init__(self,length, width): self.length=length self.width=width def getArea(self): area= self.length*self.width print("Area of the Rectangle is: ", area) return area
6a34496d114bc6e67187e4bc12c8ff874d575de0
BrightAdeGodson/submissions
/CS1101/bool.py
1,767
4.28125
4
#!/usr/bin/python3 ''' Simple compare script ''' def validate(number: str) -> bool: '''Validate entered number string is valid number''' if number == '': print('Error: number is empty') return False try: int(number) except ValueError as exp: print('Error: ', exp) ...
0b3c1743acf1b4f3ad68757fe8699ee10fc8f67e
abhi-accubits/caffinated
/src/filegen.py
676
3.671875
4
import os """ File Generator Author Danwand NS github.com/DanBrown47 verify if the buffer file is present, if not generates one as temp storage of the file """ class FileGen: """ Checks if the file is present if not generate """ def __init__(self, path) -> None: self.path = path pas...
009b1d64116333f801b6b7947d336be76686f082
BowieSmith/project_euler
/python/p_001.py
133
4.0625
4
# Find the sum of all the multiples of 3 or 5 below 1000. ans = sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0) print(ans)
49b854f0322357dd2ff9f588fc8fb9c6f62fd360
BowieSmith/project_euler
/python/p_004.py
352
4.125
4
# Find the largest palindrome made from the product of two 3-digit numbers. def is_palindrome(n): s = str(n) for i in range(len(s) // 2): if s[i] != s[-i - 1]: return False return True if __name__ == "__main__": ans = max(a*b for a in range(100,1000) for b in range(100,1000) if is_...
81c2f882685c1222115f2700ae39aeb77da3749a
BowieSmith/project_euler
/python/p_019.py
1,550
4.03125
4
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? # Assume 1 Jan 1900 was a Monday def is_leap_year(n): if n % 4 != 0: # leap years on years divisible by 4 return False if n % 400 == 0: # also on years divisible by 400 return Tr...
48d4eaad07fc9dcfa1f4c8b4a1f364bc02bbbd7f
Dron2200/My-first-steps-in-Python
/HW3_4.py
554
4.0625
4
print("This program is more interesting that previous", '\n', "So, using this program you can resolve following formula", '\n', "ax^2 + bx + c = 0 ") a = float(input("Please, write a :")) b = float(input("Please, write b :")) c = float(input("Please, write c :")) d = (b**2 - 4*a*c) x = -(b/2*a) x1 =...
1def7f563fa6c611e1806b07e94c84e8af0cbb0d
Dron2200/My-first-steps-in-Python
/lesson2_3.py
362
4.03125
4
print("Homework-2 Task-3") print("This program is more interesting that previous", '\n', "So, using this program you can resolve following formula", '\n', "ax^2 + bx + c = 0 ") a = float(input("Please, write a :")) b = float(input("Please, write b :")) c = float(input("Please, write c :")) x = (-b ...
ccb6c8bd7bd657668691cad6c3fa7c5bd699c766
tameravci/FeedForwardNNet
/AvciNeuralNet.py
7,606
4.09375
4
# coding: utf-8 # # Simple feedforward neural network with Stochastic Gradient Descent learning algorithm # # Tamer Avci, June 2016 # # Motivation: To get better insights into Neural nets by implementing them only using NumPy. # Task: To classify MNIST handwritten digits: http://yann.lecun.com/exdb/mnist/ # # Ac...
b1ce06dcf2fffe8543d67751f712166d20000bf7
ysw900524/Python_Multicampus
/Day4_10_27/s606_인스턴스변수_인스턴스간공유안됨.py
556
3.5
4
# 인스턴스 변수 class Cat: def __init__(self, name): self.name = name self.tricks = [] # 인스턴스 변수 선언 def add_trick(self, trick): self.tricks.append(trick) #인스턴스 변수에 값 추가 cat1 =Cat('하늘이') cat2 = Cat('야옹이') cat1.add_trick('구르기') cat2.add_trick('두발로 서기') cat2.add_trick('죽은척 하기') print(cat1.n...
daa15a806aa377a9261d0d4cb94a4d3676904b86
ysw900524/Python_Multicampus
/Day4_10_27/Day4_미션1_로또번호생성.py
1,121
4.03125
4
# 미션 1 # 로또 번호를 자동으로 생성해서 출력 # 주문한 개수만큼 N개의 로또 번호 출력 # Hint : 랜덤 숫자 생성 # import random # random.randint(num1, num2) # num1~num2까지의 정수 생성 # # Ex. dice.py # import random # # dice_num = random.randint(1, 6) # print('주사위:'. doce_num) import random # class Lotto: # nums = set() # # ...
c8e8670b016510be47f75896a82fecaadef0aa77
ysw900524/Python_Multicampus
/Day2_10_25/Day2_과제_도형그리기.py
865
4
4
import turtle import math import time width = 100 height = 100 slide = math.sqrt(width**2 + height**2) input('엔터를 치면 거북이가 도형을 그립니다.') turtle.shape('turtle') turtle.pensize(5) turtle.color('blue') print('거북이 달리기 시작합니다.') #time.sleep(1) turtle.forward(width) #time.sleep(1) turtle.right(135) turtle.forward(slide) #...
a9e29aa8ec9548ea7928a9d83598ddcdec7e4ba7
ysw900524/Python_Multicampus
/Day1_10_24/s105_comment.py
626
3.65625
4
# 한줄 주석 : 샵기호(#)로 시작하는 줄 # 블럭 주석 : 큰따옴표 3개로 감사는 줄 # 이 줄은 라인 코멘트입니다. print("Hello World!") print("Hello World!") # 이것도 라인 코멘트입니다. print("Hello World!") # 이것도 라인 코멘트입니다. # First comment a = 15 # Second comment # a값을 출력해 보세요! print(a) b = '파이썬의 주석은 샾기호(#)로 시작합니다.' print(b) # 마지막 라인입니다. # 한줄 주석과 블럭 주석 """ 블럭주석, 즉 ...
00cf2f1c84d610e15e65b70d4a643caea0a01c4c
JordenHai/workSpace
/oldboyDaysDir/day1/passwd.py
360
3.625
4
# -*- coding:utf-8 -*- # Author: Jorden Hai #秘文输入 import getpass #新的包 _username = 'jh' _password = '123456' username = input("username:") password = input("password:") if username == _username and _password == password: print("Success Login!") print('''Wellcome user {_name} login...'''.format(_name = username)...
44c8ac49899f2174a56812c8e62d229ea7b0c3a3
JordenHai/workSpace
/oldboyDaysDir/day6/MulIheri.py
695
3.984375
4
# -*- coding:utf-8 -*- # Author: Jorden Hai class A(): def __init__(self): print("init in A") class B(A): def __init__(self): A.__init__(self) print("init in B") class C(A): def __init__(self): A.__init__(self) print("init in C") class D(B,A): #找到第一个就停下来 pas...
5be234e49a9106b7bdef8a1cea9def37cc97a72b
JordenHai/workSpace
/oldboyDaysDir/day1/集合.py
1,073
3.859375
4
list_1 = [1,4,5,6,9,7,3,1,2] list_1 = set(list_1) print(list_1) list_2 = set([2,6,0,66,22,8,4]) print(list_2) #交集 list_3 = list_1.intersection(list_2) print(list_3) #并集 list_3 = list_1.union(list_2) print(list_3) #差集 list_3 = list_1.difference(list_2) print(list_3) list_3 = list_2.difference(list_1) prin...
a60a933c68c6210b3c407f3bdfcae0352cd575c6
MarkHershey/PythonWorkshop2020
/Session_01/py101/10_classes.py
418
3.984375
4
class People: def __init__(self, name, birthYear): self.name = name self.birthYear = birthYear self.age = 2020 - birthYear self.height = None self.pillar = None p1 = People("Maria", 1999) print(p1.name) print(p1.birthYear) print(p1.age) p1.pillar = "Architecture and Sustai...
552b2a950f718a75b11dcba8ee93fbb41ad4438c
zhengshaobing/PythonSpider
/BK_全局锁机制_生产者与消费者模式.py
1,899
3.625
4
import threading, random, time Qmoney = 1000 # Value_data = 0 gLock = threading.Lock() gTotal_times = 10 gtimes = 0 # # # class CountThread(threading.Thread): # def run(self): # global Value_data # # 锁主要用于:修改全局变量的地方 # gLock.acquire() # for x in range(1000000): # Value_d...
5822eb6433daf2b6421c7a0f318729b043eb84fb
avelikev/Exercises
/data_structures/dictionaries_and_arrays/2.Reverse_Array /Solutions/solution.py
196
4.0625
4
from array import * array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3]) reverse_array = array('i') for i in range(len(array_num)-1,-1,-1): reverse_array.append(array_num[i]) print(reverse_array)
ae5fd33d822cacc8617bf5db2f8b4633f9860f1a
avelikev/Exercises
/introduction_to_python/functions/1_return_hello/Solution/solution.py
128
3.671875
4
# Code your solution here def hello(name): data="Hello "+name return data name=input() result=hello(name) print(result)
73857ec7f281166378fecff5c1ab4f1ff3011d44
avelikev/Exercises
/data_structures/stacks_and_queues/1_create_queue/Solution/solution.py
369
3.703125
4
# Code your solution here def queue(): import queue queue_a = queue.Queue(maxsize=5) # Queue is created as an object 'queue_a' queue_a.put(9) queue_a.put(6) queue_a.put(7) # Data is inserted in 'queue_a' at the end using put() queue_a.put(4) queue_a.put(1) return queue_a d...
7cddd25f93030f10c2c9a4e6eb71bb1445f7fc9c
avelikev/Exercises
/introduction_to_python/functions/3_total/Solution/solution.py
160
3.5
4
# Code your solution here def summ(l): total = 0 for x in l: total=total+x return total l=[10,20,30,40,50,60] result=summ(l) print(result)
1bd7f0daf5019e00dc508429182bd7016956bf33
avelikev/Exercises
/data_structures/stacks_and_queues/2_stack_insert/Solution/solution.py
237
3.515625
4
# Code your solution here def insert(stack_planets): stack_planets.insert(2,'Earth') return stack_planets stack_planets=['Mercury','Venus','Mars','Jupiter','Saturn','Uranus','Neptune'] result=insert(stack_planets) print(result)
cbe50f30732a080bf558b0a77e29942ed2c04f7a
avelikev/Exercises
/data_structures/binary_trees/3_normal BST to Balanced BST/Solution/solution.py
1,810
3.953125
4
import sys import math # A binary tree node has data, pointer to left child # and a pointer to right child class Node: def __init__(self,data): self.data=data self.left=None self.right=None # This function traverse the skewed binary tree and # stores its nodes pointers in ve...
eed8d54cb38af8b0bb62927b9dadfdf0aa69d378
debargham14/bcse-lab
/Sem 4/Adv OOP/python_assignments_set1/sol10.py
444
4.125
4
import math def check_square (x) : "Function to check if the number is a odd square" y = int (math.sqrt(x)) return y * y == x # input the list of numbers print ("Enter list of numbers: ", end = " ") nums = list (map (int, input().split())) # filter out the odd numbers odd_nums = filter (lambda x: x%2 == 1, nums) ...
6b2736e3ef5bd2b374367750d21d8af3e9ca2e0a
debargham14/bcse-lab
/Sem 4/Adv OOP/python_assignments_set1/sol11.py
434
4.28125
4
print ("Pythagorean Triplets with smaller side upto 10 -->") # form : (m^2 - n^2, 2*m*n, m^2 + n^2) # generate all (m, n) pairs such that m^2 - n^2 <= 10 # if we take (m > n), for m >= 6, m^2 - n^2 will always be greater than 10 # so m ranges from 1 to 5 and n ranges from 1 to m-1 pythTriplets = [(m*m - n*n, 2*m*n, m*m...
2f266658a68658cc904391e4fea493d8581025c8
JasianJ/Python
/Fibonacci Sequence/Fibonacci.py
1,195
4.09375
4
from IPython.display import clear_output def findnum(n): out = [] a, b = 0, 1 for i in range(n): out.append(a) a, b = b, a+b return out def nth(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a on = True print 'Enther a number...
2c0d624ee886d24c10a979e922c1e7fbab74d7ed
AlterFritz88/flask_practice
/task_3_14_6.py
758
3.546875
4
class PiggyBank: def __init__(self, dollars, cents): self.dollars = dollars self.cents = cents def add_money(self, deposit_dollars, deposit_cents): self.dollars += deposit_dollars self.cents += deposit_cents if self.cents > 99: self.dollars += self.cents // 1...
bbe6083817412b75edfb6985b3718f08a6740faa
ThallesVale/calculadoraAnuncios
/calculadora.py
849
3.765625
4
#CALCULADORA - ALCANCE DE ANÚNCIO ONLINE: investimento = input('Digite o valor a ser investido: ') investimento = float(investimento) #Visualizações atreladas ao valor investido: visualizacao = investimento*30 #Cliques gerados por volume de visualizações: cliques = int(visualizacao*.12) #Compartilhamentos por volum...
84e3e7e273206db5ddb0576f42fbec467164f1c5
shaunmulligan/resin-neopixel
/app/leds.py
1,530
3.53125
4
from time import sleep from neopixel import Adafruit_NeoPixel, Color # LED strip configuration: LED_COUNT = 64 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 5 ...
669f4bbca09f2d6062be01a30fdfd0f7a0367394
mckinleyfox/cmpt120fox
/pi.py
487
4.15625
4
#this program is used to approximate the value of pi import math def main(): print("n is the number of terms in the pi approximation.") n = int(input("Enter a value of n: ")) approx = 0.0 signchange = 1.0 for i in range(1, n+1, 2): approx = approx + signchange * 4.0/i # JA signchange...
5c1a951d38aeeec9b7329a011b8d634cb9137f52
jorgeromeromg2/Python
/mundo2/ex92.py
580
3.703125
4
from datetime import datetime relacao = dict() relacao["Nome"] = str(input('Nome: ')).capitalize() idade = int(input('Ano de nascimento: ')) relacao["Idade"] = datetime.now().year - idade relacao["CTPS"] = int(input('Carteira de Trabalho (0 não tem): ')) if relacao["CTPS"] != 0: relacao["Contratação"] = int(input('...
f6c98f4637a5dbf25fd4d76119aa0cb93c819e77
jorgeromeromg2/Python
/mundo2/ex85.py
670
3.84375
4
'''valores = [] par = [] impar = [] for v in range(1, 8): valores.append(int(input(f'Digite o {v}º valor: '))) if valores[0] % 2 == 0: par.append(valores[:]) elif valores[0] % 2 != 0: impar.append(valores[:]) valores.clear() print(sorted(par)) print(sorted(impar))''' numeros = [[], []] ...
6d8ca4a28dfdc8a6a703c8dc8d8652981fe10238
jorgeromeromg2/Python
/mundo1/ex033.py
350
3.890625
4
reta1 = float(input('Digite a primeira reta: ')) reta2 = float(input('Digite a segunda reta: ')) reta3 = float(input('Digite a terceira reta: ')) if (reta1 + reta2 > reta3) and (reta2 + reta3 > reta1) and (reta1 + reta3 > reta2): print('Possui condição para ser um triângulo.') else: print('Não possui condição p...
4c538d0eccedfa427845be1ca803cdb6cc2ef867
jorgeromeromg2/Python
/mundo2/ex008_D41.py
787
4.25
4
#--------CATEGORIA NATAÇÃO--------# print(10 * '--=--') print('CADASTRO PARA CONFEDERAÇÃO NACIONAL DE NATAÇÃO') print(10 * '--=--') nome = str(input('Qual é o seu nome: ')).capitalize() idade = int(input('Qual é a sua idade: ')) if idade <= 9: print('{}, você tem {} anos e está cadastrado na categoria MIRIM.'.forma...
fd614fdd36b34645dd4afc125153dc09493841c2
jorgeromeromg2/Python
/mundo1/ex005.py
648
4.15625
4
#--------SOMA ENTRE NÚMEROS------ #n1 = int(input('Digite o primeiro número: ')) #n2 = int(input('Digite o segundo número: ')) #soma = n1 + n2 #print('A soma entre {} e {} é igual a {}!'.format(n1, n2, soma)) #--------SUCESSOR E ANTECESSOR----- n = int(input('Digite um número e verifique o sucessor e antecessor:')) a ...
f26dc0e78afb7d4ca9e79764ee4914b8f523f9b8
jorgeromeromg2/Python
/mundo2/ex013_D51.py
437
4.0625
4
#-----PROGRESSÃO ARITMÉTICA------ '''num1 = int(input('Digite o primeiro termo da P.A: ')) num3 = int(input('Digite a razão da P.A: ')) for n in range(num1, 10*num3, num3): print('O termos da P.A são {} '.format(n))''' primeiro = int(input('Primerio termo: ')) razao = int(input('Razão: ')) decimo = primeiro + (10 ...
457ee2cf1dbd934cab7bf67f8600c895ec9229a0
jorgeromeromg2/Python
/mundo2/ex88.py
458
3.6875
4
from random import randint from time import sleep jogo = [] jogo1 = [] jogadas = int(input('Quantos jogos você quer que eu sorteie? ')) print(3*'-=', f'SORTEANDO {jogadas} NÚMEROS', 3*'-=') for j in range(1, jogadas+1): jogo.clear() jogo1 = [randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randin...
c53134cddbc37e350cd80a9b8a334a0f1299382e
jorgeromeromg2/Python
/mundo2/ex013_D48.py
655
4.0625
4
#------NUMEROS IMPARES DIVISIVEIS POR 3-------- '''primeiro = int(input('Digite o primeiro número da sequência: ')) ultimo = int(input('Digite o último número da sequência: ')) for c in range(primeiro, ultimo): if c % 3 == 0 and c % 2 != 0: print(c) print('Na contagem de {} à {} os números em tela são impar...
d11deb0a802075340ada466cb8a9af86f764b71d
jorgeromeromg2/Python
/mundo2/ex014_D64.py
558
3.78125
4
cont = n = total = 0 while total < 999: total = int(input('Digite um número [999 para parar]: ')) if total != 999: n += total cont += 1 print('Você digitou {} números e a soma entre eles foi {}'.format(cont, n)) ''' n = cont = soma = 0 n = int(input('Digite um número [999 para parar]: )) while ...
225121d559a01c2380908f55d70d53357972b619
jorgeromeromg2/Python
/mundo2/ex014_D60.py
687
4.0625
4
#----FATORIAL----- '''from math import factorial fat = int(input('Digite o número e descubra seu fatorial: ')) num1 = factorial(fat) print('O fatorial de {} é {}'.format(fat, num1))''' '''n1 = int(input('Digite um número para calcular o fatorial: ')) f = 1 print('Calculando {}! = '.format(n1), end='') while n1 > 0: ...
8bd089a620d46edb2e29106eeecbbcc94c4a46ab
jorgeromeromg2/Python
/mundo1/ex004a.py
204
3.765625
4
n1 = input('Digite algo: ') print('O que foi digitado é um número? ', n1.isalnum()) print('O que foi digitado é uma string? ', n1.isalpha()) print('O que foi digitado é alfanumérico? ', n1.isalnum())
c5eb72c84282a18019f9d280449ffcdbcf0948d1
Zoooka/Rock-Paper-Scissors-
/rock paper.py
1,228
4.03125
4
import sys import getpass # Creates two users, and for users to enter their names User1 = input("Player one, what is your name? ") User2 = input("Player two, What is your name? ") # Counts users wins User1_wincount = 0 User2_wincount = 0 # Prompts users to enter rock paper scissors etc... User1_answer = input("%s, ...
ec7e9176ef54a88a6c1d25b89c599f8d9e419c89
irische/Intro-to-CS_Python
/HW_3/HW_3_part_1/hw3_part1_files/hw3_part1.py
3,744
3.921875
4
# Qianqian Che (cheq@rpi.edu) # Purpose: output the table about top 250 ranked female and male names on demand. # read and access the names and counts import read_names import sys # function to find if a value is in the list and the index and return required values def table(name,list_name,list_counts): position=...
d4fd84f9634db9e9db97e347360b5da2bab01b09
irische/Intro-to-CS_Python
/HW_8/hw9_part1.py
1,898
3.84375
4
"""Author: <Boliang Yang and yangb5@rpi.edu> Purpose: This program reads a yelp file about the businesses, counts all categories that co-occur with the given category and prints those categories with counts greater than the given cutoff in sorted order. """ ## all imports import json ## main bo...
5bad1293e9456a4baf7c4b63c1edac3662d1f18d
irische/Intro-to-CS_Python
/HW_4/hw4_part3.py
1,473
3.640625
4
'''This program reads in the death statistics for areas of NYS from 2003 to 2013 and ouput the trend in a single line. ''' import hw4_util ## function definition to output the trend of death statistics. def read_deaths(county,data): data_=data[:] sum=0 for r in range(len(data_)): sum+=data_[r] ...
7354794ac710eeb677d5c2d163c2c74f60e78d22
nindanindra/meerkpy
/chapter2.py
1,715
4.0625
4
users={"Anna":{ "bbm":2.0, "doraemon":4.325}, "Joe":{"ff7":4.125, "doraemon":3.275}, "Smith":{"ff7":1.25, "bbm":2.450, }} def manhattan(rating1,rating2): distance=0 for key in rating1: if key in rating2: distance+=abs(rating1[key] - rating2[key]) return distance def minkowski(rating1, rating2, r): ...
3d93e7ba5742d17e856ec95538b1bfaaca906d79
Madhuparna-Das/Madhuparna_Das
/extension.py
330
3.890625
4
file_name=input("enter the file name").casefold() b=file_name.split('.') y=b[1] if(y=='py'): print("file extension is python") elif(y=='java'): print("file extension is java") elif(y=='c'): print("file extension is C") elif(y=='cpp'): print("file extension is c++") else: print("please enter valid fi...
d1efce2817a84b01f03ffd6510e19e70177387f9
elirud/kattis
/problems/sodasurpler.py
257
3.5625
4
i = dict(zip(['start', 'found', 'needed'], map(int, input().split()))) bottles = i['start'] + i['found'] sodas = 0 while bottles >= i['needed']: sodas += bottles // i['needed'] bottles = bottles // i['needed'] + bottles % i['needed'] print(sodas)
e8ba6c87fc0660ecec74f67dff3ab8a4b92316f8
jptafe/ictprg434_435_python_ex
/wk4/wk4_input.py
989
3.609375
4
#!/usr/bin/python # TAKE only 1 parameter from the CLI # calculate and print the CLI parameter + 5 # NOTE: Attempt this WITHOUT an if statement # use try: except: block instead import sys try: newnum = int(sys.argv[1]) + 4 if(newnum = 999): raise Exception('blah') except ValueError: print(...
6c3d96d82e199378ef5cb8b5060a52f4ad92da07
ArjunSubramonian/CrazyEights
/util/card.py
692
3.6875
4
from enum import Enum class Rank(Enum): JOKER = 14 KING = 13 QUEEN = 12 JACK = 11 TEN = 10 NINE = 9 EIGHT = 8 SEVEN = 7 SIX = 6 FIVE = 5 FOUR = 4 THREE = 3 DEUCE = 2 ACE = 1 class Suit(Enum): CLUBS = 1 DIAMONDS = 2 HEARTS = 3 SPADES = 4 class C...
0b1c100231c6dbe5d970655a92f4baed0cbe1221
firoj1705/git_Python
/V2-4.py
1,745
4.3125
4
''' 1. PRINT FUNCTION IN PYTHON: print('hello', 'welcome') print('to', 'python', 'class') #here by default it will take space between two values and new line between two print function print('hello', 'welcome', end=' ') print('to', 'python', 'class') # here we can change end as per our requirement, by addind end=' ...
bf66f636f476c0610625d54d5ebb6ec4c0111b05
firoj1705/git_Python
/V5.py
1,003
4.0625
4
''' 1. INPUTS IN PYTHON: s=input('Enter String: ') print(s) n=int(input("Enter Number: ")) print(n) f=float(input('Enter Floating point number: ')) print(f) 2. LOOPS IN PYTHON: A. if-elif-else ladder: Single if statement has multiple elif statements. n%5=Buzz n%3=Fizz n%3,5=FizzBuzz n=int(input("Enter Number: ...
b18609cde09810784b1c2ce40381ee7ab7ee6d43
samaro19/Random_Code
/decode_ceaser.py
717
3.859375
4
dict = { -2: '!', -1: '?', 0: ' ', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: '...
54202c7d5234ff5bad17419c664f9d479615cef5
samaro19/Random_Code
/l_system_hilbert_curve.py
510
3.96875
4
import turtle turtle.penup() turtle.sety(00) turtle.pendown() turtle.hideturtle() turtle.tracer(20, 1) def str_rep(x): y = "" for xs in x: if xs == "A": y += "BF+AFA+FB-" elif xs == "B": y += "AF-BFB-FA+" else: y += xs return y def iterate(x, t): for i in range(t): x = str_rep(x)...
38932f838745fff4b086d05c8b7b00802133bd22
samaro19/Random_Code
/polyalphabetic_cypher 1.0.py
818
3.78125
4
ALPHABET = { '!': -2, '?': -1, ' ': 0, 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, '...
13ca3b030032cf5763a584614ee169d436145fb9
TroyeWlb/testProjects
/ifelse.py
1,207
3.8125
4
# price = float(input("价格")) # weight = float(input("重量")) # total = price * weight # print("合计 %.02f元 " % total) # name = input("name") # print("我的名字叫 %s,请多多关照" % name) # student_no = int(input("No.")) # print("我的学号是 %09d" % student_no) # scale = float(input("age")) # if scale >= 18: # print("welcome") # else: # ...
4c7fede5166a8852646ab41c41033e4d40be3c13
mohanbabu2706/testrepo
/2020/october/1/2-Oct/log2 and log10.py
255
3.609375
4
#importing "math" for mathematical operations import math #returnig log2 of 16 print("The value of log2 of 16 is:",end="") print(math.log2(16)) #returning the log10 of 10000 print("The value of log10 of 10000 is:",end="") print(math.log10(10000))
655468222209a0a6151c576027827d12c1082ad6
mohanbabu2706/testrepo
/2020/october/1/1-Oct/reverse string.py
194
4.09375
4
def string_reverse(str1): rstr = '' index = len(str1) while index>0: rstr1 += str1[index-1] index = index-1 return str1 print(string_reverse('1234abcd'))
9d72e56c01ac55832f7caa24afb7d32e39dde8b3
gc2321/Coursera_PC_1
/week2_2048_full.py
6,987
3.625
4
""" Clone of 2048 game. """ import poc_2048_gui, random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0, -1)} def slide(line, val): """ Functi...
3303ed1dceb6078ee7f6770b67dcf3fefd24a99b
saedmansour/University-Code
/Artificial Intelligence/final_competition/myGraph.py
6,492
3.734375
4
################################# ## ## ## Graph Search Algorithms ## ## ## ################################# # This file contains the basic definition of a graph node, and the basic # generic graph search on which all others are based. # The classes defined ...
288f226242b46fc371d12df7f9dcfb7166f6d46b
whg/DfPaI
/week3/examples/exception-example.py
108
3.640625
4
text = input() try: number = int(text) print(number + 1) except: print("that's not a number!")
c7eebd9b9319084b280308ea931083fba6a4f222
chorton2227/dailyprogrammer
/challenge_86/intermediate/program.py
601
3.734375
4
import sys import math from datetime import date if len(sys.argv)==1: print 'Enter arguments' exit(0) days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] day = int(sys.argv[1]) month = int(sys.argv[2]) year = sys.argv[3] T = int(year[2:]) if T & 1: T += 11 T /= 2 if T & 1: T +=...