blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
c5d37e12a12dac2df8bf04bd536a9c84418b5ce9
seddon-software/python3
/Python3/src/13 Scientific Python/Pandas/12_covid.py
1,124
4.125
4
import pandas as pd pd.set_option('display.precision', 1) pd.set_option('display.width', None) # None means all data displayed pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) ''' Pandas 2D dataset are called dataframe. This example shows ...
d2b0186cdd02cc43b02744d499ea724e2252ca2a
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/lngyas001/question4.py
574
3.765625
4
import math function = input('Enter a function f(x):\n') for y in range(10,-11,-1): for x in range(-10,11): new_function = round(eval(function)) if new_function == y: print('o', end = '') elif new_function != y and y != 0 and x !=0: print (' ',end= '') ...
cc2b67a4e83bdd889030bc4c9223cefa699e506c
duk1edev/projects
/PythonExamples/Python_Lesson2/PythonApplication1/elis_switch.py
295
4.09375
4
print("""Menu: 1.File 2.View 3.Exit """) choise = input("Enter your choise: ") if choise == "1": print("File menu open!") elif choise == "2": print("Choise view parameters") elif choise == "3": print("Exit!Press enter") else : print("You choose is wrong!Exiting program...")
c37fb45c3052c3403099a70dabaa738f7b67b1b7
mvitnyucoders/64squares
/algos/dec1/twoSum.py
605
3.640625
4
from typing import List class Solution: def twoSum(self, nums: List[int], target: int): h = {} # iterating a list for i, val in enumerate(nums): if target - val in h: # check if target value - current value exists in dictionary return [h[target -...
2d6502ccd78151922404c308cbd1dd6dbd39d54c
jadhavsmita/Letsupgrade-pyhton-assignment
/Day 8 Assignment.py
693
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # Day 8 Assignment 1 # In[43]: fibonacci_cache={} def fibonacci(n): if n in fibonacci_cache: return fibonacci_cache[n] if n==1: value=1 elif n==2: value=1 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) fibonacci_ca...
04b8570841d921b6133ceee1e0fe36bfc2d6bbb8
GeorgeJopson/OCR-A-Level-Coding-Challenges
/53-Mortage Calculator (Extensions Available)/Mortgage Calculator.py
533
4.125
4
#Mortgage amount mortgage=int(input("Input the mortgage amount: ")) #Number of years years=int(input("Input how long you have to pay off the £{0:d} mortgage: ".format(mortgage))) #Interest interest=float(input("What is the interest: ")) months=years*12 interestMultiplier=interest/100 interestMultiplierPerMonth=interes...
f936cd4f957065b886e86865e66ee4c84f4ff5a5
sunilsm7/python_exercises
/python_3 by pythonguru/defaultarg.py
120
3.53125
4
def func(i,j=100): print("Addition",i+j) v1 = int(input("Enter value1:")) v2 = int(input("Enter value2:")) func(v1,v2)
cdea58774f8c025d1a7ae33b403aaf64735647ff
GDN2/DL
/DeepLearning/backpropagation_simulator.py
1,128
3.53125
4
import numpy as np W2 = np.array([1,1,2,1]).reshape(2,2) W3 = np.array([2,1,1,1]).reshape(2,2) T = np.array([2,1]) b2 = np.array([1,1]) b3 = np.array([0,2]) learning_rate = 0.1 A1 = np.array([1,2],ndmin=2) A2 = np.random.rand(1,2) A3 = np.random.rand(1,2) def sigmoid(z): dic = { 0:-3, 1:-2, ...
8dac1029344b3e2fda805996909e196647388d5a
slamatik/Free_Code_Camp
/Scientific Computing with Python Projects/Arithmetic Formatter/arithmetic_arranger.py
1,796
3.953125
4
def arithmetic_arranger(problems, display_answer=False): if len(problems) > 5: return "Error: Too many problems." temp_first_line = [] temp_second_line = [] temp_dashed_line = [] temp_answer_line = [] for question in problems: left = question.split()[0] operator = quest...
e342e28881b5e78c5d1c3319f2d51ceb742de145
java131312/python_execise
/2017-04-21/for1list.py
116
3.75
4
#!/bin/env python #! -*- coding:utf-8 -*- #这里可以写中文。 print [x * x for x in range(1,11) if x %2 == 0]
aed54136b8ce03669e30835d8c287f094a8b9b7f
zupph/CP3-Supachai-Khaokaew
/Exercise5_2_Supachai_K.py
353
3.59375
4
s = int(input("กรุณาใส่ค่าระยะทางการเคลื่อนที่ (km) : ")) t = int(input("กรุณาใส่ค่าเวลาในการเคลื่อนที่ (h) : ")) v = s/t print("อัตราเร็วของการเคลื่อนที่คือ : ", v, " km/h")
02a9d436b130ab9d005a2f3edd4178b7292657ba
infinityman8/logbook-week-13-15
/week 13 q1.py
787
3.734375
4
class Animal(): def __init__(self,types,name): self.types=types self.name=name def getAnimalString(self): return "animal name: %s, type: %s" %(self.name, self.types) class Mammal(Animal): def __init__(self, species, name): super().__init__("mammal", name) ...
20d52f6d911ff4e89bd65b0e1fb8d91b1592610e
rakesh08061994/github_practice
/Project (2).py
570
4.34375
4
# BMI Calculator height = float(input("Enter your Height in centemeter : ")) weight = float(input("Enter your weight : ")) new_height = height/100 BMI = weight/(new_height * new_height) print("Your body mass index is : ",BMI) if BMI > 0: if BMI <= 16: print("You are severly underweight") elif BMI <= ...
3c82ebf0ae4e52945ee6956800414238bb48e67f
michalczaplinski/scrabblez
/scrabble_letter_counter.py
2,423
3.71875
4
#!/usr/bin/env python '''Scrabble tile counter. Returns neat statistics about the tiles that are still left in the game. The respective commands allow you to keep track of the tiles played so far, as well as remove tiles that have been entered in error. The count command runs the statistics Usage: scrabble_letter_c...
52460b7b7543f9a18b168d00e561c0b382493a29
AlexandrShestak/mag_python
/lab6/iterators.py
250
3.578125
4
import itertools def unique(iterable): visited = set() for elem in iterable: if elem not in visited: yield elem visited.add(elem) def transpose(iterable): return list(itertools.izip_longest(*iterable))
f25e7a4560fcde9427f723cd182c6c699edae30b
daniel-reich/ubiquitous-fiesta
/wwN7EwvqXKCSxzyCE_7.py
460
3.78125
4
def reorder_digits(lst, direction): new_lst = [] if direction == 'asc': for i in lst: i = list(str(i)) i.sort() i = int("".join(i)) new_lst.append(i) return new_lst elif direction == 'desc': for i in lst: i = list(str(i)) ...
af407fcf80b0abe57cdc63e4c5e5922f4fa1f7e5
zsmountain/lintcode
/python/stack_queue_hash_heap/541_zigzag_iterator_ii.py
1,348
3.9375
4
''' Follow up Zigzag Iterator: What if you are given k 1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". Have you met this question in a real interview? Exam...
5c19969f4190acbfd063cc2f2066cc3dbe743776
QuentinDuval/PythonExperiments
/arrays/FindMissingAndRepeating.py
3,068
3.640625
4
""" https://practice.geeksforgeeks.org/problems/find-missing-and-repeating/0 Given an unsorted array of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in array. Find these two numbers. Note: - If you find multiple answers then print the Smallest number found...
b3bfd740ab8fe3ac47e76e6bc0272fc40b5dcdea
xuxiazhuang/LeetCode
/python_leetcode/_561.py
871
3.796875
4
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3...
b32e81caf0e9d8a9b5a0f0a4cffcaf64a23a52ac
sweetyn/Leetcode
/traversal_bin.py
917
4.125
4
"""graph traversal, binary search tree, OOP 1 2 3 4 5 Depth First Traversals: (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1""" class Node(object): def __init__(self, val): self.left = None self.right =...
ee112893b97db689308ddf37ba78a4554af14fe8
aramosescobar/Aliciamonday9
/Monday 9/monday.py
251
3.765625
4
for i in range(0,5): print("first identification") for j in range(0,3): print("Second indentation") for k in range(0,10): print("third identidication") print("forth identification") print("fifth identification")
d67a09531ca47b192f39a88f96bf77aa085c1fbd
Sarthak-Singhania/Work
/Class 11/untitled1.py
129
3.859375
4
def countSquares(n): return (((n+1) * (n + 2) / 2) * (2 * (n+1) + 1) / 3) n = 8 print("Count of squares is ",countSquares(n))
b943fef0e483cb0b71bfcb07f3dd43fcaf27328f
brenj/solutions
/hacker-rank/python/numpy/arrays.py
248
4.15625
4
# Arrays Challenge """ You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float. """ import numpy numbers = raw_input().split() numbers.reverse() print numpy.array(numbers, float)
14247a965997a52a6ea723febe81848a92eb0229
jingong171/jingong-homework
/尤焕雄/第一次作业/第一次作业 金工1 尤焕雄 2017310411/zhishu.py
138
3.546875
4
num=[]; for m in range(2,100): for n in range(2,m): if (m%n==0): break else: num.append(m) print(num)
7ae6149d6dca398f55c1f886636499bb9e0752d2
LINLUZHANGZZ1/----
/三家餐馆_cases.py
607
3.765625
4
class Restaurant(): """这里是表示一家餐馆的类""" def __init__(self,restaurant_name,cuisine_type): """初始化属性name和type""" self.restaurant_name=restaurant_name self.cuisine_type=cuisine_type def describe_restaurant(self): print("这家餐厅的名字是"+self.restaurant_name.title()+" 类型是"+self.cuisine_type.title()) def open_restaurant...
f69feb6df2b451b6d6c17c7f44736be2b9f02fd3
EmersonBraun/python-excercices
/cursoemvideo/ex065.py
927
4.03125
4
# Crie um programa que leia vários números inteiros pelo teclado. # No final da execução, mostre a média entre todos os valores # e qual foi o maior e o menor valores lidos. # O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores cont = 0 total = 0 continua = 'S' while True: entrada...
eebf73dd9eff454febb5bc90e7a5aab1111b5e06
emehrawn/mehran.github.io
/Python/Tkinter/tkinterMessagebox.py
544
4.0625
4
''' This program is a simple example of Message Box in Tkinter where you can use various types, in this program we only came across (askquestion & showinfo) ''' from tkinter import * import tkinter.messagebox root=Tk() answer=tkinter.messagebox.askquestion("Question","Do you get offended if i use swear words?"...
85cfec59c000a0eebddda678bd4044e6b274b266
Enfernuz/project-euler
/problem-2/O(logN)_0.py
774
4.0625
4
#python 3 def getSumOfEvenFibonacciTerms (limit): prevTerm = 1 nextTerm = 2 sum = 2 # Starting from the term 2, each next 3rd Fibonacci term is even (indexing from 1). # The logic is simple: # 1 (odd) + 2 (even) = 3 (odd) --> the start of the sequence: odd + even = odd, order = 1 # 2 (even) + 3 (o...
334b59e794cccd1ab78c1c80d82cadb4dd998698
digitalladder/leetcode
/problem70.py
1,140
3.546875
4
#problem 70 /Climbing Stairs #DP with memory class Solution: def climbStairs(self, n): memo = [0]*(n+1) x = self.ways(0,n,memo) return x def ways(self,i,n,memo): if i>n: return 0 if i == n: return 1 if memo[i]>0: return memo[i] ...
54834efd7e3fa0a71075a1c11534bab7b5654229
Artinto/Python_and_AI_Study
/Week02/Main_HW/Nested Lists/Nested Lists_LGY.py
1,916
3.890625
4
#key, value 나눠 sort. dict에서 찾아서 프린트 if __name__ == '__main__': student = {} ans = [] for _ in range(int(input())): name = input() score = float(input()) # input값을 받아서 student[name] = score # dictionary로 저장 names = student.keys() # key, value로 각각 리스트 생성 scores...
88289486c2e412bec81d25e880bdedc6d1d938f4
MoazMansour/data-structures
/Binary_search_tree.py
1,536
4.09375
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): current = self.root notPlaced = True while notPlaced: ...
81dcbe272b97d8a349e6be11646c615d523c513c
itscrisu/pythonPractice
/Guías/diccionarios2.py
1,036
3.546875
4
# Vamos a crear otro diccionario y utilizarlo para practicar otras cosas: gatitos = { "Frodo": { "nombre": "Frodo", "edad": 3, "ronronea": "Si, muy bajito", "hermoso": "Si" }, "Sami": { "nombre": "Sami", "edad": 2, "ronronea": "Muchisimo", "he...
3d33017c6480d0526d4a63054cd69fbe48da036b
leeanna96/Python
/Chap03/직선 방정식 구하기.py
323
3.6875
4
x1=int(input("첫 번째 점의 x좌표: ")) y1=int(input("첫 번째 점의 y좌표: ")) x2=int(input("두 번째 점의 x좌표: ")) y2=int(input("두 번째 점의 y좌표: ")) if x2-x1!=0: m=(y2-y1)/(x2-x1) q=y1-m*x1 print("직선의 방정식은",m,"x+",q) else: print("직선의 방정식은 x=", x1)
43bc39623cf54d05d607c70c1539bfd78650abbd
gauravsarvaiya/python-codes
/lambda.py
857
4.15625
4
# changes # lambda expression # other name is anonymous function # lambda exprestion means name without funtion # lambda use map,filter etc # add=lambda a,b: a+b # print(add(10,20)) # multply=lambda a,b: a*b lambda use in programe # print(multply(10,10)) # g1 = lambda a: a**2 # print(g1(10)) # def func(a): #...
bce3b5395752a971ba2797fc3fbdd7cecdb54dec
cb2411/2019-camerino-ODD
/potions/tools/cooking.py
1,524
3.671875
4
"""This file contains all defined cooking methods for brewing potions. All cooking methods are functions, so there are docstrings available. In case you are wondering, this is the text in the module docstring of /tools/cooking.py . """ dummy = 1 def stir(potion, direction): """Stirs the potion. Updates c...
5a298518591eea60a0bc001de1495a5c60bf272a
abhinandan991/Projects-and-Assignments
/CS50/pset6/hello/hello.py
89
3.78125
4
#Takes input for name a=input("What is your name?\n") #prints required print("hello,", a)
f19603ec3564cd21914d37124fd478c9be9466e5
ryosuke071111/algorithms
/AtCoder/ABC/card_game_easy.py
256
3.578125
4
from collections import deque A=deque(input()) B=deque(input()) C=deque(input()) turn={"a":A,"b":B,"c":C} next = A.popleft() flag = True while flag: if len(turn[next]) != 0: next = turn[next].popleft() else: print(next.upper()) break
81b099d183251d5cb3cc4a21e6ab378f001c344a
rShar01/Scrapespeare
/ScrapeShakespeare.py
3,470
3.59375
4
from bs4 import BeautifulSoup from requests import get from warnings import warn from heapq import nlargest import matplotlib.pyplot as plt """ To be honest, I don't have any meaningful analysis of this information. If you do, go right ahead and use this code I just did this as practice """ print("Welcom...
ba41ef426a5439807aad825f9365774652974925
dvoiss/programming-puzzles
/programming-praxis/sum-of-four.py
649
3.734375
4
import itertools as it test = [2, 3, 1, 0, -4, -1] value = 0 # numbers in test can be used more than once: # [0, 0, 0, 0] = 0 or [1, 1, -1, -1] = 0 print [i for i in it.combinations_with_replacement(test, 4) if sum(i) == value] # no numbers in the test array can be used more than once, # ex: full result set of test...
d4d2f5b787b90e78b75e24e9a684b585178758f8
Hermotimos/Learning
/algorithms/8.SORT ALGORITHMS.py
13,676
4.5625
5
""" This file is for learning and exercise purposes. Topics: - algorithms: recursion, monkey sort, bubble sort, selection sort, merge sort Sources: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall...
31dfe1bf9c36c12a9477bec393bcfa3f1af759c3
ojhak02/python2
/disjoint.py
1,198
3.75
4
x={"apple","banana","cherry"} y={"google","microsoft","facebook"} z=x.isdisjoint(y) print(z) x={"a","b","c"} y={"f","e","d","c","b","a"} z=x.issubset(y) print(z) x={"apple","banana","cherry"} y={"google","microsoft","facebook"} x.intersection_update(y) print(x) x={"a","b","c"} z=x.issuperset(y) prin...
6c7d31368081e5e1989a5ea1e608eb946d698591
lucianovictor/python-estudo
/pythonexercicios/ex006.py
142
3.921875
4
n1= int(input('Digite um numero:')) n2= int(input('Digite um numero:')) s = n1 + n2 print('A soma de {} e {} é igual {}!'.format(n1, n2, s))
9ec579927f47973ddde5b3b3dac3fdfc8004626c
Kumarved123/Basic-Data-Structure-Algorithm
/Dynamic Programming/Longest_Bitonic_Subsequence.py
972
3.828125
4
#Longest Bitonic Subsequence '''Given an array arr[0 … n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing or...
3fa46146099c29aad9a17748a199b6bbe204b7f0
hanchang7388/PythonExercises
/test/test_re.py
315
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def match(a): pattern = re.compile(r'(\w+)@(\w+).(\w+)') m=re.match(pattern,a) if re.match(pattern,a): print "yes" else: print "fail" # a=raw_input("enter email: ") a="123@qq.com" print a match(a) # print 'a b cd'.split(' ')
2772971267cc3e1209c5b576e5f2b86933c5c41d
lunar0926/python-for-coding-test
/binary_search/binary_p1-1.py
1,103
3.703125
4
''' 입력 예시 5 8 3 7 9 2 3 5 7 9 ''' # 내가 적은 코드로 문제를 맞추긴 했지만 교재에 있는 예시대로 이진 탐색, 계수 정렬, 집합 자료형을 이용해서 해결해보기. # 이진 탐색 활용(재귀함수) # 함수 정의 def check(array, start, end, target): # target에는 구매하려는 제품 종류를 변수로 넣어야 함. # target을 못 찾았을 때 if start > end: print("no", end=' ') # 중간값 mid = (start + end) // 2 if a...
82ae7f2888896719b1a1d0105534989f29316514
SonoDavid/python-ericsteegmans
/CH2_floating_point/realroots.py
760
4.21875
4
# Calculates the real roots of a quadratic equation # The equation is in the from a*x**2+b*x+c # The solution is x = (-b +- sqrt(discriminant)) # The discriminant is b**2 + 4*a*c from math import sqrt a = float(input("Give the value of a: ")) b = float(input("Give the value of b: ")) c = float(input("Give th...
5b4abcd48177ce4df4b1961c2fd9c09611a70c31
rachit995/practice
/hackerrank/ctci-bubble-sort.py
529
3.84375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countSwaps function below. def countSwaps(a): n = len(a) num_swaps = 0 for _ in range(n): for j in range(n-1): if a[j] > a[j+1]: num_swaps += 1 a[j], a[j+1] = a[j+1]...
4aabc4f894a412f527394bfd5baa4e318f5cfac6
teojcryan/rosalind
/code/fibo.py
178
3.765625
4
# Fibonacci Numbers """ Problem Given: A positive integer n≤25. Return: The value of Fn. """ def fibo(n): if n <= 1: return n else: return fibo(n-1) + fibo(n-2)
8c65de342e9e44951c77b6c2c935d99e024f514e
UncleBob2/MyPythonCookBook
/JSON urlopen read loads dict get.py
692
3.578125
4
import json from urllib.request import urlopen with urlopen('https://api.exchangeratesapi.io/latest') as response: source = response.read() data = json.loads(source) # print(json.dumps(data, indent=2)) usd_rates = dict() # create new dic from JSON for quicker access # for item in data['list']['resources']: # ...
90b69ffcadd562c183b5d0ee09e16c819dbbb8f3
grigor-stoyanov/PythonAdvanced
/workshop/tic_tac_toe/core/validators.py
963
3.625
4
from tic_tac_toe.core.helpers import get_row_col def is_position_in_range(position): if 1 <= position <= 9: return True return False def is_place_available(board, position): row, col = get_row_col(position) if board[row][col] == ' ': return True return False def is_winner(board...
e41b028d8baf32b88767103e217d0c4416a2c92e
panthitesh6410/python-programs
/functional_programming.py
211
3.609375
4
# functional programming tells to do work using function : def add_ten(x): return x + 10 def twice(func, arg): # call any function twice return func(func(arg)) print(twice(add_ten, 10))
28b2fc46d177873fc6b56f4309570a6363725d9a
Juhee-Jeong-SW/ALGORITHM
/PROGRAMMERS/STACK:QUEUE/42583.py
1,206
3.640625
4
from collections import deque # idea : '다리'의 무게와 '다리'에 대한 리스트를 동시에 갱신시키며 값을 구한다. # 트럭이 '다리'에서 빠져나가는 부분(앞)과 트럭에서 빼내어 다리에 붙여주는 부분(뒤)가 구현되어야 함. -> deque 특성 def solution(bridge_length, weight, truck_weights): answer = 0 bridge = deque([0] * bridge_length) # 다리 크기만큼의 deque [0,0] truck_weights = deque(tru...
e45bd7eb869e74f499121aa2d6e5f02efc7da37f
TheJoeCollier/cpsc128
/code/python3/simple_plot_example.py
653
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 17 17:59:45 2019 @author: sbulut """ #example1 import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16],label='data by hand') plt.ylabel('axis label with equation $y=x^2$') plt.xlabel('x') plt.legend() plt.show() #example 2 import numpy as n...
fc928c0fd0f53b4f44163b67fba387b4aab7c80e
Narendon123/python
/140p.py
96
4
4
t=input().split() if(t=='a' and t=='b' or t=='a' or t=='b'): print("yes") else: print("no")
f2477a62cc1ccf2a190c4ef55a28c17f968f5191
Zahidsqldba07/CodeFights-9
/Arcade/Intro/Level 12/digitsProduct/code.py
800
3.78125
4
from math import sqrt def factor(x): return sorted(reduce(list.__iadd__, [[n, x / n] for n in range(1, int(sqrt(x)) + 1) if not (x % n)])) def is_prime(x): return True if len(factor(x)) == 2 else False def digitsProduct(product): # This should be 0 to be consistent with 1, 2, 3, ..., 9. if product ==...
1d018ae5e775b13618c66839101492effae0dddf
Ajinkyasarmalkar/Python-examples
/enter a number.py
212
4
4
while(True): inp = int(input(("enter a number: ")) if inp>100: print("congrats ypu have entered number greater than 100.") break else: print("Try again!") continue
3d5ff5e747548bdd6c8ead7f6f3e195aff197d90
bradyt/project-euler
/python/p005.py
578
3.78125
4
# Smallest multiple # Problem 5 # # 2520 is the smallest number that can be divided by each of the # numbers from 1 to 10 without any remainder. # # What is the smallest positive number that is evenly divisible by # all of the numbers from 1 to 20? import fractions def lcm(a, b): return a * b // fractions.gcd(a, ...
97ee1f0148f653317d2672adf93671d1d6c89fb6
TeddyTeddy/Complete-Python-3-Bootcamp
/19-Managing Python Environments/sys-path-is-fixed/1-package-import-example/start.py
1,477
3.90625
4
""" Let’s recap the order in which Python searches for modules to import: 1) built-in modules from the Python Standard Library (e.g. sys, math) 2) modules or packages in a directory specified by sys.path: a) If the Python interpreter is run interactively, sys.path[0] is the empty string ''. This tells Python to ...
9226ca05867d9985f7db3c69666d34bd1fc155c8
rarezhang/data_structures_and_algorithms_in_python
/exercises/ch07_linked_lists/SinglyLinkedBaseRecursive.py
3,366
3.625
4
""" base class for singly linked list recursive version reference: UC Berkeley CS61A """ class _SinglyLinkedBaseRecursive: """ a base class for singly linked list recursive version """ empty = () def __init__(self, head, rest=empty): """ :param head: :param rest: ...
91e4f4157c7c0cbfaca18fbbf1b528f9adf533f8
FabianTz/Study-Data
/Data Analysis/FunctionsPandas.py
1,060
3.5625
4
import tkinter as tk from tkinter import filedialog import numpy as np import math import pandas as pd def grab_data(): # file open dialog to select the file to work on root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() # by default expect a csv delim = "," # if a ts...
f721da4a62a9d6ee2a783efd17d7bc324a8275c7
charliedmiller/coding_challenges
/minimum_depth_of_binary_tree.py
1,601
4.03125
4
# Charlie Miller # Leetcode - 111. Minimum Depth of Binary Tree # https://leetcode.com/problems/minimum-depth-of-binary-tree/ """ recursivley find the min depth of left and right children. Keep track of min depth seen so we don't have to venture futher than necessary """ # Definition for a binary tree node...
7da1237855a4951f6cf2c5f9f43e1fc108d32d22
plawanrath/Leetcode_Python
/MulyiplyStrings.py
2,733
4.125
4
""" Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Input: num1 = "2", num2 = "3" Output: "6" """ from typing import List from itertools import zip_longest def multiply(num1: str, num2: str) -> str: if num1 == "0" or num2 =...
088be36a6a6c205d444a4b495ca6f4eddc880ade
chan2ie/2018_datastructure_exercises
/exercise_week4/gen_maze.py
809
3.640625
4
from __future__ import print_function from random import shuffle, randrange def make_maze(w = 42, h = 43): print( h*2 +1, w*2 + 1) vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] ver = [["10"] * w + ['1'] for _ in range(h)] + [[]] hor = [['0'] + ["11"] * w for _ in range(1)] hor += [["11"] * w + ['1'] ...
04fb95505b09128ea51da08c6bb6ccf9a6e329ad
RLNetworkSecurity/Python_learning
/time_table.py
330
4.125
4
#while loop example table_number = int(input("Input yoru times table: ")) number_rows = int(input("Input row_number: ")) #display heading print(f"{table_number} times table") print("-"*60) #for loop examples for row in range(number_rows+1): answer = table_number * row print(f"{row:3} * {table_number} = {an...
6c7c60c05f45220175e7f5e4df26532401d32cd1
meda-kiran/DS
/graph/dfsIterative.py
1,721
3.703125
4
from collections import defaultdict import collections class Graph: def __init__(self): self.graph=defaultdict(list) def addEdge(self,src,dest): self.graph[src].append(dest) print self.graph def DFS(self,v): visited=[False]*(len(self.graph)) q=collections.deque() self.prev...
f7cbc93a59297a303cff722230e5a59ec2aa79f9
NewMike89/Python_Stuff
/Ch.1 & 2/flo_math.py
179
3.609375
4
# Michael Schorr # 2/19/19 # Program of basic math operations on floats(decimal) numbers. print(0.1 + 0.1) print(0.2 - 0.2) print(2 * 0.2) print(0.2 / 2) print(0.2 + 0.1) print(3 * 0.1)
c40886ce475522978854c1cfce8baccc4c042c97
sadatusa/PCC
/6_4.py
750
4.53125
5
# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean # up the code from Exercise 6-3 (page 102) by replacing your series of print # statements with a loop that runs through the dictionary’s keys and values. # When you’re sure that your loop works, add five more Python terms to your # glossary. W...
7f807624844f3912c905728155194b2d91f9ee6a
petitviolet/python_challenge
/ex2.py
531
3.515625
4
# -*- encoding:utf-8 -*- from itertools import permutations def count(text): words = {} for t in text: words.setdefault(t, 0) words[t] += 1 return words def main(): lines = file('text_2.txt').read() words = count(lines) ans = [] for k, v in words.items(): if v == 1:...
e4fca1702eb1f12c3bcf96ca21a5b1800e4898a6
joashcabanilla/DICT-python-training
/day3/day3prac2.py
493
4.03125
4
answer = "Y" while answer.upper() == "Y": num1 = int(input("Enter First Number: ")) num2 = int(input("Enter Second Number: ")) if (num1 + num2) % 2 == 0: print("The sum of two integers is Even") else: print("The sum of two integers is Odd") print("____________________________________...
13fdad4ac41f8e5b5b18cd8ee24d996c13d22cef
rpycgo/tf-pdf
/union_find.py
965
3.609375
4
# -*- coding: utf-8 -*- class Union_Find: __slots__ = ['data', 'size'] def __init__(self, n): self.data = [-1 for _ in range(n)] self.size = n def upward(self, change_list, index): value = self.data[index] if value < 0: return index ...
f4682acabc6a3895c4c98ab30e3c3759d00d6518
thefr33radical/codeblue
/concepts/function_tracer.py
293
4.125
4
'''' function to trace the recursion stack : factorial of a number ''' def func(n): print(n) if(n==0 or n==1): return 1 if(n==2): return 2 else: x=(n* func(n-1)) print(x) return x if __name__=="__main__": y=func(5) print(y)
9b8149938e5d0074a0f5d653f057d51a422cdba4
FerniPicart/Lista.py
/Lista.py
62,681
3.578125
4
from tda_lista_lista import nodoLista , Lista, insertar, eliminar, busqueda_lista, busqueda_lista_vec, barrido_sublista, barrido_lista, tamanio, lista_vacia, criterio from random import randint, choice from datetime import date from time import sleep lista = Lista() def lista_numerica(lista): while tama...
8b7c58fcd7ba835068ecb3bcd5fd444d7c99c886
WaveBlocks/WaveBlocksND
/WaveBlocksND/MatrixPotential1S.py
20,063
3.53125
4
r"""The WaveBlocks Project This file contains code for the representation of potentials :math:`V(x)` that contain only a single energy level :math:`\lambda_0`. The number of space dimensions can be arbitrary, :math:`x \in \mathbb{R}^D`. @author: R. Bourquin @copyright: Copyright (C) 2010, 2011, 2012, 2014 R. Bourquin...
6f465f061f274fe3d2a597c4863d9fd82fb17e70
watalo/fullstack
/面对对象/Day2/1-变量.py
1,728
3.859375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #__author__:"watalo" # @Time: 2019/12/22 19:58 # @Site : # @File : 1-变量.py # @Software: PyCharm # class Foo: # def __init__(self): # 构造方法 # self.name = name # self.age = 21 # # obj = Foo('国宴中') # # class Food: # def func(self): # print(s...
d528e253401283555c736a3cc3b574f65cc49aa1
minhlong94/Theoretical-Models-in-Computing
/Lab 4 - Optimization and HyperOpt/Newton's Algorithm.py
750
4.0625
4
import sympy as s x = s.Symbol('x') f = 4*x - 1.8*(x**2) + 1.2*(x**3) - 0.3*(x**4) iter = int(input("Input your number of iteration:\n")) err = float(input("Input your relative error:\n")) x0 = int(input("Input your initial guess:\n")) print("The program now calculates {} using Newton's Algorithm\n".format(f)) x_pri...
a9242b7fd84c3a3338ffe9981a486fcd18040186
fidelis111/fidelis1
/ex28.py
334
3.9375
4
import random computador = random.randint(0, 5) #faz o computador pensar print('Vou pensar em um número de 0 a 5, tente adivinhar: ') jogador = int(input('Em que número eu pensei? ')) #o jogador tenta adivinhar if jogador == computador: print('Parabéns, você acertou.') else: print('Não foi dessa vez, tente de n...
17676c830d2018ffff868232ced6c850b9d8724b
MichelleZ/leetcode
/algorithms/python/designBrowserHistory/designBrowserHistory.py
897
3.84375
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/design-browser-history/ # Author: Miao Zhang # Date: 2021-05-09 class BrowserHistory: def __init__(self, homepage: str): self.urls = [] self.urls.append(homepage) self.idx = 0 def visit(self, ur...
b4408f7e8c27750a1dd619f71bc0d7d9a1471d5e
mychristopher/test
/Selenium练习/pytest_sample/base_used/test_assert.py
1,060
4
4
# 功能:用于计算a,b 相加的和 def add(a, b): return a + b # 功能:用于判断素数 def is_prime(n): if n <= 1: return False for i in range(2, n): if n % i == 0: return False return True # 测试相等 def test_add_1(): assert add(3, 4) == 7 # 测试不相等 def test_add_2(): assert add(17, 22) != 50...
e5c51a662a38f71a745b91efb285bee4f997c6e4
JulianDomingo/learningPython
/firstProgram.py
465
4
4
print('Hello, user.') print('What is your name?') name = input() print('Welcome, ' + name) print('Your name is ') print(len(name)) print(' letters long.') print('What about your age?') age = input() ageVal = int(age) print('You are ' + age + ' years old.') if ageVal >= 21: print('You are old enough to lega...
dc57b8a59de8a10eaf54bdb6d8edc788e93e9369
bigfil/Code-chef-practice
/digitCounter.py
92
3.890625
4
size = len(str(input())) if size <= 3: print(size) else: print("More than 3 digits")
1ee5530f3b42635cd91749cd181091d1748f3bad
davidyc/GitHub
/davidyc/simplepython/MyFirst.py
480
3.65625
4
from tkinter import * clicked = 0 def Click(): global clicked clicked += 1 root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked)) root = Tk() root.title("Мой первый интерфейс на Python нажатий клавиш {0}".format(clicked)) root.geometry("800x250") btm = Button(text="Click Me",...
9524dfd93676c2945b58d564376f7cc568947edc
tpeoples2/Learning-Python
/python_Challenge/puzzle3/puzzle3.py
128
3.703125
4
text = open("puzzle3txt").read() import re hits = re.findall("[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]", text) print "".join(hits)
eb9bfd62db1e67b1d0fd6ff928daaa61422331a1
nderkach/algorithmic-challenges
/reverse_words.py
445
3.640625
4
# def reverse_words(message): # m = ''.join(message[::-1]) # return ' '.join([e[::-1] for e in m.split()]) def reverse_words(message): m = list(message) m = m[::-1] j = 0 for i in range(len(m)+1): if i == len(m) or m[i] == ' ': m[j:i] = m[j:i][::-1] j = i + 1 ...
ee3cb6235f639301f814276d194b9ff3588210ca
jmajorNRELgit/Random-code_bits
/email project/clean up emails.py
1,491
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 6 14:03:41 2018 @author: jmajor """ import pandas as pd df = pd.read_csv('C:/Users/jmajor/Desktop/combined_emails.csv', header = None) emails = list(df.iloc[:,0]) i = 0 for email in emails: if len(email.split(' ')) > 1: email = email.split(' ')[-1].lstrip...
907fdd94385570eca49cf9051d75e8e5bcfc6d3d
Proxims/PythonLessons
/Lesson_13_Input.py
863
4.09375
4
# Lesson-13-Input name = input("Please enter ypur name: ") print("Privet " +name) print("------------------------\n") num1 = input("Enter X: ") num2 = input("Enter Y: ") # По умолчанию Input вводит строчные значения, summa = int(num1) + int(num2) # конвертируем в цифровые при помощ...
b3d0535f7f2180d3cd66c83e4b94d65f333e8975
brenddesigns/learning-python
/7. Conditions/conditions.py
1,804
4.46875
4
# Project Name: Conditions # Version: 1.0 # Author: Brendan Langenhoff (brend-designs) # Description: Boolean logic to evaluate conditions. x = 2 print(x == 2) # Prints out True (Logic: is 'x' equal to 2?) print(x == 3) # Prints out False (Logic: is 'x' equal to 3?) print(x < 3) # Prints out False (Logic: is 'x' le...
e7d65db3e70e1c2371b731d8ab883613d030c2cc
pageza/dojo_Python
/Python_Fundamentals/coin_tosses.py
788
4
4
# Coin Tosses # Write a function that simulates tossing a coin 5,000 times. # Your function should print how many times the head/tail appears. import random def toss_coin(): result = random.randint(0,1) return result def tosses(num): print "Starting to toss coins..." heads_count = 0 tails_count =...
25e005062bc23eff142fcb13c1251cf7381b44fb
marekkowal/LearnPythonTheHardWay
/ex43.py
3,498
4.21875
4
__author__ = 'marek' from sys import exit class Scene(object): def enter(self): print "You've just entered a scene! But you should not be really" \ " seeing this message. This is the master class's method. " \ "Implement the right one in the actual subclass." exit(1) ...
39988f2c5832ece346e70fc673318840e5ebd25a
luigi-borriello00/Metodi_SIUMerici
/sistemi_lineari/esercizi/Test5.py
1,272
3.515625
4
# -*- coding: utf-8 -*- """ Test 5 testiamo come utilizzando il pivoting i |moltiplicatori| sono tutti < 1 """ import funzioni_Sistemi_lineari as fz import numpy as np scelta = input("Seleziona Matrice ") matrici = { "1" : [np.array([[3,1,1,1], [2,1,0,0], [2,0,1,0], [2,0,0,1]],dtype=float), ...
9c6dc6e290cb758384b4d10b6b5dbebc087c4eee
ROOPAUS/Python_LeetCode
/Find words that can be formed by characters.py
532
3.78125
4
class Solution: def countCharacters(self, words:[str], chars: str) -> int: from collections import Counter count=0 charcount=Counter(chars) for s in words: scount=Counter(s) if(scount & charcount==scount): count=count+len(s) return coun...
fbbf5b904f2df758cb0df76683d0a438d052db35
Jingliwh/python3-
/pythonio.py
3,039
3.5
4
#python-IO学习 #open("路径","r/w") #读写字符注意编码错误 #绝对路径与相对路径 #1读文件 #1.1文件打开 ''' f1=open("c:/Users/Administrator/Desktop/python_stydy/py3test/py3test.py","r") str1=f1.read() print(str1) f1.close() ''' #1.2打开文件捕获异常 ''' try: f = open("py3test/py3test.py","r") print(f.read()) except Exception as e: p...
7baffbe3a806925dbbc93633428f21ad6e66a202
lindaverse/edx6.00
/Week 1/problem1.py
923
3.703125
4
numbob = 0 state = 0 s = 'sjshsbobbobsdhfjkafsdjkncvakhufvjkhvckjvcjkvjdackljasvdkljvlkacsjkvljcaxklavc' for letter in s: if state == 0: if letter == "b": state = 1 elif state == 1: if letter == "o": state = 2 elif letter == "b": state = 1 el...
d63dccf64ebb313639bef486522cfea02768793e
Willian-PD/Exercicios-do-Curso-de-programacao-para-leigos-do-basico-ao-avancado
/Exercícios de python/secao-3-parte-5.py
100
3.546875
4
altura = float(input('Digite a sua altura: ')) print(f'Seu peso ideal é {(72.7 * altura) - 58}')
0a7dd139541bb011ca1303e3b4478715a6d5b119
gguilherme42/Livro-de-Python
/Cap_7/ex7.3.py
219
4.0625
4
s1 = list(input('String 1: ').upper()) s2 = list(input('String 2: ').upper()) lista = [] for l in s2: if l not in s1: lista.append(l) for l in s1: if l not in s2: lista.append(l) print(lista)
7d50efcac28c0c6b510c5759b866a1a323732365
vidhyaveera/vidhyaveeradurai
/sorted.py
109
3.5625
4
m=int(input("") n=list(map(int,input().split())) b=sorted(n) if b==n: print("yes") else: print("no")
ddfea4ef8a9c6ecc90fe1fa421cdba608a1fdb3a
CarlosVRL/daily-coding-problem
/src/tests/problem_83_tests.py
2,039
3.5
4
""" Module problem_83 tests """ import unittest import sys sys.path.append("../problems") import problem_83 class TestMethods(unittest.TestCase): def test_simple_case_is_valid(self): # Initialize the nodes a = problem_83.Node("a") b = problem_83.Node("b") c = problem_83.Node("c") ...
5e1c76466b5a4e309b8e53ced65d3f651168969e
anujns/Predictive-Analytics
/Assignment 2/Submission/mapper2.py
1,104
3.703125
4
#!/usr/bin/python3 import sys import re import string for line in sys.stdin: words = line.split() words = re.findall(r'\w+', line.strip()) length = len(words) i = 0 while (i+2 < length): first = words[i] first = first.strip(string.punctuation).lower() second = words[i+1] second = second.strip(string.p...
e465bf117aef5494bb2299f3f2aaa905fb619b52
purple-phoenix/dailyprogrammer
/python_files/project_239_game_of_threes/game_of_threes.py
1,346
4.25
4
## # Do not name variables "input" as input is an existing variable in python: # https://stackoverflow.com/questions/20670732/is-input-a-keyword-in-python # # By convention, internal functions should start with an underscore. # https://stackoverflow.com/questions/11483366/protected-method-in-python ## ## # @param o...
da376b2371aaf992f321d37f8e83881d3b384a3a
csiggydev/crashcourse
/3-1_names.py
193
3.578125
4
#! /usr/bin/env python # 3-1 Names names = ['Mike', 'Jason', 'Matt'] print(names) # Print Mike only print(names[0]) # Print Jason only print(names[1]) # Print Matt only print(names[2])
447077741c6922c3a942c5f77b377f84f9f1d549
windniw/just-for-fun
/leetcode/328.py
949
3.671875
4
""" link: https://leetcode.com/problems/odd-even-linked-list problem: 给链表,要求拆分成奇数项在前,偶数项在后的形式,时间O(n),空间O(1) solution: 拆链表保存奇偶项表头和表尾 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, hea...