blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8a25b07e40fb6859fdbd7d6e26f3a36fe95b7087
waithope/leetcode-jianzhioffer
/剑指offer/17-打印从1到最大的n位数.py
2,319
3.90625
4
# -*- coding:utf-8 -*- ''' 打印从1到最大的n位数 ========================== 输入数字n,按顺序打印从1到最大的n位十进制数。比如输入3,则打印出1、2、3 一直到最大的3位数999 ''' def print1ToMaxOfNDigits(n): ''' 提示:由于没有规定n的范围,当输入的n非常大的时候,可能会出现溢出的情况, 也就是说我们要考虑大数问题。 ''' def incrementBy1(nums): isOverflow = False carry = 1 for i...
d37300a9674231ae93cd74607fb136059bcc9ac0
leodengyx/LeoAlgmExercise
/DataStructure/Queue/linked_queue.py
2,314
4.28125
4
class Node(object): ''' Defines a class for Queue Node ''' def __init__(self, value=None): self.value = value self.next = None def __repr__(self): #return "{value: %s, next: '%s'}" % (self.value, self.next) return str(self.value) def __str__(self): retur...
2086a97245aaa323671d6c587d3f1be6993558f8
shasha9/30-days-of-code-hackerrank
/Day_22_Binary_Search_Trees.py
671
4.21875
4
#Task #The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. #You are given a pointer,root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree. def getHeight(se...
17f5b1773906e9bdb0e1dc5d745092037a4e15f8
nrndll/roguelike_tutorial
/action.py
1,136
3.5
4
class Action: def perform(self, engine, entity): # do this within the engine, entity performs the action # this raises an error and so Action must be overridden by one of the subclasses raise NotImplementedError() # action when escape is pressed, exits program class EscapeAction(Ac...
2df07640c4586f83b7d5e1bc72bc69dc03b9f476
ThisIsJorgeLima/DS-Unit-3-Sprint-2-SQL-and-Databases
/module4-acid-and-database-scalability-tradeoffs/practice_on_titanic (1).py
2,132
3.609375
4
import pandas as pd import numpy as np import sqlite3 import psycopg2 !pip install psycopg2-binary df = pd.read_csv('https://raw.githubusercontent.com/EvidenceN/DS-Unit-3-Sprint-2-SQL-and-Databases/master/module2-sql-for-analysis/titanic.csv') df.head() # In case we have issues with spaces and /: df.columns = df.col...
66a28b65bab0ef1f85625288b7e04a37be036771
JohnBrown19/TTS_Notes
/DS/Day 5/Hackerrank exercises Day 5.py
898
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 11:13:25 2020 @author: Jbrown """ #Exercise 1 from itertools import product X = list(map(int, input().split())) Y = list(map(int, input().split())) XCrossY = product(X, Y) print(*XCrossY) #Exercise 2 from itertools import permutations def Permutations(str, num): ...
a7241f4b617ab69e21b4a12fed29392376c4fdf2
Viola8/Python-Exercises
/dct4.py
724
4.15625
4
# Write a Python program to multiply all the values in a dictionary. dct = {'a':1,'b':2,'c':3} answer = 1 for key in dct: answer = answer * dct[key] print(answer) # Write a Python program to remove a key from a dictionary. # 1 using pop() dct2 = {'a':2,'b':4,'c':6,'d':8} dct2.pop("a") print(dct2) # {'b'...
f34f023d1a9a7d8668b7c2e756ad602710a6f424
theyujisamfull/EP-Google
/tarefa2.py
8,555
3.96875
4
# Define funçoes para operar com matrizes e vetores def mult(A,b): '''Multiplica uma matriz quadrada por um vetor''' return( [sum( A[i][j]*b[j] for j in range(len(A)) ) for i in range(len(A))] ) def soma(A,B): '''Soma duas matrizes quadradas de mesmo tamanho''' return( [A[j] + B[j] for j in range(len(...
f768de451b36a9b17d4086efc0d78307f1b09cbc
Foundations-of-Applied-Mathematics/Advanced-Programming
/2018_WinterMaterials/SolutionsToHardProblems/components-in-graph.py
2,489
3.875
4
# This solves each test case for https://www.hackerrank.com/challenges/components-in-graph/problem # by implementing a DisjointSet: See https://en.wikipedia.org/wiki/Disjoint-set_data_structure # Note: this does not implement path compression or flattening, as it is not needed for this problem. class DisjointSet: ...
77c23723b7493b8b50781957fc979f9d74601c2a
Rashinkar/Practice
/Infitq2.py
1,515
4.125
4
#Write a Python program to calculate the bill amount to be paid by a customer based on the list of gems and quantity purchased. Any purchase with a total bill amount #above Rs.30000 is entitled for 5% discount. If any gem required by the customer is not available in the store, then consider total bill amount to be -1....
4f53c9a15adb535a34b51cb11a5df1421e243f15
AdamZhouSE/pythonHomework
/Code/CodeRecords/2158/60835/267424.py
734
3.78125
4
origin = input() result = 0 is_neg = False is_effect = True origin = origin.lstrip().rstrip() if origin[0] == '-': is_neg = True origin = origin[1:] elif origin[0] >= 'a' and origin[0] <= 'z': is_effect = False elif origin[0] >= 'A' and origin[0] <= 'Z': is_effect = False mid = "" n = 0 while n < len(or...
113cb18529ac12307bed4b49a6e405b554a8da33
IMDCGP105-1819/portfolio-S197615
/ex6.py
924
4.1875
4
Name = input("What is your name?") Age = input("What is your age?") Height = input("What is your height in inches?") Weight = input("What is your weight in pounds?") EyeColour = input("What is your eye colour?") HairColour = input("What is your hair colour?") if Age >= str(46): print("You're older than most"...
2e11e47d45ef4c435cae3c5bcd6b8fa05643cf29
chandni540/tathastu_week_of_code
/Day 6/program9.py
266
4.0625
4
n = int(input("\nEnter size of your list:")) li=[] for i in range(n): list.append(int(input("Enter element :",i+1))) print("\nThe list is:",list) k= int(input("\nEnter the value of k:")) sort = sorted(li) print("\nThe kth smallest value in list is=",sort[k-1])
7bcfb18ecd7aa5e5ef317b885baffb4ff03ce4db
pleielp/apss-py
/Ch04/4.06/jiho.py
251
3.671875
4
def factor(n): primes = [] div = 2 while n > 1: if n % div == 0: n = n // div primes.append(div) continue div += 1 return primes if __name__ == "__main__": print(factor(9999))
eb7f1c107dc3356cb005694afc3cd0b4c3d6148d
protea-ban/Python_House
/026Python绘制具有描边效果和内部填充的柱状图.py
391
3.640625
4
import numpy as np import matplotlib.pyplot as plt #生成测试数据 x = np.linspace(0, 10, 11) y = 11 - x plt.bar(x, y, color = '#772277', alpha = 0.5, edgecolor = 'blue', linestyle = '--', linewidth = 1, hatch='*') # 为每个柱形添加文本标注 for xx, yy in zip(x, y): plt.text(xx-...
052fd21de45e56e3f4cc649999b1c5c1aa4c60b1
adanyear1/Learn-Python-The-Hardway
/ex33.py
652
4.3125
4
i = 0 numbers = [] #while-loop will iterate 6 times or 0 - 5 while i < 8: print(f"At the top i is {i}") numbers.append(i) #print each statement 6 times 0 - 5 i = i + 2 print("Numbers now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) print("Code bellow wi...
cf4ecdbed2b9b82ada3585b08cd831069ef6c9a5
shweta2425/ML-Python
/Week1/Program36.py
425
4.0625
4
# Write a Python program to determine if variable is defined or not. x = 'aa' #checks if it contains any error try: x > 1 #execute if try block raises name error except NameError: print("You have a variable that is not defined.") #execute if try block raises data type error except TypeError: print("You are compa...
1a1234183d976be5697747d49348b13b8521e08c
Earthnuker/Py_Intel_8008_Emu
/Stack.py
494
3.609375
4
class Stack(object): def __init__(self,levels,width,memory): self.levels=levels*2 self.width=width self.stackmem=memory.mem[:self.levels] def push(self,value): value=value&((1<<self.width)-1) for b in int.to_bytes(value,2,'little'): self.stackmem.insert(0,b) self.stackmem=self.stackmem[:self.levels...
47114cd6b386756f13ba2b0dd892209694417111
Th3Lourde/l33tcode
/problemSets/300/practice/528.py
667
3.5625
4
import random class Solution: def __init__(self, w): self.arr = w self.n = len(w) for i in range(1, self.n): self.arr[i] += self.arr[i-1] self.s = self.arr[-1] def pickIndex(self): rand_num = random.randint(1, self.s) l = 0 r = len(self.ar...
b1f7a333ea001d21eb06ffa5c7a12cd3dfc77ed6
kalpajpise/Tik-Tak-Toe
/Game.py
4,582
4.0625
4
import random def player_input(): # Input for the player marker = '' while not (marker == 'X' or marker == 'O'): marker = input('Player 1: Do you want to be X or O? ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X') # test cases for the marker genera...
d47f3ac5271c75510479148a647c31a7111439b1
kses1010/algorithm
/programmers/level2/target_number.py
562
3.640625
4
# 타겟 넘버 def solution(numbers, target): n = len(numbers) count = 0 # dfs 트리층, 합계 def dfs(layer, total): if layer == n: if total == target: nonlocal count count += 1 else: # 마지막 노드까지 못갔다면 dfs 재귀 dfs(layer + 1, total + n...
29efff3f5997e5fe1ae628d205572ee97b305d8c
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc097/A/4927590.py
152
3.796875
4
l = [int(i) for i in input().split()] print("Yes" if ((abs(l[0] - l[1]) <= l[3]) & (abs(l[1] - l[2]) <= l[3])) or (abs(l[0] - l[2]) <= l[3]) else "No")
ec184b71ea3d7b20ba797f964961fd336987eddd
Payaj/test
/NameMatch.py
6,739
3.890625
4
import numpy as np import pandas as pd import re import math ##################################################### #1. This section creates the bigrams of the names. These bigrams will be the input of the jeccard index formula/function #################################################################### ##############...
75aa8e01a99712e1a7cd1904c91e1768ba1986b1
lsifang/python
/python核心/python面向对象/python类属性.py
2,402
4.21875
4
class Money: age=18 count=1 num=666 s=Money() Money.name='hello' print(s.age) print(Money.age) print(Money.name) print(s.name) print(s.__class__) print(Money.__name__) print(Money.__class__) print(dict.__class__) print(dict.__name__) #所有说,变量类型就是一个类(__class__)。而我们自定义一个类就相当于自定义了一个变量类型 a=str('hello ersbad asd...
5cc447777d08b82dd20bd962415d26c3319e0e53
yo-mama-yo-papa/simple_rock_paper_scissors_game
/main.py
1,009
3.859375
4
import random while True: rps = ["ROCK", "PAPER", "SCISSORS"] computer_answer = random.choice(rps).lower() player_answer = (input("Rock paper or scissors?\n")).lower() if computer_answer == player_answer: print(f"You both answered {computer_answer}, tie.") elif computer_answer =...
aa701754c947b73065439e8fdfd1c66865284a88
ablimit/cs130r
/solution/hw/hw1/leapyear.py
322
4.09375
4
year = int(input("Please input the year: ")) flag = False if year % 400 == 0: flag = True elif year % 100 == 0: flag = False elif year % 4 == 0: flag = True else: flag =False if flag: print ("Year", year, "is a leap year.") else: print ("Year", year, "is NOT a leap year.") ...
c50db1a7bd428a87b051c7c7f147b3241615019a
VarunGogia101/Sales_Prediction
/Advertising.py
1,352
3.890625
4
# coding: utf-8 # import necessary modules import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression # read the csv file using pandas data = pd.read_csv('/home/ubuntu/Desktop/Advertising/Dataset_advertise.csv', index_col = 0) # Get all the features in a Dataframe X = data[['TV', 'Rad...
5063123c9a06e789549ca24e84ba56409bfcdca4
bharatmazire/Python
/Programs/Basic/RegularExpressions/start_end_same.py
354
3.984375
4
#!/usr/bin/python # WAP where 1st word of line present at end import re def main(): sentence = input("enter your sentence : ") sent = re.split(" ",sentence) first = sent[0] first = first + "$" #print (first) if re.search(first,sentence): print ("1st and last same") else: print("1st and last not same") i...
885073cef4316c23fd68c94bf119bf969918343f
r-malon/python-code
/question_marks.py
470
3.625
4
def qmark(x): num_list = [] for i in x: if i.isdigit(): num_list.append(x.index(i)) print(x.index(i)) for i in range(0, len(num_list), 2): #if '?' in x[num_list[i]:num_list[i + 2]]: if x[num_list[i]:num_list[i + 2]].count('?') != 3 and '?' in x[num_list[i]:num_list[i + 2]]: return False return True ...
3ad9822dc416b325b2e2c5a072a53bf3e1cb27dd
yqdl945/Data-analysis
/dataquest数据处理/dataquest-cleandata.py
2,927
3.578125
4
#!/usr/bin/env python # coding: utf-8 # # Introduction: The beginning of DA&DS # ## Over there, # In[ ]: from csv import reader open_apple_file = open('AppleStore.csv') open_google_file = open('googleplaystore.csv') apple_data = reader(open_apple_file) google_data = reader(open_google_file) apple_data_list = list...
791101ead24338dc3ced07592b30ba3758c26597
khanma1962/Data_Structure_answers_Moe
/100 exercises/day17.py
1,719
4
4
''' Question 65 Question Please write assert statements to verify that every number in the list [2,4,6,8] is even. ''' def assert_list(lst): for i in lst: # print(i) assert i % 2 == 0 # assert_list([2, 4, 6, 7, 8]) """ Question 66 Question Please write a program which accepts basic mathematic exp...
0b579ff701e5fae79e7593e56343fe54418776e6
Rainboylvx/pcs
/loj/10085/data_generator.py
1,448
3.640625
4
#!/usr/bin/env python from cyaron import * #=== 字符串 # s1 = String.random(5) # 生成一个5个字母的单词,从小写字母中随机选择 # s1 = String.random((10, 20), charset="abcd1234") # 生成一个10到20个字母之间的单词,从abcd1234共8个字符中随机选择 # s1 = String.random(10, charset="#######...") # 生成一个10个字母的只有'#'和'.'组成的字符串,'#'的可能性是70%,'.'可能30%。 # s1 = String.random_sentence(...
c1da7e9ec5b2d8555e392c80a094f1b6f99726ae
jadhavrk/leetcode
/114-Flatten-Binary-Tree-to-Linked-List.py
1,936
4.0625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place ...
4ed448fcfe9de2e4330d8f5ad319cbcfce032015
chapman3/syllagetter
/dbOperations.py
2,777
3.84375
4
import sqlite3 def init(): ''' Usage: creates the wordbank.db database Args: none Returns: 1 if created 0 if already existed ''' try: print("Initialising Database") connection = connect() print("Creating Inventory Table") sql_command = """CREATE TABLE wordbank (word VARCHAR(30) PRIMARY KEY,...
c063efeb9843c4f24ced05b926153bbfbd5faf96
domkozz/Repozytorium
/laboratoria/LAB2-zad/zad6.py
374
3.859375
4
a=int(input("Podaj a: ")) b=int(input("Podaj b: ")) c=int(input("Podaj c: ")) d=int(input("Podaj d: ")) if a>b and a>c and a>d: print("Największą liczbą jest a: ",a) elif b>a and b>c and b>d: print("Największą liczbą jest b: ",b) elif c>a and c>b and c>d: print("Największą liczbą jest c: ",c) elif d>a and d>b and d...
5bd4089d8a599fd871898a105137801dd6dd706c
mellumfluous/cs50w
/project1/import.py
1,655
3.6875
4
# Run *once* to create the necessary tables and insert the books into them. # If the table(s) is/are already created, comment out the corresponding CREATE TABLE line(s) import csv import os from dotenv import load_dotenv from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionma...
298ad13a3b3ed5e0e15cfd3edddc235f63c41416
jessicagamio/stack_min
/stack_min.py
1,255
4.1875
4
class Stack(): """ build a stack that will show you the most current minum value in stack """ def __init__(self): self._stack = [] self.min = [] def push(self, item): """ append item to stack. If min is empty append to item to min elif item...
c1c765ae3429710f435b26e8c4eac0906ba2f397
kdaivam/data-structures
/linkedlists/random_double_linked_list.py
2,140
3.90625
4
from double_linked_List_prototype import DoubleListNode from collections import deque def print_double_linked_list_forward(head): nodes = deque() while head: nodes.append(head.data) head = head.next while nodes: print(nodes.popleft()) def print_double_linked_list_backward(head): ...
e8464aaca4759ee27d135fd3bb4170e256c95aa1
brandle26/Learning
/Section 6 -Working with data part 2/Lec 35 - Duplicates in DataFrames/Duplicates_in_dataframes.py
645
3.796875
4
import numpy as np import pandas as pd from pandas import Series,DataFrame dframe=DataFrame({"key1":["A"]*2+["B"]*3, "key2":[2,2,2,3,3]}) print(dframe) #finding duplicate rows print("="*50) print(dframe.duplicated()) #droping duplicates print("="*50) print(dframe.drop_duplicates()) ...
2b5068d1ba555495460cba7103841b08a38632bf
kevinhenry/data-structures-and-algorithms
/python/code_challenges/stack_queue_animal_shelter/stack_queue_animal_shelter.py
1,263
3.625
4
class InvalidOperationError(BaseException): pass class Node: def __init__(self, value, next=None): self.value = value self.next = next class AnimalShelter: def __init__(self): self.front = None self.rear = None def __str__(self): if self.front == None: ...
ec74f4c2083bcfbcb5730359ee564203d27f45c9
LPRowe/coding-interview-practice
/old_practice_problems/arcade/the-core/medium/equalPairOfBits.py
1,147
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 21 01:26:30 2020 @author: Logan Rowe Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. You're given two integers, n and m. Find position of the rightmost pair of equal bits in their binary representations (it is guaranteed that su...
d103bf9aacd32879ac9a1c12abaefecc47bbd083
alexandraback/datacollection
/solutions_5744014401732608_1/Python/alberist1/b.py
586
3.5
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- def solve(): b, m = map(int, input().split()) if 2**(b-2) < m: return 'IMPOSSIBLE' m -= 1 result = ['POSSIBLE'] for i in range(b): line = '' for j in range(b): if (i == 0 and j == b-1) or (j > i and (j != b-1 or (m & (1...
cb47d49e9889046535b7d2d3479606bf0943c300
Jdavies91/Python-Script-for-Aws
/How to change the Instance type.py
3,456
4.09375
4
# Change the size of an EC2 instance. # The program displays a list of existing instances and the current size of the instance. # The user is able to run the program with a specific instance ID # and the new size of the instance. import boto3 class instanceclass: def __init__ (self,instancename, instanceid...
a8ed29210c75f39ba5c97cdea465ac4a803ff7b8
hyobim/NoshibalKeepGoing
/프로그래머스_3진법 뒤집기.py
301
3.59375
4
def solution(n): answer = 0 num=[] while True: if n<3: num.append(n) break num.append(n%3) n=int(n/3) # n=n//3 l=len(num)-1 for i in num: answer+=i*3**(l) l-=1 return answer
6aabb04631d57cbd43d9f0e49f78095efac86edd
RanchDress/EatWhere
/eatwhere.py
2,387
3.6875
4
import json import datetime import random from enum import Enum class Weekday(Enum): SUNDAY = 0 MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 restaurants = {} preferences = {} people_going = input("Who's going? (separated by spaces)\n").split(" ") restaurants_...
6d2f36f3fbcd9a6ba6e6144c41c3ebb40fd98ecf
jjmpal/risteys
/archives/risteys_sketch_search/data/parse_icd10.py
608
3.578125
4
""" Parses the icd10cm_order_2019.txt to a JSON representation. """ import json from sys import argv def main(filepath): res = [] with open(filepath) as f: lines = f.readlines() for line in lines: # We use the fact that the file is column aligned to get the columns we want. # This...
e1f4e64923d61f1449839cb58cb91ac69adc6576
kindaem/Practice
/16.py
318
3.75
4
import datetime from math import pi def printTimeStamp(name): print('Автор програми: ' + name) print('Час компіляції: ' + str(datetime.datetime.now())) r = int(input("Радіус: ")) print("Об'єм:", (4/3)*pi*r**3, "Площа: ", 4*pi*r**2) printTimeStamp("Денис")
57f8db451ec153193f71f94bc34f7a3a36274b76
priscaogu/Wejapa-Wave3
/CFU.py
1,256
4.59375
5
#Question: What type of loop should we use? #You need to write a loop that takes the numbers in a given list named num_list: #num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166] #Your code should add up the odd numbers in the list, but only up...
8c2ba919ff3cca8bb1a9d2cdfc0fa21cde231d25
Sri2614/python-practice
/object-oriented-programming/walrus.py
381
4.25
4
# walrus operator := # assignment expression # assigns values to variables as part of a larger expression foods = list() while food := input("What food do you like?: ") != "quit": foods.append(food) # while True: # food = input("What food do you like?: ") # if food == "quit": # ...
dcffd7a2f38ebc31fc88e300b36816567e273b88
jasmgang/pythonProject
/hyggehejsa.py
129
3.640625
4
def svar(d): if "hej" in d: return "hej\n" else: return "hej\n" x = input("hejsa \n") print(svar(x))
304c9f605700c20a55e5e06217aac19c2140f749
Achelics/Python_Test
/algorithms/string.py
5,669
3.75
4
#!/usr/bin/env/ python # coding=utf-8 __author__ = 'Achelics' __Date__ = '2016/10/08' def string_matching_naive(text='', pattern=''): """Returns positions where pattern is found in text We slide the string to match 'pattern' over the text O((n-m)m) Example: text = 'ababbababa', pattern = 'aba' ...
dc6173da05ed99a7b8c12161ff266bc17a370ef0
renan09/Assignments
/Python/PythonAssignments/Assign6/substraction.py
180
3.5625
4
import math class substraction() : def __init__(self): print("Init Method") def findSubstraction(self,a,b): value=a-b print("substract ",value)
a40fec32a7be3d1741ce756e67d81c0b85086bc3
fahadaliawan-nbs/cdkProject
/venv/SearchPractice.py
1,794
4.09375
4
# Used as linear search i.e. one by one comparison search """list = [5, 8, 4, 6, 9, 2] n = 11 pos = 0 def search(list, n): for x in list: if x == n: i = list.index(x) + 1 globals()['pos'] = i return True return False if search(list, n): print("found "+str(n)+" i...
4a19533f03e9571f7deeee4125e122d32e2922f3
santidev10/ec2-user
/check_user.py
1,346
3.640625
4
#!/usr/bin/env python3 import sys, os, subprocess, pwd, grp, getpass, time, shutil, re from time import strftime def die(msg): print(msg) os._exit(1) def checkuser(name): try: return pwd.getpwnam(name) except KeyError: return None def getfirst(): fn = "" try: while len(fn)...
f4e3cd652e346f457f77a9ed884cbcdc55f5f0b5
Somi-Singh/python_loop_Questions
/table2.py
88
3.8125
4
num=int(input("enter any num")) i=0 while i<=10: i+=1 print(num,"*",i,"=",num*i)
ab54f9228fa9a6d7471534c3a9550fb674cdf22c
MrViniciusfb/Python-Crash-Course
/Parte 5/Exemplo/voting.py
385
4.15625
4
#19/07/2021 age = 17 #Após ver sobre condicional é natural usarmos isso para avançar para o if-else #Estes usam do teste condicional para fazer ou não uma ação if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry,you are too young to vote.") ...
dfa8f10c0edee13ed291c91138cfe2a8860b0b88
kohyt/cpy5p3
/q3_find_gcd.py
749
4.0625
4
# q3_find_gcd.py # find greatest common divisor import numbers def check(): if a > 0 and b > 0 and isinstance(a, numbers.Integral) and isinstance(b, numbers.Integral): return True else: return False def gcd(a,b): if a >= b: while b != 0: d = a % b a = b ...
da5fb60460245ae40c5fbe479ccd4117d71070d8
Shakhy101/Hangman
/main.py
1,053
3.90625
4
import random, os from hangman_art import stages, logo from hangman_words import word_list from sys import platform clear = lambda: os.system("clear") chosen_word = random.choice(word_list) word_length = len(chosen_word) lives = 6 game_ended = False clear() print(logo) display = [] for _ in range(word_length): d...
9bf7d20ff73a36028dd3153990f433db5ae331f1
adityaparab04/Python-Exercises
/ex15.py
272
3.625
4
#Reading files from sys import argv #import argv script, filename = argv #argument txt = open(filename) print(f"Here's your file{filename}") print(txt.read()) print("Type the filename again:") file_again = input("> ") txt_again = open(file_again) print(txt_again.read())
29ddaf5acb49a51a89c95db28e5dbf6b121bb89f
wooseokoh/python
/python19/class/member.py
1,135
3.96875
4
class Member: id = '' pw = '' grade = '' mileage = '' # 생성자 def __init__(self,id,pw,grade,mile): self.id = id self.pw = pw self.grade = grade self.mile = mile list_total =[] for index in range(0,3,1): list = [] id = input("아이디...
4f5dea1aa4a4b7b0cea9344099d3551fc17eaa26
Hawful/machinelearningpractice
/getResponse.py
712
3.546875
4
#This response system allows neighbors to "vote" for their class attribute, and use the # majority as a prediction. #This function assumes that the class that is voted on is the last attribute of each # queried neighbor. #Still totally based off machinelearningmastery.com import operator def getResponse(neighbors): ...
9a1ac7f12609bab848f930dc22ae56d61f8b0cb9
davidgmor/kata1
/Kata2/1#if1.py
373
3.671875
4
''' Almacenar contraseña en una variable y comprobar si es igual a la que tenemos almacenada en memoria, sin tener en cuanta mayúsculas y minúsculas ''' password = 'contraseña' user_password = input('Introduzca la contraseña: ') user_password = user_password.lower() if password == user_password: print('Password co...
c57cfc014e47d598203f2d97b003e27b5fc40670
Angold-4/algorithms_in_python
/Chapters/Chapter_1/Answer/1.27.py
713
3.859375
4
# Angold4 20200509 C1.1.27 def factors(n): k = 1 while k * k < n: if n % k == 0: yield k yield n // k k += 1 if k * k == 0: yield k def fibonacci(): a = 0 b = 1 while a < 100: yield a future = a + b a = b b = futur...
03fcb6531972ab3c91410ae049c2b08c927248bd
FilipFelipe/BUri
/Python/1065.py
129
3.75
4
count = 0 for op in range(5): a = int(input()) if a%2 == 0: count=count+1 print("%d valores pares" % count )
0ee4f082d0e4ee167c8851c7a9d287440b30ed87
NCAR/pyngl
/examples/viewport1.py
6,137
3.578125
4
# # File: # viewport1.py # # Synopsis: # Illustrates the difference between the viewport and bounding box. # # Categories: # viewport # polylines # polymarkers # text # # Author: # Mary Haley # # Date of initial publication: # August 2010 # # Description: # This example shows how to r...
a0628af8b95f7e3669da9ca2b1e70c77970c78a5
Deepti3006/pythonProgrammingExamples
/lists/swapFirstAndLastElement.py
238
3.890625
4
def swapFirstAndLast(): a=[1,3,5,8,22,44,60] f_elem = a[0] print(f_elem) l_elem= a[-1] print(l_elem) temp = a[0] a[0] =a[-1] print(f_elem) a[-1] =temp print(l_elem) print(a) swapFirstAndLast()
53bf67c2828e5a48854a684c624d43f85aa8d30a
JorgeTranin/Python_Curso_Em_Video
/Exercicios Curso Em Video Mundo 3/Exe_088.py
723
4.3125
4
''' Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' from time import sleep from random import sample numeros_megasena = list(ra...
d7debea1c4ced924d0f1f610c5e0ce4b21522282
TheSheepKing/Deep-Learning-Gomoku
/reinforcement.py
1,971
3.71875
4
#!/usr/bin/env python3 """ play a game against oneself until the end save labels (state, policy, winning) to file label_{num_game}.label """ import numpy as np from mc_tree_search import turn, expand from node import Node def save_tmp_label(board, p, player): """ append board, policy vector and current play...
77972802bb286c250023c4fb3c9ea10b9fe3c512
manufebie/program-design-method
/python_files_excersises/2_avg_word_len.py
790
4.46875
4
''' Write a program that will calculate the average word length of a text stored in a file (i.e the sum of all the lengths of the word tokens in the text, divided by the number of word tokens). ''' import os file_path = os.chdir('/home/manu/Desktop/computer_science/semester1/exercises/program_design_methods/files/te...
0a64ab3dff9adcd81dc28d3b8871e71f87abf168
mateus-n00b/graphs_ufba
/graphs2.0/find_circle.py
707
3.71875
4
# This function allows to find the edges inside the cycle # # Mateus-n00b (UFBA), August 2017 # # # License GPLv3 # //////////////////////////////////////////////////////////////////////////////////////////////////// import networkx as nx def find_cycle_mst(H,u,v,mst): G = nx.Graph() for node in range(0,len(H)...
6be8e55955d17c4e910db30a94cb161e1ec1f311
Amangiri99/Dynamic-Web-Scraping
/web_scrapping.py
4,550
3.71875
4
#importing necessary packages #Selenium - Powerful tool for automation which helps to communicate between the browser and driver #BeautifulSoup - Is a Python library for pulling data out of HTML and XML files from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from selenium....
ec8106c2c8a32e8ce8e7fee83792e942937782d6
rmaiquez/code-wars
/python/8kyu/square(n)-sum.py
263
4.21875
4
# Complete the square sum method so that it squares each number passed into it and then sums the results together. # # For example: squareSum([1, 2, 2]) should return 9 because 1^2 + 2^2 + 2^2 = 9. def square_sum(numbers): return sum(x ** 2 for x in numbers)
b3d7d1759c85de5812c9719451fdbaaaedd53ef1
SimonTheFirst/python_magistracy
/lab3.py
427
4.1875
4
def encode_str(string): vowel_encode_dict = { "a": "0", "e": "1", "i": "2", "o": "2", "u": "3" } for key in vowel_encode_dict.keys(): string = string.replace(key, vowel_encode_dict[key]) return str(string[::-1] + "aca") if __name__ == "__mai...
27e367eb218f3e5e9831f6ab78bf8edda2d6bc9b
galemos/ZNC
/Tutoriais de Python/Curso Alura Python/1_introducao.py
206
3.71875
4
# coding: UTF-8 nome = 'Gabriel' idade = 25 print 'Meu nome é ' + nome + 'e tenho ' + str(idade) + ' anos' x = 5 y = '9' print x+int(y) print 'Meu nome é %s e tenho %s' %(nome, idade) nome = 'nome'
e9a71642c06d9c0e84de9d8c6d3bf9c994f2b3e7
RomanKalsin/python-project-lvl1
/brain_games/scripts/brain_even.py
855
3.90625
4
#!/usr/bin/env/ python3 from brain_games.welcome import welcome from random import randint import prompt def main(): name = welcome() brain_even(name) def brain_even(name): print('Answer "yes" if the number is even, otherwise answer "no".') i = 0 while i < 3: num = ran...
97b16a9798970f1f2d734ed16a60187ae7f3f7e1
sudhanthiran/Python_Practice
/Competitive Coding/RegEx matching.py
1,621
4.5625
5
""" Given a pattern string and a test string, Your task is to implement RegEx substring matching. If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with the starting position of the text string. Similarly, if it is preceded by a $, the pattern(excluding the ^) will be matched with the endi...
466e86f8b79744b9f0e8686f3d95fd041137c4d8
brittany-fisher21/python_rpg
/python_rpg/rpg-2.py
2,425
4.15625
4
""" In this simple RPG game, the hero fights the goblin. He has the options to: 1. fight goblin 2. do nothing - in which case the goblin will attack him anyway 3. flee """ class Character: def __init__(self, health, power, name): self.health = health self.power = power self.name =...
c5bc73f16e38e06c97b1d62223d2defde0ee5f31
eanopolsky/advent-of-code-2019
/14/nanofactory2.py
2,769
3.609375
4
#!/usr/bin/python3 from math import ceil reactions = [] with open("input.txt") as f: for line in f: reaction = {"Rs": [], "P": {}} reagents, product = line.split("=>") reagents = reagents.strip().split(", ") product = product.strip() #print("'{}'".format(reagents)) ...
526819350a7ed114601af2d0be14f7e99594b8cf
ibek01/tasks_all_weeks
/Desktop/bootcamp/week2/practice/task4.py
1,325
3.921875
4
# 4. Изменение списка гостей: вы только что узнали, что один из гостей прийти не сможет, # поэтому вам придется разослать новые приглашения. Отсутствующего гостя нужно заме- # нить кем-то другим. # • Начните с программы из упражнения 3. Добавьте в конец программы команду print # для вывода имени гостя, который прийти н...
d6c58c46b3b0010d22bb613fd2788bd996c9fe53
DanielHa01/Calculator
/calculator.py
4,399
3.875
4
""" Simple Calculator By Daniel Ha Contact: bb13112001@gmail.com """ from tkinter import * from math import sqrt master = Tk() master.title("Calculator") e = Entry(master, width = 40, borderwidth = 3) e.grid(row = 0, column = 0, columnspan = 4, padx = 5, pady = 5) def show_value(num): current =...
607b2a4070cbe37a7889bb5ef1947e7f4ffbb64a
KaySchus/Project-Euler
/Problem 1 - 50/Problem1.py
220
3.609375
4
def sum_multiple(target, value): result = 0 for i in range(1, target): if (i % value == 0): result += i return result final = sum_multiple(1000, 3) + sum_multiple(1000, 5) - sum_multiple(1000, 15) print(final)
a3626d98ae60cb29b3b8d8ee6240f56ccd85b7a5
laboyd001/python-crash-course-ch8
/user_albums.py
660
4.1875
4
#write a while loop that allows users to enter an album's artist and title. Print the dictionary and be sure to include a quit. def make_album(artist, album_name): """Return an artist and album name, neatly formatted.""" album = {'artist':artist, 'album_name':album_name} return album while True: ...
5065570ef0bf937fd0f419495d1b594962490c76
cardy31/CTCI
/Random/fib.py
223
3.703125
4
def main(): for i in range(0, 100): print(fib(i)) # 0, 1, 1, 2, 3, 5, 8, 13... def fib(n): if n == 0 or n == 1: return n return fib(n - 1) + fib(n - 2) if __name__ == '__main__': main()
47624bd594724a2245f35e23706b82ef827a86ec
OwlFlash/proste_cw_na_poczatek
/Duration of planet.py
481
3.671875
4
import math odległość_Ziemii = 150 *pow(10,9) okres_Ziemii = pow(1314000,2) #w kwadracie print ("Podaj nazwę planety") planeta = input() print("Podaj odległość (W METRACH) planety od Słońca"),format(planeta) odległość =int( input()) d = float (odległość/odległość_Ziemii) okres =( math.sqrt( (pow(d, 3))*okres_Zi...
eb34f1203b7d10c87bb46277b69a5cb1eb1254cb
jry-king/leetcode
/3.longest-substring-without-repeating-characters.py
1,442
3.796875
4
# brute force, examine longest substring starting from each character and compare their lengths # O[n**3] time complexity and O[max(m,n)] space complexity # m, n is the size of the string and the alphabet # 576 ms, faster than 15.2% # 13.1 MB, less than 5.51% '''class Solution: def lengthOfLongestSubstring(self, ...
fc3c79f66963352b0a9a519598b496e1b0743d78
xiaoxue11/python_learning
/basic/function.py
1,293
3.5625
4
import math def aa(): return 'something' def fahrenheit_convet(C): fahrenheit=C*9/5+32 print (fahrenheit) def weight_convert(g): weight=g/1000 return weight; def triangle_side(a,b): third_side=math.sqrt(a*a+b*b) return 'The right triangle third side\'s length is '+str(third_side)...
76cd1e4c0265ae639349fb6265f4cf0b4d74abdd
CHREC/PythonTutorials
/variableTypes.py
2,545
4.53125
5
# Values to variables inte = 100 # integer variable type fl = 100.0 # floating variable type st = 'john' # string variable type # Multiple Assignment a = b = c = 1 # all three variables (a,b,c) have a value of 1 a, b, c = 1, 2, 'john' # value of integer 1 to a, integer 2 to b, and string 'john' to c # 5 data typ...
ccf6147c627f75baa0c5374e723a6df0589b7271
minas528/a2sv
/Introdution to Competitive Programming/D19/Binary Search.py
547
3.671875
4
class Solution: def search(self, nums: List[int], target: int) -> int: if not nums : return -1 def recSearch(nums,target,left,right): if left>right : return -1 mid = (left+right)//2 if target == nums[mid] : return mid ...
99cc7450b8527d654bca3bccdecc78c921e8ec92
vincent507cpu/Comprehensive-Algorithm-Solution
/LeetCode/easy - Hash Table/350. Intersection of Two Arrays II/.ipynb_checkpoints/solution-checkpoint.py
1,549
3.71875
4
# base model, ugly class Solution: def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]: if not nums1 or not nums2: return [] lst = [] for i in range(len(nums1)): if nums2 and nums1[i] in nums2: lst.append(nums1[i]) ...
10ee8d8a7153d881b2e36ffcd3a9f9a2ca4c768e
Pumacens/Competitive-Programming-Solutions
/CodeWars-excercises/Python/7_kyu/files/77. Get the Middle Character.py
190
3.53125
4
def get_middle(s): len_s = len(s) if len_s <= 2: return s return s[len_s//2 - (len_s%2==0) : len_s//2 + 1] # def get_middle(s): # return s[(len(s)-1)/2:len(s)/2+1]
057700b7c97b2191dbaf251ffe7c38dac37a651d
UCSD-CSE100-SS1-2020/set_and_map_using_linked_list
/set_solution.py
1,267
3.828125
4
class ListNode: next = None val = None def __init__(self, v): self.val = v class Set: head = None size = 0 def __init__(self, h=None): if h: self.head = ListNode(h) self.size += 1 def add(self, e): if not self.contains(e): temp ...
5b38d8a2ad85211ff3c79ed6e8635e8987020915
jonghoonok/Algorithm_Study
/1240.py
1,242
3.5
4
def password_check(numbers): # 먼저 암호문에 해당되지 않는 행 제거 i = 0 while True: if not '1' in numbers[i]: numbers.pop(i) else: i += 1 if len(numbers) == i: break # 열 제거 for j in range(m-1, 56, -1): if numbers[0][j] == '0': contin...
9092b0983f9f8304be95ea4faed7fe17d1f4343d
adityachache/data-structures
/graph.py
937
4.03125
4
class Graph(): def __init__(self): self.numberofnodes = 0 self.adjacentlist = {} def addvertex(self,node): """add a vertex in the graph""" self.adjacentlist[node] = [] self.numberofnodes += 1 def addedge(self,node1,node2): ...
b145cc89ace12483c90b33f24834b3d413e92289
mattbingham/Python
/turtle_miniproject.py
2,455
3.8125
4
import turtle window = turtle.Screen() window.bgcolor("#87cefa") window.setup (width=800, height=600, startx=0, starty=0) class Shapes(): # Make the ground def ground(): soil = turtle.Turtle() soil.up() soil.setpos(-100, -200) soil.down() soil.color("brown") soi...
7af2ead36b52e7e7fc6b57c271aa2f9d40c7bf75
inauski/SistGestEmp
/Tareas/Act02. If....else/ejer04/ejer04.py
613
4.0625
4
print("Comparador de multiplos") num1 = int(input("Escriba un numero: ")) num2 = int(input("Escriba otro numero: ")) if ((num1 > num2) and ((num1 % num2)==0) ): print (str(num1) + " es multiplo de " + str(num2)) elif ((num2>num1) and ((num2 % num1)==0)): print(str(num2) + " es multiplo de " + str(num1)) elif ((...
eb4b3363e7c4c9c6932fdc77bc2e6a676fbd23fb
SpykeX3/NSUPython2021
/problems-3/a-ushaev/problem3.py
2,210
3.515625
4
#!/usr/bin/env python3 class Vector(): def __init__(self, *args): if len(args) > 0: if isinstance(args[0], (tuple, list)): self._components = list(args[0]) else: self._components = list(args) else: self._components = [0,0] def...
77e15071634e4e79cc73df64f6035be62c09e54c
UX404/Leetcode-Exercises
/#976 Largest Perimeter Triangle.py
685
3.859375
4
''' Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths. If it is impossible to form any triangle of non-zero area, return 0. Example 1: Input: [2,1,2] Output: 5 Example 2: Input: [1,2,1] Output: 0 Example 3: Input: ...
e78dfb5863286090be0641073479c1362759f3a8
monkeydunkey/interviewCakeProblems
/sumNumbers.py
400
3.71875
4
def sumNumbers(st): num = '' runSum = 0 for d in st: if d.isdigit(): num += d else: if len(num) > 0: runSum += int(num) num = '' if len(num) > 0: runSum += int(num) return runSum if __name__ == '__main__': print sumNum...
f4058434293c27f9b4ed4d93515948176118adfc
Ricksou/Python_L3
/Episode 4.py
2,876
3.8125
4
chaine = "Python" for lettre in chaine: print(lettre) print() chaine = str(input("Ecrire un mot afin de compter les occurence de chaque lettre dans ce mot ")) i=0 cnt=0 while i <= len(chaine)-1 : compteur = chaine.count(chaine[i]) i+=1 index=i i-=1 while i>=0: ...
db08ec9595799f93780870eca2fdf579f642e87a
Balu862/everyday_assignments
/day6assignment-26july/26thjuly2021_Balasubramaniyam_assignment/day6practiced/inheritance1.py
388
3.71875
4
class Person(object): def __init__(self, name): self.name = name def getName(self): return self.name class Employee(Person): def __init__(self, name,id): self.id=id super().__init__(name) def getName(self): return self.name,self.id emp = Person("Balu")...