blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
cfd3292829a5f7458c5c44229d9046c6addea805
vineeta786/hackerank_solutions_python
/Strings/Capitalize!.py
395
3.671875
4
import math import os import random import re import sys # Complete the solve function below. def solve(s): l = s.split(" ") width = len(l) for i in range(width): if(l[i].isalpha()): cap = list(l[i]) cap[0] = cap[0].upper() l[i] = "".join(cap) cap.c...
780e81524394afbf859287e768a87d8ab385d44b
aquibjamal/hackerrank_solutions
/validating_phone_nums.py
315
3.625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 02:39:52 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT import re n=int(input()) for _ in range(n): if re.match(r'[789]\d{9}$', input()): print('YES') else: print('NO')
38ac8c311b2c1334c50a7768cd79eee1921af74a
vishalbelsare/rPSMF
/pypsmf/psmf/learning_rate.py
615
3.765625
4
# -*- coding: utf-8 -*- import abc class BaseLearningRate(metaclass=abc.ABCMeta): @abc.abstractmethod def get(self, t): """ Get the learning rate for time t """ class ConstantLearningRate(BaseLearningRate): def __init__(self, lr): self.lr = lr def get(self, t): return self....
6b13ab4fcc119127d28e22cc544897ee8c60e358
shiratsu/face_trim
/numpytest.py
396
3.625
4
# -*- coding: utf-8 -*- import numpy as np def main(): # 2次元配列の宣言・初期化 A = np.array([[1, 2], [3, 4], [5, 6]]) A = np.array([1,2]) # 行列の大きさ print("行列Aの大きさ:", A.shape) print("行列Aの行数:", A.shape[0]) print("行列Aの列数:", A.shape[1]) if __name__ == '__main__': ...
05d577a93177d8212ee42ec99d5412e23e96fe2d
anganesh/PythonLearning
/tutorial_loop_examples.py
799
4.21875
4
# To check whether a given number is even or odd for i in range(2,10): if i%2 == 0: print (i,'even number') else: print (i, 'odd number') # To print fibonaci series n0=1 print n0 n1=1 print n1 val = n0+n1 for i in range(2,10): print val n0=n1 n1=val val = n0+n1 print " another w...
9c14d2ce7a64346f5c87b086519698b88aca6d28
xdfc1745/baekjoon
/17478.py
901
3.578125
4
def recursion(n, cnt): intent = '____' * cnt print(intent+"\"재귀함수가 뭔가요?\"") if n == 1 : print(intent+"\"재귀함수는 자기 자신을 호출하는 함수라네\"") print(intent+"라고 답변하였지.") return print(intent+"\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.") print(intent+"마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지...
0f78e5b9ea3a3d06cd68d6448ca0e394a461774c
giordafrancis/adventofcode2019
/day02_alarm.py
2,522
3.984375
4
""" https://adventofcode.com/2019/day/2 """ from typing import List, NamedTuple, Iterator import itertools class Command(NamedTuple): pointer: int opcode: int pos_1: int = None pos_2: int = None pos_final: int = None def instructions(inputs: List[int]) -> Iterator[Command]: """ Splits ins...
b7757a06f89cacb51cb96eba0c685b4cf31a9b4a
jdobner/grok-code
/find_smallest_sub2.py
1,537
4.21875
4
def find_substring(str, pattern): """ Given a string and a pattern, find the smallest substring in the given string which has all the characters of the given pattern. :param str: :param pattern: :return: str >>> find_substring("aabdec", 'abc') 'abdec' >>> find_substring("abdbca", 'abc') 'bca' >>> f...
6fd13c22a04c044832d1c6622237bded799931cd
mupotsal/Programming_Practice_IGIT
/Lab2.py
2,282
3.59375
4
import random from datetime import datetime def mergesort(A): n = len(A) if n > 1: mid = n // 2 B = A[0:n // 2] C = A[n // 2:n] mergesort(B) mergesort(C) merge(B, C, A) def merge(B, C, A): bIndex = cIndex = 0 m1 = len(B) m2 = len(C) n = len(A) ...
9af12851de2d3e0ef8ea0181fa1a627fef74bee7
MrinaliniTh/Algorithms
/Interview_question/find_second_largest.py
596
3.96875
4
import heapq def find_second_largest(nums): largest = 0 second_largest = 0 for num in nums: if num > largest: second_largest = largest largest = num elif num > second_largest: second_largest = num return second_largest, largest def find_using_heapq(n...
7c3bdfed299500306f053fab3d9b0d7f68eba598
k3vzz/Coursera_Python
/week5_1.py
400
3.984375
4
count = 0 total = 0 avg = None while True: try: inp = raw_input('Enter a number: ') if inp == 'done': break if len(inp) < 1 : break num = float(inp) count = count + 1 total = total + num avg = total / count except: print 'Invalid input' c...
05d40ca989c3349ade58bb07af4e849ea275f27b
845318843/20190323learnPython
/withKid/代码清单5-end.py
1,058
4.03125
4
# test items # anser = input("key a num,please!") # print(type(anser)) # key in 12, will be stored as string form # num = float(input()) # using float() can solve it # print(num) # try items # item1 # firstname = "ke" # lastname = "zj" # print(firstname+lastname) # item2 # firstname = input("hi,key your firstname") # ...
6af6cb9c5b143d49f1ff1497eeb69a2a7fbeeba9
JJJOHNSON22/Python-fundamentals
/functions_intermediate1.py
560
3.671875
4
import random def randInt(max_num=0, min_num=0): if (min_num==0 and max_num==0): num = int(random.random() * 100) return num elif (min_num!=0 and max_num!=0): num = int(random.random() * (max_num - min_num) + min_num) return num elif (max_num!=0): num = int(random.ran...
53bf2ba5463159243732ead589db72ffe603afb4
sashadev-sky/Python-for-Networking
/chapter2/threads/threads_init.py
952
3.96875
4
from threading import Thread from time import sleep num_threads = 4 def thread_message(message): global num_threads num_threads -= 1 print('Message from thread %s\n' % message) while num_threads > 0: print("I am the %s thread" % num_threads) Thread(target=thread_message("I am the %s thread" % num_threads)).st...
1312fed483a6a70d4f53b53b761b498b55a82bcc
FabianoJanisch/CursoEmVideo-Python
/Exercício 039.py
428
3.953125
4
from datetime import date ano = int(input("Ano de nascimento: ")) anoatual = date.today().year idade = anoatual - ano jafoi = ano + 18 jafoi2 = anoatual - jafoi aindavai = 18 - idade if idade == 18: print ("Esse ano é o seu alistamento!") if idade > 18: print (f"Já se passou {jafoi2} anos de seu alistamento e...
42f2ef71989736761630fa4080b6b49474e524eb
codelurker/ASCIIShooter
/shapes.py
422
3.765625
4
def draw_circle(at,size): Circle = 0 width=size height=size CenterX=(width/2) CenterY=(height/2) circle = [] for i in range(height): for j in range(width+1): Circle = (((i-CenterY)*(i-CenterY))/((float(height)/2)*(float(height)/2)))+((((j-CenterX)*(j-CenterX))/((float(width)/2)*(float(width)/2)))); if C...
82d86b34440c384268f49f27b03477179bfbff4e
marcusvtms/moto_questions
/q5.py
2,057
3.796875
4
#!/usr/bin/env python class node: def __init__(self): self.val = None self.next = None class lk_list: def __init__(self): self.curr_node = None def add_node(self, value): n_node = node() n_node.val = value n_node.next = self.curr_node self.curr_...
a0ebf828880a2d4b056d808c99794902ac0228af
wisdom2018/pythonLearn
/class.py
422
3.640625
4
#! /usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/7/29 9:42 AM # @Author: zhangzhihui.wisdom # @File:class.py class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) if __...
84f42f83ca2e2691009a5f47d1e5b81d66521112
liquid-sky/scripts
/collatz.py
928
3.921875
4
#!/usr/bin/python THRESHOLD = 10L ** 6 length_memo = {1: 1} def collatz_length(n): '''Recursively builds a dict of lenghts of Collatz sequences. ''' if n not in length_memo: if n % 2 == 0: length_memo[n] = 1 + collatz_length(n / 2) else: length_memo[n] = 1 + col...
a90ed40f60edcfa686e000cabe790d22bcdeab18
syurskyi/Python_Topics
/020_sequences/examples/ITVDN Python Essential 2016/20-comparing_sequences.py
664
3.90625
4
""" Последовательности одинаковых типов можно сравнивать. Сравнения происходят в лексикографическом порядке: последовательность меньшей длины меньше, чем последовательность большей длины, если же их длины равны, то результат сравнения равен результату сравнения первых отличающихся элементов. """ print('abc' < 'ab') pr...
0b767a90585b8aa99191ff03ad9f0516808240b6
nckturner/practice
/cookies/sorted.py
155
3.875
4
d= [{ "a": 1, "b": 3, "c": "FIRST"}, { "a": 2, "b": 2, "c": "SECOND"}, { "a": 3, "b": 1, "c": "THIRD"}] print(d) print(sorted(d, key=lambda x: x["b"]))
7738a512670afe1612e0d49ce51ea5d0901809d8
akinovak/music_visualisation
/musical-genres.py
6,615
3.640625
4
""" Cilj rada je da se sto pribliznije moguce vizualizuju slicnosti (odnosno razlike) muzickih zanrova, koriscenjem genetskog algoritma. Podaci korisceni u radu preuzeti su sa: https://www.researchgate.net/figure/Relations-between-liking-for-musical-genres-in-the-N332-participants-screened-for-the_fig1_33011082...
65d2d463767cb856379bed83e3987b6896446551
mrparkonline/ics4u_solutions
/09-28-2020/tuple.py
1,637
4.5
4
# Question related to Tuple Slide Deck # Q1) Create a list of tuples containing (a,b,c). Where b = a^2 and c = a^3. Let a be integers of 2 to user_input upper limit upper_limit = 30 result = [(a, a**2, a**3) for a in range(1,upper_limit)] print(result) # Q2) Create a deck of cards using tuples. Creating a fu...
81ea55e1c158529c9af4e2bc7df81648320f81ba
qorjiwon/LevelUp-Algorithm
/LeetCode/Leet_0024.py
1,111
3.671875
4
""" @ LeetCode 0024. Swap Nodes in Pairs @ Prob. https://leetcode.com/problems/swap-nodes-in-pairs/ Ref. @ Algo: LinkedList @ Start day: 20. 10. 05. @ End day: 20. 10. 05. """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solut...
fde2b33c370e40e49c1bb33e82f7797c772aded6
stufit/pycharm_test
/numpy예제/소스코드_예제/ch06/ex06-4.py
459
3.734375
4
#!/usr/bin/env python # coding: utf-8 # # 6.4 데이터형 객체의 개념 # In[1]: #p117 def func(x): x = 5 print('x(함수):', x) x = 3 func(x) print('x(메인):', x) # In[2]: #p118 def swap(aa, bb): print('2: id(aa)', id(aa), 'id(bb)', id(bb)) return bb, aa a=3 b=5 print('a=', a, 'b=', b) print('1: id(a)', id(a), 'id...
6874077a6cedea9a6b2d5a1f49a43431ba349f81
theksenia/hm7
/2.py
164
3.78125
4
a= int(input("Enter: ")) def fido(x): if x == 0: return 0 elif x == 1: return 1 else: return fido(x-1)+ fido(x-2) print(fido(a))
d0aed2b088e4d174f150970a19ec683c3633a1bb
duanwandao/PythonBaseExercise
/Day11(面向对象3)/Test07.py
1,417
4.375
4
""" 方法重写: 1.什么叫方法重写?如何重写? 前提: 继承关系,父类中存在某个方法,子类中将该方法重写实现一遍 overrides 2.重写有什么好处? 可以为父类中方法补充新的东西 3.什么情况下需要重写? 父类中的方法,不能满足需求的时候,可以使用重写 4.重写的时候注意事项: 1.方法名 方法名必须一致 2.参数 参数可以不同 3.返回值 与返回值无关 """ class Animal(object): def ...
1ced777666dbd99c44aa407f7b30524fe14320c0
liuhanyu200/pygame
/7/7-5.py
362
3.625
4
# coding:utf-8 promote = "\nHow old are you?" promote += "\n Enter quit to quit." active = True while active: age = input(promote) if age == 'quit': active = False continue if age != 'quit': age = int(age) if age < 3: print("free") if 3 < age < 12: print("$10...
01dc5136feb0d573fdfdddf26730ae7782ea8b79
dima-panchenko/Python
/week-2/5.Ход короля.py
512
3.90625
4
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if x2 == x1 and (y2 - y1 == 1 or y1 - y2 == 1): print("YES") elif y2 == y1 and (x2 - x1 == 1 or x1 - x2 == 1): print("YES") elif (x2 - x1 == 1 and y2 - y1 == 1) or (x1 - x2 == 1 and y1 - y2 == 1): print("YES") elif (x2 - x1 ==...
2eb17b1e47e94d09b4da2557c13d4a170466f3f2
Jeff2076/YOUTUBE
/youtube.py
1,131
3.828125
4
import time print("Do you want to start? (y,n)") start = input(">>>") if start == "y" or start == "Y": while True: time.sleep(1) print("[1] World Youtuber") print("[2] Asian Youtuber") print("[3] Europian Youtuber") print("[4] African Youtuber") print("[5] Others") 대륙 = input(">>>") i...
19049a97aa13aaa967d6ef8d5b09411c47620151
sharathoddiraju/firstcode
/Helloworld.py
437
4
4
def helloworld(myString): print(myString) myName = input("what is your name?") myVar = input("Enter a number: ") myVar2 = input("Enter another number :") if((myName == "santosh" and myVar == "0") or myVar2 == "5"): print("santosh is great") elif(myName == "raghu"): print("you are cool") else: prin...
22afefa9f19c238ea51b9f154ce412decf573157
NitinJRepo/Python
/Dictionary/1-dictionary.py
717
4.4375
4
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Nitin', 2: 'Nilesh', 3: 'Nitesh'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Nitin', 1: [...
e189db84272034517f80f883b8402af3e03cb6a4
bochenekk/codebrainers
/Pycharm-Projects/oop/day1/example2.py
154
3.84375
4
list = tuple a = [1,2,3,4,5] print(tuple(a)) print(list(a)) # dlaczego?? a = (1,2,3) b = [1,2,3] print(list(a)) print(b) print(list(b)) print(tuple(b))
3083442c2f53ee9288e12658e430c57b3c07c5b9
soumyajitray/Learning-Python
/Leet - Pascal's Triangle II.py
606
3.640625
4
import math class solution(object): # def combination(self,n, r): # return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r))) def pascals_trianglecombined(self, rows): # result = [] # for count in range(rows): # row = [] row = [] for e...
552bf152dc2e7a7d1ea31ae793c22e3ba4f0a5b4
acejang1994/SoftwareDesign
/hw2/compare.py
218
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 13:03:38 2014 @author: james """ def compare(x ,y): if x > y: return 1 if x == y: return 0 if x < y: return -1 print compare(4,6)
96cfbf1b793c5cd256dec3ddec70df5168c5e04e
Kuranio/Ejercicios-sencillos-en-Python
/Suma.py
124
3.796875
4
numero1 = int(input("Primer numero: ")) numero2 = int(input("Segundo numero: ")) numero3 = numero1 + numero2 print(numero3)
ae954512e5f67cdaaa7ae362128b1c6b15faba3f
qeedquan/challenges
/codeforces/749A-bachgold-problem.py
1,013
4.0625
4
#!/usr/bin/env python """ Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exact...
ced8513b0af26a36817ee35d4bc80e6b184dca16
JUNGEEYOU/python-algorithm
/6/1.py
397
3.8125
4
""" 선택 정렬 """ def selection_sort(a): """ 선택 정렬 함수 :param a: 리스트 :return: """ for i in range(len(a)): min_index = i for j in range(i+1, len(a)): if a[min_index] > a[j]: min_index = j a[min_index], a[i] = a[i], a[min_index] print(a) array ...
4aa9041c3a305efc16b73a687f01a59849f47718
stacygo/2021-01_UCD-SCinDAE-EXS
/06_Writing-Functions-in-Python/06_ex_4-12.py
851
3.5625
4
# Exercise 4-12: Check the return type def returns_dict(func): # Complete the returns_dict() decorator def wrapper(*args, **kwargs): result = func(*args, **kwargs) assert (type(result) == dict) return result return wrapper @returns_dict def foo(value): return value try: ...
cf694893b29f721e0b381c4fc7b896e8e225ab19
zantiago29/bicycle_industry
/bicycles.py
2,180
4.1875
4
class Bicycle(object): def __init__(self, model_name, weight, cost): self.model_name = model_name self.weight = weight self.cost = cost class BikeShop(object): def __init__ (self, shop_name, bicycle_inventory = {}, bicycle_markup = 0.0): self.shop_name = shop_name ...
df03b8d58b4cb0991c4bd75b41c1effb64a02bf6
dresenhista/python_thehardway
/check_list.py
1,581
4.09375
4
#Version3.0 #Changes: # -> perfect square works now # -> prime list uses less memory # -> list doesn't need to be sorted to use remove duplicates # -> refactoring the code to make it more pythonic #check if the number in a list is pair or even def check_parity(x): for i in x: if i%2==0: # if the rest...
de2cbd2d97567e6a2ad80e4d4b9279c5e26f924d
rownak-glitch/coding-test-
/task3.py
1,136
4
4
import click courses= {'0':['English grammar','John Smith '], '1': ['Mathematics','Lara Gilbert'], # used dictionary data structure '2': ['Physics','Johanna Kabir'], '3': ['Chemistry','Daniel Robertson'], '4': ['Biology','Larry Copper']} day=0 hour=0 co=0 routi...
9d1d5795f9004784ed358b7e5d0a25439e801fc1
manoel-alves/Exercicios_Python
/Curso_em_Video-Exercicios/ex065.py
473
3.96875
4
soma = cont = 0 inercia = 'S' while inercia != 'N': x = float(input('Digite um número: ')) if cont == 0: maior = x menor = x elif x > maior: maior = x elif x < menor: menor = x soma += x cont += 1 inercia = str(input('Quer continuar [S/N]? ')).strip().upper() ...
d99d8d3462d55c39056bed829c471b58061a64b8
KristinCovert/Bootcamp
/PythonProjects/test.py
4,737
4.03125
4
__author__ = 'Kristin' import random import time import re from nltk.tokenize import RegexpTokenizer #Welcome to translator & choice of how to put in text to translate def ca_speak_method(): print """\nOh my god, you are like, totally awesome 'cause you want to be more californian.\n""" time.sleep(2.5) print """So Dude...
b4c747feae3ca65e76b8071d12d8d8a08bddd4ad
guruc-134/Py_programs
/File_Dictionary.py
534
3.609375
4
"""file_name=input("enter the file name") fh=open(file_name) emails=dict() for line in fh: if line.startswith("From") : if not line.startswith("From:"): words=line.split() emails[words[5][:2]]=emails.get(words[5][:2],0)+1 print(emails) print() print(emails.items()) lst=sorted(emails....
40ab4926d52be1e6f9ba2bb9e7c655d421e3967c
SudherrSingidi/Learnings
/python/rps.py
5,092
4.0625
4
# from itertools import count # input_1 = input("Enter option for user1: ") # input_1 = input_1.lower() # if input_1 != "scissors" or input_1 != "rock" or input_1 != "paper": # for i in count(): # print("Dear user1,your input is invalid.please enter valid input") # input_2 = input("Enter option for user1: ") # ...
bef6ab5427693cf403f193728060b74296195b1e
Tim-Sotirhos/statistics-exercises
/probability_distributions.py
6,035
4.4375
4
# Probability Distribution import numpy as np import math from scipy import stats import matplotlib.pyplot as plt import pandas as pd # 1.) A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars. # Make a chart of this distri...
15a967200acede557583b34626d7119df92535b8
tommyphan8/verdant-octo-sniffle
/anagram.py
782
3.671875
4
#O(n^2) def anagram(a, b): temp = list(b) posA = 0 contSearch = True while(posA < len(a) and contSearch): posB = 0 found = False while(posB < len(b) and not found): if a[posA] == temp[posB]: found = True else: posB += 1 ...
bc270afd2f812ba2968201d391c93affd7e366cd
J14032016/LeetCode-Python
/tests/algorithms/p0094_binary_tree_inorder_traversal_2_test.py
432
3.53125
4
import unittest from leetcode.algorithms.p0094_binary_tree_inorder_traversal_2 \ import Solution, TreeNode class TestBinaryTreeInorderTraversal(unittest.TestCase): def test_binary_tree_inorder_traversal(self): solution = Solution() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3...
ed3f861200d65ef6c2d8d1be419570d193424b59
isaacmthacker/ProjectEuler
/bouncy.py
1,628
4.3125
4
""" Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decr...
987992775a32a546fb28126c0f101b25f7065ee5
joshuaMarple/phase-vocoder
/app/Duration.py
2,156
3.59375
4
""" Authors: Fernando (UPDATE HIS INFO) License: GPL 3.0 Description: This file contains functions that allows the user to change the pitch of a .wav Comments: None. """ import subprocess import os from sys import platform as _platform from lib import pydub def changeDuration(filename,percent): """ Input: file...
63157fbd4ebf5dc97075e0dfcb7fe981d2dd1114
DamManc/workbook
/chapter_3/83.py
358
3.765625
4
# Maximum Integer import random x_max = 0 count = 0 for i in range(1, 100): x = int(random.random() * 100) print(x, end="") if x > x_max and i != 1: print(" <== Update") count += 1 x_max = x else: print() print("The maximum value found was %d" % x_max) print("The maximum...
2259d51d59ef95c6dd830e4559909ad2ed3ea5d5
shuangyangqian/python_road
/utils/one_hundred/example17.py
568
3.84375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # author # email: shuangyang.qian@easystack.cn # irc: qsyqian # def func(my_str): i = 0 j = 0 k = 0 for n in my_str: if n.isalpha(): i += 1 elif n.isdigit(): j += 1 elif n.isspace(): k += 1 ...
5be9b51e708bbeaef1294169c8781b6c9ede7c44
hariprohandler/dataStructurePython
/queue/queue.py
607
3.84375
4
from collections import deque class Queue: def __init__(self): self.buffer = deque() def enqueue(self, data): # self.buffer.insert(0,data) self.buffer.appendleft(data) def dequeue(self): self.buffer.pop() def is_empty(self): return len(self.buffer) == 0 def s...
8472aca7a5a65ed83cc485258a50006575da9edd
karanbuddy500/Python-Basic-course-soluions-coursera
/gradedWeek4(4)_1.py
188
3.625
4
# For each character in the string saved in ael, append that character to a list that should be saved in a variable app. ael = "python!" lst = [] for i in ael: lst.append(i) app = lst
f0d67a0970d19fec8106712b90828f23ea54fa2c
yosef8234/test
/hackerrank/python/introduction/loops.py
771
3.984375
4
# -*- coding: utf-8 -*- # Loops are control structures that iterate over a range to perform a certain task. # There are two kinds of loops in Python. # A for loop: # for i in range(0,5): # print i # And a while loop: # i = 0 # while i < 5: # print i # i+=1 # Here, the term range(0,5) returns a list of i...
0a88f7f5a7a7f96d4f307388b28cad1257634816
khatuu/gwccompilation
/lc.py
947
4.21875
4
#imports the ability to get a random number (we will learn more about this later!) from random import * #Create the list of words you want to choose from. aList = ["Hamburger", "Hot Dog", "Salad", "Chicken", "Fish", "Soup", "Pancakes", "Spaghetti", "Pizza"] dList = ["Ice Cream", "Brownies", "Cookies", "Mochi Ice Cream...
bc9cd9c915ae480520b142e7850bb0d1aa2a6477
shamoldas/pythonBasic
/while_loop.py
116
4.03125
4
a=int(input("enter a number.\n")) b=int(input("input a number.\n")) while a<=b: print(a,end=' ') a=a+1
a0626a9d3ee955fd89292b166ad61136c5f3f738
pangguoping/python-study
/day4/写博客.py
3,658
3.8125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' with open('aa','r',encoding='utf-8') as f1: for line in f1: line_strip = line.strip() print(line_strip,bool(line_strip)) s = "print(123)" ''' """ '''例1:接收字符串,先把字符串转换为python代码,然后再执行该代码''' s = "print(123)" exec(s) '''例2:接收到的是代码,直接执行该代码''' s = "prin...
c0b203b9f9944f42c0304fa013e1d3e0e6b9658e
rohithn/tic-tac-toe
/src/game/game.py
2,081
4.3125
4
from abc import abstractmethod from game.board import Board class Game(object): """Base class for the Tic-Tac-Toe game.""" def __init__(self, board: Board): self.board = board @abstractmethod def start(self): """Main class that should be initialized.""" pass def play(se...
3beca9839907a5408d950a538fc1b0637bfa60e2
jinzhe-mu/muwj_python_hm
/01_python基础/introduce_变量命名规则.py
1,964
3.953125
4
""" 变量的命名 目标 标识符和关键字 变量的命名规则 0.1 标识符和关键字 1.1 标识符 标示符就是程序员定义的 变量名、函数名 名字 需要有 见名知义 的效果,见下图: 001_中国山东找蓝翔 标示符可以由 字母、下划线 和 数字 组成 不能以数字开头 不能与关键字重名 思考:下面的标示符哪些是正确的,哪些不正确为什么? fromNo12 from#12 my_Boolean my-Boolean Obj2 2ndObj myInt My_tExt _test test!32 haha(da)tt jack_rose jack&rose GUI G.U.I 1.2 关键字 关键字 就是在 Python 内部已经使用...
5e7b6da54584cf4801292fc8888363a0e99be121
baxtiyor-gis/python-exe
/main.py
1,988
3.5625
4
from tkinter import * from tkinter import ttk # Create window object app = Tk() app.title("Noemnkaltura xisoblash") app.geometry("800x300") def show(): k = float(kenglik.get()) u = float(uzoqlik.get()) m = masshtab.get() if m == "1:1000 000": print("1:1000000") title = Label(app, t...
7f93119aa2a0aa197766d48fa5ddfee8814dadec
0x0400/LeetCode
/p53.py
511
3.625
4
# https://leetcode.com/problems/maximum-subarray/ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: maxNum = nums[0] curNum = None for n in nums: if curNum is None: maxNum = max(n, maxNum) if n > 0: ...
9e88b11c27ad53dbd5929bd00f05d18d3a54c6e2
YWFANK/guess
/guess.py
723
3.96875
4
import random lower_bnd = input('Enter an integer as a lower bound: ') upper_bnd = input('Enter an integer as a upper bound: ') lower_bnd = int(lower_bnd) upper_bnd = int(upper_bnd) r = random.randint(lower_bnd, upper_bnd) try_number = 0 while True: print('Enter an integer btw ',lower_bnd,' and ', upper_bnd, ': ') ...
07ecd9e877922991f9ec8f7be33e6a349edfdfea
Ahmed-Mosharafa/Algorithms-problems-and-training
/modified_kapreker_numbers.py
334
3.578125
4
import math x = int(raw_input()) y = int(raw_input()) answer = "" for i in xrange(x,y+1): ind = "1" squared = i**2 ind += "0" * int(math.ceil(len(str(squared))/2.0)) if (squared%int(ind) + squared/int(ind)) == i: answer += str(i) + " " if answer != "": print answer.strip() else: print "...
50c8cefcff8f2afa86b862309ca1a7ea1f3d3e8f
asen-krasimirov/Python-Advanced-Course
/5. Functions Advanced/5.2 Exerceses/Problem 11- Age Assignment.py
319
3.78125
4
def age_assignment(*names, **age_data): ages_by_name = {} for name in names: first_letter = name[0] ages_by_name[name] = age_data[first_letter] return ages_by_name # print(age_assignment("Peter", "George", G=26, P=19)) # print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))
775c160329e3c6c96aec87bf285fc2d53fe32212
dhruv-rajput/data-structures-and-algo
/random/topdownFibonacci.py
266
3.796875
4
def fib(n, lookup): if n == 0 or n == 1 : lookup[n] = n if lookup[n] is None: lookup[n] = fib(n-1 , lookup) + fib(n-2 , lookup) return lookup[n] n = 9 lookup = [None]*(101) print ("Fibonacci Number is ", fib(n, lookup))
dcd4679882db1fa852c33a5e28255d75864b91f8
Herophillix/cp1404practicals
/prac_05/word_occurences.py
720
4.25
4
""" Count the number of repeated words in a text """ def main(): """Ask the user to input a text, and count the number of repeated words""" count_of_words = {} text = input("Input text: ") for word in text.split(): word = word.lower() if word in count_of_words: count_of_wo...
e3c21101f139079d4ff885b2e743c9ed33fd3c6f
priyaliverma/python-examples
/is_palindrome.py
847
3.859375
4
a = "pkafbj1483u40ue" # print a.isalnum() # given_string = "Madam I'm Adam" # given_string = given_string.lower() # print given_string # given_string = ''.join(x for x in given_string if x.isalpha()) # print given_string # print given_string[len(given_string)/2] def is_palindrome(given_string): given_string = ''.jo...
bac7566231977709308df24888c9d6a6ca465bac
prabal1997/Cracking-The-Coding-Interview-Python
/arrays_and_strings/1_1_a.py
816
3.765625
4
import sys input_string = "art"; #ALGORITHM EXPLANATION: we go through each letter, put it into hashmap. If collision occurs, then repetitione existed. #NOTE 1: this runs in O(n) time, assuming the hash-table provides an average rutime of O(1) #NOTE 2: If you were to use the 'try'-'except' approach, know that the run...
2e6aff6ce794ce43cfe47d6fd9d59cadc226a3e5
shahlaaminaei/python-learning
/ex - advance6.py
365
3.671875
4
word_list = {} num = int(input()) while num > 0 : num -= 1 words=input().split() word_list[words[1].strip()]=words[0].strip() word_list[words[2].strip()]=words[0].strip() word_list[words[3].strip()]=words[0].strip() sentence = input().split() result="" for word in sentence: result+=" "+word_l...
77d8fc8ad7faa260c9f9cfc6785295f782c715ea
murawskikrzysiek/kurs_python
/notes_4_lokaty.py
2,107
3.859375
4
import time def trigger(f): def g(self, *args, **kwargs): while self.do_trigger: time.sleep(0.1) f(self, *args, **kwargs) return g class DepositAccount: def __init__(self, name, investment): self.name = name self.amount_of_money = 1000 self.investm...
c0e9a88eb60a9e0f54d0f0313147a2ef2355c5f8
statistics-exercises/t-tests-10
/main.py
1,275
3.78125
4
import matplotlib.pyplot as plt import numpy as np def sample_variance( data ) : # Your code to compute the sample variance goes here def common_variance( data1, data2 ) : # Your code to compute the common variance using the formula in the # description on the left goes here # This code generates the...
cd187670b4ca939919d955e25ce6d465f89b33e7
Ham4690/AtCoder
/abc162/b.py
221
3.75
4
def isFizzBuzz (N): if N % 15 == 0 : return 0 elif N % 3 == 0: return 0 elif N % 5 == 0: return 0 else: return N N = int(input()) ans = 0 for i in range(1,N+1): ans += isFizzBuzz(i) print(ans)
bb5b127f00857cc92e2f92ce894d62123cbddba1
ech1/Random-Scripts
/Python/17.py
327
3.921875
4
nterms = 10 n1 = 0 n2 = 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibo sequence upto", nterms, ":") print(n1) else: print("Fibo sequence upto", nterms,":") while count < nterms: print(n1, end=' , ') nth = n1 + n2 #update values n1 = n2 n2 = nth coun...
38c4cc3ef45f8de2d06377304a29a3bdfd1fc895
anoop600/Python-Basics-Learn
/4. Looping/random_module.py
985
4.09375
4
import random def get_integer(prompt): while True: temp = input(prompt) if temp.isnumeric(): return int(temp) highest = 10 answer = random.randint(1,highest) print(answer) # TODO: Remove this line after testing print("Please guess number between 1 and 10: ") guess = get_integer("Enter...
3b4e2a1b82ba6b1f34f2558b65e17daaa34cdd2a
imyourghost/python
/hw1/home_work1.py
2,870
3.9375
4
good_answer=0 user_input = input ('Какой язык мы учим? ') if user_input.lower() == 'python': print ("Красава!\n") good_answer += 1 else: print ("Неправда\n") user_input = input ('Какая фамилия у препода? (ответ пишем на инглише) ') if user_input.lower() == 'sobolev': print ("Он самый\n") good_answer += 1 else: p...
67074c08182c5958ba967ad5b99a1a431536f251
sshukla31/misc_algos
/misc/coin_dice.py
1,802
4.34375
4
#! /usr/bin/python # -*- coding: utf-8 -*- """ Coin
Flipping
and
Die
Rolls Algorithm Solution Flip
the
coin
three
times and
use
the
three
coin
flips
as
the
bits
of
a
 three bit
number.
If
the
number
is
in
the
range
1
to
6,
output
the
number.

 Otherwise repeat. """ import random # Generate random number...
377584efb23359ce3fbb461618cacfcc9105b3c8
Godson-Gnanaraj/DSA
/arrays/sorting/quick_sort.py
486
3.859375
4
def quick_sort(arr, left, right): if left >= right: return pos = left - 1 for i in range(left, right): if arr[i] <= arr[left]: pos += 1 arr[i], arr[pos] = arr[pos], arr[i] arr[pos], arr[left] = arr[left], arr[pos] quick_sort(arr, left, pos - 1) quick_sor...
a0510527f097819d5cbe0365d6514a8f5736bbdf
randomguy069/Python-tutorial-complete
/Day7/datesandtimes.py
220
4.3125
4
import datetime print(datetime.datetime.now()) yes = datetime.datetime(2017,3,24,11,2,27,0) now1= datetime.datetime.now() print(yes," ",now1) sub = now1 - yes print(sub.days) #prints the number of days between two dates
26fee7fb9a26f97279b3d3553ff8a581afd6409c
apastewk/Twilio-API
/model.py
1,374
3.53125
4
"""Models for my database to store questions questions.""" import os from flask_sqlalchemy import SQLAlchemy # This is the connection to the PostreSQL database. Getting the through the # Flask-SQLAlchemy helper library. db = SQLAlchemy() ############################################################################...
b465348f21b0be49bf4e0b4da56961902cd7ab8a
circularpenguin/poly
/poly.py
421
3.703125
4
def poly_diff(p): deg_p = len(p) - 1 if deg_p == 0: return [0] else: return [k*p[k] for k in range(1,deg_p+1)] def poly_eval(p,a): """Given a list representing the coefficients of a polynomial in increasing order and a, return p(a)""" cumsum = 0 for n,t in zip(p, r...
8c24a4e2555d72445a39f644c5110178b0dc7143
malomodaniels/PyCodes
/Grading_System.py
623
4.3125
4
name = input("Enter your name: ") if name: score = int(input("Enter score: ")) if score > 100: print(f"{name}, please enter a valid score") elif score >= 70: print(f"{name}, your grade is A") elif score>=60: print(f"{name}, your grade is B") elif score>=50: print(f"{name}, your grade is C") elif score>...
cc2f60cafc15fb17482307874330d807a8e77914
karen-edith/Wallbreakers
/Week2/mostCommonWord.py
1,357
3.625
4
from collections import defaultdict class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: # create a words counter initiated with 0 as values # create a punctuation array wordsCounter, punctuation = defaultdict(int), ['?', '!', ',', ';', "'", '.'] #remo...
502b1a2bd613b795c4e886d8398ba2d8cbc2ea28
AceRodrigo/CodingDojoStuffs
/Python_Stack/_python/OOP/Rodriguez_Austin_VS_User.py
967
3.59375
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_deposite(self, amount): self.account_balance+=amount def make_withdraw(self, amount): self.account_balance-=amount def display_user_balance(self): ...
37de9c37663ff02faff3dcf5b53b3c76149b44e1
MarshalLeeeeee/myLeetCodes
/44-isMatch.py
6,471
4.25
4
''' 44. Wildcard Matching Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s cou...
84eddcd4b549d80a56d868e6e12a362b9a0794d4
ljordan51/ToolBox-Unittest
/unittest_practice.py
390
3.65625
4
import unittest def sort_and_rm_neg_num(num_list): edited = [] for num in num_list: if num >= 0: edited.append(num) return sorted(edited) class TestMethod(unittest.TestCase): def test_func(self): self.assertEqual(sort_and_rm_neg_num([3, -4, 2, 6, -1, -8, 7, 3, 2, 1]), [1...
a461534953cf4d367e2ce0b81d25b99d01624c26
sourabhcode/python
/listoverlap_old.py
602
4
4
#!/usr/bin/python x = input ("What is size of first list:") print "Size1 :", x y = input ("What is size of second list:") print "Size2 :", y list1 = list() list2 = list() list3 = list() for i in range(x): num1 = input("enter the number:") n1 = list1.append(num1) print "first list is:", list1 for i in range(y): ...
be9618b3747fb76326efe50764e4872f874049b8
FidelSol/-Python-GeekBrains
/-Python-GeekBrains--_7_PYTHON/урок №7 Соловьев Ф.М..py
3,707
3.703125
4
# Задание №1 class Matrix: def __init__(self, *args): self.list_of_lists = [] for n in args: self.list_of_lists.append(n) def __str__(self): for n in range(0, len(self.list_of_lists)): print(self.list_of_lists[n]) if len(self.list_of_lists[n]) != le...
3d380924980b41e28c1a20f538cc441199213b77
Vortes/Regular-Expressions
/basic.py
226
4.125
4
import re #* Say you want to find a phone number using regular expression message = 'Call me at 732-668-6908 or 646-671-0903' phone_number = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phone_number.findall(message) print(mo)
2062b8bb8ddb6764dce15e2319b107bf68470cba
stevenzim/lrec-2018
/src/waseem.py
1,262
3.5625
4
'''Function to load Waseem/Hovy tweets set 1 and classes from csv and return lists of data''' # Load datasets import csv # shuffle data (the tsv files are grouped by racism, sexism and none) import random from random import shuffle random.seed(21) def get_hate_data(): X_hate_raw = [] Y_hate_raw = [] with...
81638aa69effdaf7490439113a999edd9f6ad03e
priyanshukumarcs049/Python
/Day2/The Minion Game.py
381
3.65625
4
def minion_game(string): # your code goes here vowels = 'AEIOU' kevin = 0 stuart = 0 for i in range(len(s)): if s[i] in vowels: kevin += (len(s)-i) else: stuart += (len(s)-i) if kevin > stuart: print ("Kevin", kevin) elif kevin < stuart: ...
40dd98b54f00d94e43877d046e0b5341f225fd9f
GeraldineE/Curso-python
/interfaces_graficas/tkinter/tk_label.py
232
3.78125
4
from tkinter import * root = Tk() labelframe = LabelFrame(root, text = "This is a LabelFrame") labelframe.pack(fill = "both", expand = "yes") left = Label(labelframe, text = "Inside the LabelFrame") left.pack() root.mainloop()
49760a6eddd8f0b9c7b3ced820b961a0ea3a9015
bellfive/utils
/python/backup/backup_jwfreeNote.py
873
3.59375
4
# -*- coding: utf-8 -*- # backupToZip.py import zipfile, os def backupToZip(folder) : folder = os.path.abspath(folder) number = 1 while True: zipfileName = os.path.basename(folder)+'_'+str(number)+'.zip' if not os.path.exists(zipfileName): break number +=1 print 'Creating %s....' % zipfileName backup...
1159db0477e002d466638fa23cb7592073746a28
Carl-Aslund/project-euler
/problem010.py
566
3.984375
4
from math import sqrt def primeSieve(n): """Uses the Sieve of Erastothenes to find all primes less than n.""" primes = [] for i in range(2,n): isPrime = True root = sqrt(i) for p in primes: if p > root: break if i%p == 0: isPri...
8f5ddf39ad90e9bc52e45f61a2601ecfef437f02
alecbar/data-structures-and-algorithms
/Binary Search/binary_search.py
688
4.0625
4
# Binary Search Algorithm # O(log n) def binary_search(arr, item): """ Takes a sorted list of items and an item to look for Reeturns the index of the item in the list or none if not found """ low = 0 # Frst index high = len(arr) - 1 # Last index while low <= high: mid = (low + hig...
d8b8496522424bb9a51e45a23987c338583b2c86
NoouFoox/DoubanCrawler
/homework/t2.py
1,434
3.71875
4
# -*- coding:utf-8 -*- # @author: 贺俊浩🐱 # @file: t2.py # @time: 2021/6/29 8:48 itemlist = [ {"name": "板烧鸡腿堡", "pice": 16}, {"name": "巨无霸", "pice": 15}, {"name": "麻辣鸡腿堡", "pice": 16}, {"name": "芝士汉堡包", "pice": 19}, {"name": "培根牛肉堡", "pice": 19} ] print("{0:*>48}".format("")) print("欢迎光临小包子的汉堡店!") pr...
fc19c923f8aad596bff9e6705649012d6c7bddec
m-amoit/Python-recap
/BuildingSkills/is_triangle.py
583
4.34375
4
def is_triangle(a, b, c): ''' Check whether the given lengths can form a triangle. If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise you can. Print 'yes' if you can form a triangle, Otherwise print 'yes'. ''' if a > b + c: return 'No' el...
16318a40dbaf739fb6a258fa498cdee8b923f3ae
catr1ne55/epam_training_python
/lec1/hw/task5.py
159
3.734375
4
a = int(input()) b = int(input()) if a < b: a, b = b, a while True: rn = a % b if rn % b == 0: print(b) break a = b b = rn
91e6200a2fdc685c48d9868a513df48edb91958a
tkim92/Python-Programming
/school_labs/lab2/olympic.py
1,202
3.875
4
import turtle turtle.showturtle() def Drawcircle(radius): turtle.speed(0) scaled_radius = radius/100 #bluecircle turtle.penup() turtle.left(180) turtle.forward(300*scaled_radius) turtle.left(90) turtle.pensize(7) turtle.pendown() turtle.color("blue") turtle.circle(radius) ...