blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0e1f1a1014983d50fc7f5395cda3c1cc186ba429
silverfox516/play
/python/closer.py
503
3.59375
4
def outer_func(tag): tag = tag def inner_func(txt): print '<{0}>{1}<{0}>'.format(tag, txt) return inner_func my_func = outer_func('my') print my_func print print dir(my_func) print print type(my_func.__closure__) print print my_func.__closure__ print print my_func.__closure__[0] print print dir...
5eee8ba7adc1dbd83cec993eb6ce5e44dc42f105
davesheils/Project
/project2018.py
4,995
3.734375
4
# import modules import numpy as np import statistics as stat import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # code to clear screen. Use clear if Unix, cls if windows (plese note: tested on Linux only) def clearscreen(): import platform import os if platform.system() == "Window...
6c56497b596ce6c618e4133422e3d9d8f695a6c3
rcolina17/guessgame
/main.py
1,329
3.90625
4
import random def humanguess(): number=random.randrange(0,10) print(number) numero=-1 while numero!=number: numero=int(input("Dame un numero del 1 al 10 ")) if number==numero: print(f"Felicidades ganaste {number}") elif number > numero: print(f"El ...
752733c3adc2f467ccae8a91dce6d73e6b672101
tanjina-3ni/PythonCodes
/randomIntInaRange.py
272
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 09:13:49 2020 @author: Aspire """ import random x=[] y=[] for z in range(0,20): x.append(random.randrange(0, 15)) for z in range(0,20): y.append(random.randrange(0, 15)) print (x) print (y)
8513413b804dff72a09ab9efafafc55f2d5b5be1
paul0920/leetcode
/question_leetcode/1087_3.py
942
3.59375
4
def expand(s): """ :type s: str :rtype: List[str] """ if not s: return [] res = [] dfs(0, s, [], res) return sorted(res) def get_char_to_expand(index, s): stack = [] close_bracket_index = None for i in range(index, len(s)): char = s[i] if char ==...
6fd40ca0afa28e7e94d5e837d1949ac71531c421
katryo/leetcode
/5-longest-palindromic-substring/solution.py
2,594
3.546875
4
class Solution(object): # def longestPalindrome(self, s): # """ # :type s: str # :rtype: str # """ # # if not s: # return "" # if len(s) == 1: # return s # # table = [[-1] * len(s) for _ in range(len(s))] # # def pal...
3a391de27d17f6f24441b494e07f3f09995aa426
Jyldyzbek/T2Part22
/task-22.py
215
3.78125
4
tF = int(input('Vedite °F: ')) tC = int(input('Vedite °C: ')) TC = 5/9 * (tF - 32) TF = 9/5 * tC + 32 print('Celsius', round(TC, 2)) print('Farengate', round(TF, 2)) # a = (32 °F − 32) × 5/9 = 0 °C
ff6d4843be5d281eeef09d19185477348ff35a51
jrclayton/RosalindProblems
/Bioinformatics Stronghold/010_FIBD/FIBD.py
1,821
3.59375
4
#!/usr/bin/python # This approach will use a loop if else loop to split the relations # based on the input values of n and m #def fib(n, m): # if n < m: # # Use relation A # if n == 0: # return 0 # elif n == 1: # return 1 # elif n > 1: # return fib(n-1, m) + fib(n-2, m) # result from relation A # elif n == m ...
2097fb154f51b06df22b9ff0eccbe5b2564cf89e
SerikDanaaa/Python_
/TSIS9/paint.py
5,958
3.625
4
# Paint import pygame, random import os pygame.init() # (x1, y1), (x2, y2) # A = y2 - y1 # B = x1 - x2 # C = x2 * y1 - x1 * y2 # Ax + By + C = 0 # (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) def drawLine(screen, start, end, width, color): x1 = start[0] y1 = start[1] x2 = end[0] y2 = end[1] dx = ...
94b150c97723def2d0010b0ee6f959a22bd3240d
sidmadethis/files_exceptions
/file_reader.py
1,015
4.40625
4
# with open('pi_digits.txt') as file_object: # contents = file_object.read() # print(contents) # this opens the pi digits file, reads it, and then prints out the text to the screen. # you first need to open the file to access it. the open() function needs one argument, the name of the file. python looks for ...
6405c37942bec9d8978455434b3f365edb1aea3a
harry4401/30DayOfPython
/Day-10/Day_10_Mohit.py
168
4.09375
4
#sum of the n natural numbers i =int(input("Enter the number : ")) sum = 0 for i in range(0,int(i)+1): sum = sum+i print(sum," is the sum of ",i," numbers.")
f9b085edb91f8408386f6f16b51512d76e5b6e97
ifpb-cz-ads/pw1-2021-2-ac-s4-team_denis
/questao_07.py
263
4.03125
4
#7. Faça um programa que peça dois números inteiros. Imprima a soma desses dois números na tela. numero1= int(input("Informe o 1ª numero:")) numero2= int(input("Informe o 2ª numero:")) print('A soma de',numero1,'+',numero2,'é igual a:',numero1+numero2)
1e6056ea938feb355802b29a10128a119a16f806
akshat-52/FallSem2
/act1.27/9.py
142
3.640625
4
my_tuple=('a','p','p','l','e') print(my_tuple.count('p')) print(my_tuple.count('e')) print(my_tuple.index('p')) print(my_tuple.index('e'))
87dead39db7e8e6bf6902ae72aa34ecbbefd3f29
whosedaddy/Learn_python_the_hard_way
/learn_python/recursive.py
130
3.640625
4
def re(n,f,t,s): if n==1: print "From %s to %s."%(f,t) else: re(n-1,f,s,t) re(1,f,t,s) re(n-1,s,t,f) re(10,'f','t','s')
18fe5bd8730a5749e445668c4b31b2fc30715f7e
phillipfranco55/The-Beginning
/strings_and_methods_excercises.py
599
3.6875
4
# Was asked to create a string, school with the name of my elementary school. # Examine the methods that are available on that string. Use the help function. # So I viewed the methods with the dir function, picked the first on the list and # .casefold() lists all the methods with there help() file. school = 'Jackson'...
7ce46401826d19c36c52b217095cfcd5088e3338
Crigerprogrammer/Algebra_Lineal
/suma_vectores_numpy.py
785
3.875
4
import numpy as np rojo = [255,0,0] verde = [0,255,0] azul = [0,0,255] negro = [0,0,0] # Numpy tiene una estructura de datos llamado numpy arrays y se pueden crear con la propiedad array # Los numpy array tienen las propiedades de un vector y su suma puede ser como los vectores algebraicos rojo = np.array(rojo) verde...
6401c8f67b8a72fd50e7e492d3dd86411ca3e39d
raydot/coursera
/mathThinkingInCoSci/wk02more_puzzles.py
314
3.671875
4
# ∃ a six-digit number that starts with 100 and is divisible by 9,127 # x = 0 for y in range(0, 999): if (y < 10): candidate = '10000' + str(y) elif(y < 100): candidate = '1000' + str(y) else: candidate = '100' + str(y) # print(candidate) if (int(candidate) % 9127 == 0): print(candidate)
079275c5102d56c6eebd3a7a82a90c2cdb58fcf4
cczhong11/Leetcode-contest-code-downloader
/Questiondir/717.1-bit-and-2-bit-characters/717.1-bit-and-2-bit-characters_125771223.py
423
3.53125
4
class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ can = [False]*(len(bits)+1) can[0] = True for i in range(len(bits)-1): if can[i]: if bits[i] == 0: can[i+1] = ...
696492506f69be4e3d9aafd0ea042d3ade185acd
pointschan/pylearning
/listComprehension.py
784
4.28125
4
__author__ = 'pointschan' #to create a list of squares squares = [] for x in range(10): squares.append(x**2) print squares #create the same list of squares as above squares = [x**2 for x in range(10)] print squares #can also use built-in function map() and lambda expression #map(function, sequence) squares = m...
5aea24a1f0f564fc3d96667895c71401485770a2
Borlander5/PythonClass
/shep/city_functions.py
837
3.859375
4
#11-1. """A collection of functions for working with cities.""" def city_country(city, country): """Return a string like 'Santiago, Chile'.""" return f"{city.title()}, {country.title()}" #11-2. """A collection of functions for working with cities.""" def city_country(city, country, population): """Ret...
ac25e58d6056ef6082df4e2428fadbbf71420107
daikiante/python
/43_func_default.py
503
3.75
4
# functions with the default values def greet(name='lohit',age=20,country='India',work='spiceup'): print(f'my name is {name}, my age is {age}, from {country}, I working {work}') greet() greet('daiki',23,'Japan','student') print('--------------------------------') def calls(name='lohit'): print(name) ...
6294736f106dda0a0c1861794e66214c5e2816d3
carloseduardo1987/Python
/ex20_lista02.py
772
3.9375
4
print('### Calculadora de média escolar ###') n1 = float(input('\nInforme a primeira nota bimestral: ')) n2 = float(input('Informe a segundo nota bimestral: ')) n3 = float(input('Informe a terceira nota bimestral: ')) n4 = float(input('Informe a quarta nota bimestral: ')) md1 = (n1+n2+n3+n4)/4 print(f'\nO valor...
6873610a83ba0ddd0648a8052650627f72c093eb
AndreiRStamate/snekkk
/salut.py
13,586
3.5
4
import pygame import random import time def pause(): paused = True gameDisplay.fill(white) message_to_center("Game paused", black, -100, "large") message_to_center("Press 'p' to unpause or q to quit.", black, 25) pygame.display.update() clock.tick(5) while paused: fo...
d5a979d02f31cf7c056ed274c95b5329ebc9908e
cortadocodes/machine-learning
/machine_learning/logistic_regression/logistic_regression.py
3,447
3.8125
4
import numpy as np class LogisticRegressionWithGradientDescent: """An adaptive linear neuron implementation of logistic regression; an improvement on the perceptron; uses gradient descent of the logistic cost function (log-likelihood) to arrive at the global cost minimum. Type: supervised - binary classi...
74864c19ac096567aad04fe94f78ef43f7c67c3b
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4127/codes/1637_2447.py
181
3.796875
4
pc= float(input("qual o valor do produto?")) pgm= float(input("qual o valor do pagamento?")) if (pc>pgm): print("Falta",round(pc-pgm,2)) else: print("Troco de",round(pgm-pc,2))
fe7f84702f9469b466cd304ad7bfd5d80c081525
NanZhang715/AlgorithmCHUNZHAO
/Week_01/merge.py
1,662
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 初始化 nums1 和 nums2 的元素数量分别为m 和 n 。你可以假设 nums1 有足够的空间(空间大小等于 m + n)来保存 nums2 中的元素。 例 1: 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 输出:[1,2,2,3,5,6] 链接:https://leetcode-cn.com/problems...
1893c6d3402d7e8d599a59fe001b37973ab13d54
PavloBryliak/Lab_14
/fourth/game.py
1,099
3.609375
4
import random from fourth.board import Board, computer def determine(board, player): a = -2 choices = [] if len(board.available_moves()) == 9: return 4 for move in board.available_moves(): board.make_move(move, player) val = board.alphabeta(board, computer(player),...
0297d733f593fa9bbddc0fb0ccd3ddb06c1a9b15
CircularWorld/Python_exercise
/month_01/day_06/homework_06/homework_04.py
225
3.90625
4
''' 4. 将列表中的数字累减 list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] 提示:初始为第一个元素 ''' list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5] result = list02[0] for num in list02: result -= num print(result)
392a4ee2ce75643a600b866a499793af465ae835
adityachhajer/LeetCodeSolutions
/56MergeIntervals.py
624
3.65625
4
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: if intervals == []: return [] intervals.sort() stack = [] stack.append(intervals[0]) for i in range(1, len(intervals)): if intervals[i][0] > stack[-1][1]: ...
984c16e14a8b86945f5a728163c10c515812e641
Vasilic-Maxim/LeetCode-Problems
/problems/13. Roman to Integer/1 - Two Pointers.py
518
3.625
4
class Solution: """ n - length of the string Time: O(n) Space: O(1) """ def romanToInt(self, s: str) -> int: vocab = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} slow = fast = len(s) - 1 result = 0 while fast >= 0: s_val = vocab[...
476d0c4232eaef3a97c4d2c4d603c2529f940e6f
shaoye/algorithm
/jianzhioffer/顺时针打印矩阵.py
258
3.65625
4
class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): ret = [] while matrix: ret.extend(matrix.pop(0)) matrix = list(zip(*matrix))[::-1] return ret
8e0f12e981e9298065ac13fe81abd90f95edf2fc
aizhan00000/game
/lection19.py
2,273
3.78125
4
# class CLassName: # # a = 5 # # b = 5 # # # # def __init__(self, hp): # # self.hp = hp # # # # def __del__(self): # # print("IAS") # # # # def print_hp(self): # # print(self.hp) # # print(self.a) # # # # # # class ClassName2(CLassName): # # def print_hp(self): # ...
2cb2e456fbe8389d82009c8db7ca975d97d7f281
lobzison/python-stuff
/AT/clustering.py
6,765
4.03125
4
""" Student template code for Project 3 Student will implement five functions: slow_closest_pair(cluster_list) fast_closest_pair(cluster_list) closest_pair_strip(cluster_list, horiz_center, half_width) hierarchical_clustering(cluster_list, num_clusters) kmeans_clustering(cluster_list, num_clusters, num_iterations) wher...
bfc46d879aa3f368f7920b2578c4413edb972d4d
glennsvel90/Hangman-Game
/hangman_game.py
2,356
4.03125
4
import os import random import sys #make a list of words words = ["guide", "ultimate", "delete", "slides","sunny", "repository", "request", "setting", "explore", "wisdom", "apple", "banana", "cobra", "tentacles", "waterfall"] def clear(): """ clear the terminal """ if os.name == 'nt': os.system('cls') else: ...
9c95296a2eb280019e461e4f3cf72bb33469f865
cbohara/think_stats
/ch5.py
2,477
3.53125
4
"""This file contains notes and code from Chapter 5.""" import scipy.stats import thinkstats2 import thinkplot import nsfg import analytic def eval_normal_cdf(x, mu=0, sigma=1): """Evaluate normal CDF and assume standard normal distribution as default.""" return scipy.stats.norm.cdf(x, loc=mu, scale=sigma) ...
e03163fc82b0a674d7550de2318d70997f0c5b84
Asupkay/SSW-567
/HW 01/classifyTriangle.py
2,131
3.75
4
import math from numbers import Number def classifyTriangle(a, b, c): if(not isinstance(a, Number) or not isinstance(b, Number) or not isinstance(c, Number) or a + b <= c or a + c <= b or b + c <= a): return 'NotATriangle' if(a == b and a == c): return 'Equilateral' if((a == b and a != c) o...
d4a9f92211cd8515de94a2d5815e71bab92e1d1a
marcelodinamo/Exercicios_python_ALP
/5_Salario.py
140
3.578125
4
sal_b = float(input("Digite seu salario: ")) imp = sal_b * 0.1 sal_r = 50.00 + sal_b - imp print("Salario à receber: {:.2f}".format(sal_r))
eabaf262e99f892958a84077c9b5920e0988bdbd
Lucky-Dutch/password-generator
/pass_creator.py
1,561
4.34375
4
""" This program create random passwords. """ import random import string import datetime print("Hello in Password Creator 0.01\n\ Choose a right number: \n\ 1 - simple password with 6th letters\n\ 2 - password with letters (small and big) and numbers with your value of characters\n\ 3 - C...
55c05975135cd06379862ee9ab647f24cd9fc6c7
13323106900/1python-diyigeyue
/19自主复习day/闰年.py
144
3.828125
4
year = int(input("请输入年份")) if year%4==0 and year%100!= 0 or year%400==0: print("%d是闰年"%year) else: print("%d是平年"%year)
5a91da07fce38eeaf61fde307dbe2ceadca3b7ae
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/medium_algo/2_9.py
4,462
3.703125
4
Merge Sort vs. Insertion Sort **Pre-requisite:Merge Sort, Insertion Sort** ** _Merge Sort_ :** is an external algorithm and based on divide and conquer strategy. In this sorting: 1. The elements are split into two sub-arrays **(n/2)** again and again until only one element is left. 2. Merge sort us...
898eb96dbec9b6b0717e97f0a7aa85fc34090fa4
JorrgeX/CMPSC132
/Hsieh_Program5.py
4,420
4.0625
4
#Hsieh_Program5 #Yuan-Chih Hsieh #CMPSC132 Program5 class Node: def __init__(self, data=None): self.data = data self.next = None self.prev = None def get_data(self): return self.data def get_next(self): return self.next def get_prev(self): ...
8a2260c1ad39715e3e78a9d75c42b53e4b8552c5
kalbury/DnD-Character-Creator
/Character_Creation.py
42,751
3.9375
4
### Character information up to date for DnD Next version 4/11/13 ### import random as r print "~~~~ Welome to DnD Next Simple Character Creator ~~~~" print print "This program will help you create a character quickly " \ "to the point where you will need to begin choosing " \ "choosing armor, items, skil...
9b19491c1d6dc59f2625f116470a1e147e2746f5
githubfun/LPTHW
/PythonTheHardWay/projects/lexicon_project/ex48/lexicon.py
1,252
4.25
4
# Created for Learning Python the Hard Way, Exercise 48 def scan(sentence_to_parse): directions = {'north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back'} verbs = {'go', 'kill', 'eat', 'stop', 'shoot'} stop_words = {'the', 'in', 'of', 'from', 'at', 'it', 'to'} nouns = {'bear', 'princess', 'do...
28be7aaf0233c6f98b89a0edd8ffd181be162299
Malakai13/chess-tree-explorer
/MoveCount.py
1,184
3.515625
4
class MoveCount: def __init__(self, move): self.move = move self.count = 1 self.white_wins = 0 self.black_wins = 0 def __init__(self, move, game_results): self.move = move self.count = 1 self.black_wins = 0 self.white_wins = 0 self.increment_by_game_results(game_results) def increment_count(sel...
fd24b3900bc159123582a764faa95efbf5f54eef
SimonFans/LeetCode
/OA/MS/Numbers With Equal Digit Sum.py
442
3.796875
4
def find_digit_sum(num): val = 0 while num: val += num % 10 num //= 10 return val def num_digit_equal_sum(arr): digit_sum_map = {} max_val = -1 for num in arr: digit_sum = find_digit_sum(num) if digit_sum in digit_sum_map: other_val = digit_sum_map[digit_sum] max_val = max(max_val, other_v...
7fa8b029ce0ece9eaec2ad5a68e68c003329aad6
yilmazelif97/librarymanagementsystem
/DataAccess.py
861
3.65625
4
import sqlite3 as sqlite connection = sqlite.connect('library.db') connection.row_factory = sqlite.Row # Enables accessing columns via names database = connection.cursor() def getLogin(userloginname, password): result = database.execute(''' SELECT * FROM user WHERE userloginname = ? AND password = ? '''...
37af10df860fe06d3d3518481ee71aaa37833c87
prernaralh19/file
/que4.py
158
3.765625
4
def test_range(n): if n in range (10,100): print ("10 is in the range 100" (n)) else: print("the number is outside the given range") test_range(10)
b5974ffb1b7fcf00ffe5ba96953cedeb6df68bd8
Mahler7/zelle-python-exercises
/ch8/ch8-ex7.py
1,162
4.09375
4
def goldbach_values(primes, n): highValue = n / 2 for i in primes: if i <= highValue and n - i in primes: print("Prime values {0} + {1} = {2}".format(i, (n - i), n)) def get_primes(n): p = 2 primes = [] while p <= n: if is_prime(p): primes.append(p) p...
193f3f0ba4b3771d957df995d521b706363c07f2
AMBrown0/DataVizAss02
/Python/sigmoid.py
1,238
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 7 16:28:27 2021 @author: andy """ #import section from matplotlib import pylab import pylab as plt import numpy as np #sigmoid = lambda x: 1 / (1 + np.exp(-x)) def sigmoid(x): return (1 / (1 + np.exp(-x))) mySamples = [] mySigmoid = [] # generate an Array with va...
f3b47758b43ba94dd3e47698b4aa69f8fa0c229d
harshiniravula/DSP_LAB
/lab1_prog2(matrix_inverse).py
1,200
4.1875
4
# python code to find transpose of a matrix def cofactor(a): b=len(a) cofactor=[] for i in range(b): m1=[] for j in range(b): m2=[] for k in range(b): m3=[] for l in range(b): if(i==k or j==l): continue m3.append(a[k][l]) if(e!=[]): m2.append(e) if((i+j...
4b6edb266a39f582b108de4e45cf5380bb9276cc
SimonSlominski/Pybites_Exercises
/Pybites/135/books.py
2,725
4.25
4
""" Bite 135. Sort a list of book objects In this Bite you are going to look at a list of Book namedtuples and sort them by various criteria. Complete the 4 functions below. Consider using lambda and/or one or more helper functions and/or attrgetter (operator module). """ from collections import namedtuple from datet...
4bc6c85d1990d48694e80eb365770f35a23903c7
Grillern/H20_project0_harrisms_Optional_Exercise
/calculator.py
1,219
3.9375
4
def add(x, y): return x + y def factorial(n): if type(n) is int and n >= 0: factorial = 1 for i in range(1, int(n)+1): factorial *= i return factorial else: raise Exception(f"Factorial cannot be {type(n)} or a negative number. Type a natural number") de...
499bc6dc2a5430049a5002fd54df3afb4fbbfc95
DemonsHacker/learntf
/python/mo_fan/01_python3/02_if_else.py
219
4.21875
4
x = 1 y = 2 z = 3 if x<y: print('x is less than y') else: print('y is less than x') if x<y and y<z: print('x is less than y,and y is less than z') x = 2 y = 2 z = 0 if x == y: print("x is equal to y")
663c582183d36b6d261be256775d3955bcffac83
cielavenir/codeiq_solutions
/tbpgr_colosseum_manager/q1027/death6_1.py
75
3.53125
4
print(':'.join(str(i)for i in range(2,999)if all(i%j for j in range(2,i))))
dd6630cb373ab75e4c772626accb30dbc85d2b5b
sshukla31/leetcode
/wiggle_sort.py
1,082
4.1875
4
''' 280. Wiggle Sort Medium 344 42 Favorite Share Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... Example: Input: nums = [3,5,2,1,6,4] Output: One possible answer is [3,5,1,6,2,4] ''' class Solution(object): def wiggleSort(self, nums): """ ...
36c7023ceb1afa8065832ab6b8af1edca8fe9697
arononeill/Python
/ClassAttributes.py
1,008
4.21875
4
# Built-In Class Attributes class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmpl...
521fcd2ecf232bddf99b5c8a9fcba26b507b09da
colinsongf/6.00.1x_Python_course
/wordgame.py
3,601
3.9375
4
# Fisseha Berhane # MITx: 6.00.1x Introduction to Computer Science and Programming Using Python # Problem set 4 #dictionary = raw_input('Please give the word list file name\n\t') # This waits for the word list file name with appropriate extention #f = open(dictionary, "r") f = open('sowpods.txt', "r") print'' pr...
f2ed8fc548ac55b2b2404e881a31bc2d5482addb
eebmagic/phy214_enterprise_online
/python_functions/optics/lenses.py
2,041
4
4
''' A collection of functions using formulas related to projections through lenses ''' def image_distance(object_distance, focal_distance): ''' Returns the distance (cm) to the projected image Given the: distance to the object being projected (cm), focal distance of the lens (cm) Formu...
58dc93bccbc91f856bb8d32f735b988c18fb3aca
momo1606/Takhteet
/takhteet/takhteet.py
2,288
3.75
4
import test import myiter import time print("*********************** WELCOME ***************************") print("USER GUIDELINES") print("\n1. The user has to feed-in the following details:\n\ta)Number of students.\n\tb) Total number of days\n\t and then for each student,\n\tc) Student's name.\n\td) Student's curren...
2c7f6a6bb0ab06e16b476ab5cb0df7d4ccfd011c
juliermili/seminario
/Historico/Ejer teoria 1.py
356
3.6875
4
def futuro(edad): edad = edad + 1 def pasado(): edad = edad - 1 edad = int(input('Ingresa tu edad: ')) resp = int(input("""Elige una opción: 1.- El año que viene tu edad será... 2.- El año pasado tu edad era.... """)) if resp == 1: futuro(edad) print (eda...
640519a533c85d16321b70427e2b4ecc135dd2d4
jordano1/python
/python_education/regex/regex.py
1,136
4.3125
4
import re string = "search this inside of this text please!" # methods in re.search print('search' in string) a = re.search('this', string) print('tells you where the string is index: ', a.span()) # 17, 21 print('start tells you when the text starts:', a.start()) # 17 print('tells you where the text ends: ' , a.end()...
c7c30b55093879b4af4a70d5274bd39a0326a837
letsbrewcode/python-coding-lab
/lab-9/fizzbuzz.py
557
4.21875
4
""" Problem: FizzBuzz Complete the function below. For a number N, print all the numbers starting from 1 to N, except 1. For numbers divisible by 3, print "Fizz" 2. For numbers divisible by 5, print "Buzz" 3. For numbers divisible by both 3 and 5, print "FizzBuzz" Example: N = 30 Outpu...
b6eeefcea1b0eda6fb8964fa80fbdde214fbc893
v-glovatskiy/playground
/log1.py
275
3.515625
4
from sys import argv script, filename = argv name = 'COMPLETED after 1' txt = open(filename) print ('Содержимое файла %r' % filename) #print (txt.read()) for string in txt: if name in string: print(string)
986a00007a84702ef34c948faae02a176b0c92b6
DecadentOrMagic/XY_python3_lxf
/01_Python基础/02_使用list和tuple.py
3,721
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # List # Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 # 变量classmates就是一个list # ************************************* classmates = ['Michael','Bob','Tracy'] print(classmates) # 获取list元素的个数 print(len(classmates)) # 用索引来访问list中每一个位置的元素,记得索引是从0开始的 print(classmates[0]...
bcd4f4b15e374d4bf32d0f13bcca4c64aead6a05
VaishnaviReddyGuddeti/Python_programs
/Python_Sets/getthelengthofaset.py
197
4.25
4
# To determine how many items a set has, use the len() method. #Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print(len(thisset)) thisset = {" "} print(len(thisset))
bcc47559030863467b689d5a18b9490b19469f7b
ninjaboynaru/my-python-demo
/leetcode/94-binary-tree-inorder-traversal.py
554
3.5625
4
from utils import TreeNode, stringToTreeNode from typing import List class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: if root is None: return [] res = [root.val] left = self.inorderTraversal(root.left) right = self.inorderTraversal(root.right) ...
861389b28c0b685065defd0ae85d92a63e742079
JordanWauchope/Python
/Excercises/ExcercisesSep28/Sec10-String.py
785
3.671875
4
useInputs = False def sentence1(): sentence = "I like to go on holiday by the sea." for x in sentence: print(x) # sentence1() def sentence2(): sentence = "I like to go on holiday by the sea" print(len(sentence)) for x in sentence: if 7 <= x < 24: print(sentence[x])...
ecd3b4bb48ebbb254d361477ecd3894c0feb09c3
bgergovski/simple-webapp
/other/classes.py
202
3.609375
4
class Person: def __init__(self, name): self.name = name def talk(self): print(f"{self.name} is my name") person_1 = Person("Bobby") person_1.talk() x = "Hello"[0] print({x})
fbe0d6bc2ba6fe23a67c59119e5197acbb29c44d
thonathan/Ch.02_Algebra
/2.0_Jedi_Training.py
939
4.28125
4
''' Sign your name:______ethan januszewski__________ 1.) How do you enter a single line comment in a program? Give an example. 2.) Enter a=2 and b=5 in the Python Console window and then all of the following. What are the outputs? If the output is an error record the error and try to determine what the error is! b...
ef319c8112b043034d165bf0dbec05ea969f3065
subaquatic-pierre/algorithmic-toolbox
/divide_algorithms/majority_element/majoity_element.py
619
3.6875
4
# Uses python3 import sys def get_majority_element(a, left, right): size = len(a) value_counts = {} for elem in a: if elem in value_counts.keys(): value_counts[elem] += 1 else: value_counts[elem] = 1 found = False for key, value in value_counts.items(): ...
d7af1d4eaadc8ec39427784cf1ec8f7aee0ff007
arnabs542/achked
/python3/company/lnkd_rpn_eval.py
862
3.75
4
#!/usr/bin/env python3 def evalRPN(self, tokens): stack = [] for t in tokens: if t not in ["+", "-", "*", "/"]: stack.append(int(t)) else: r, l = stack.pop(), stack.pop() if t == "+": stack.append(l+r) elif t == "-": ...
42a46914a360a1dc4cc63a5a0ea0c035c4ee9e7d
Programmer-Admin/binarysearch-editorials
/Contiguous Intervals.py
598
3.515625
4
""" Contiguous Intervals We iterate over the sorted numbers, each time the present number isn't equal to the past number, we append the interval. Trick so you don't have to deal with edge cases: add big value at end, so you don't need to check if you reached the end, or if the list is at least length 2. """ class So...
7e8a9217dc478c89305b533e62219703a5a0f61b
kammitama5/Wally_Scale_game
/_005.py
1,771
4.21875
4
# build a game where if something is on a scale, calculate how much weight # kg vs pounds # Prints Welcome to Wally the scale. # You can weigh things with me. # Would you like to work in kg or pounds. Choose option # Bilingual..which want me to speak (implement library # Please select an object to weigh from choices...
d51f78adced21aa103b44ebd2e5e1836d86e662a
prachuryanath/DSA-Problems
/Easy/21. Merge Two Sorted Lists/ans.py
342
3.5625
4
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() curr = head while l1 and l2: while l1 and l2 and l1.val <= l2.val: curr.next = l1 l1 = l1.next curr = curr.next while l1 and l2 and l2.val <= l1.val: curr.next = l2 l2 = l2.next curr = curr.next curr.next = l1 o...
0e99844753b33b66d6e5fe283c9a84f16bf4256f
CristianCuartas/Python-Course
/Ejercicios/24- Objetos.py
305
4.03125
4
print('Objeto qué almacena el número y su potencia cuadrada') objeto = {} condicion = True while condicion: numero = int(input('Introduzca un número: ')) cuadrado = (numero**2) if numero != 0: objeto[numero] = cuadrado elif numero == 0: condicion = False print(objeto)
9699811745c9d7495ff8c48413d4406f431b9141
Lonitch/hackerRank
/leetcode/599.minimum-index-sum-of-two-lists.py
2,187
3.765625
4
# # @lc app=leetcode id=599 lang=python3 # # [599] Minimum Index Sum of Two Lists # # https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/ # # algorithms # Easy (49.06%) # Likes: 467 # Dislikes: 172 # Total Accepted: 74.5K # Total Submissions: 150.5K # Testcase Example: '["Shogun","Tapioca E...
2920bb9e665cfe98e8be5a6067e88bb1196370fb
ml1976/tools
/remove_images_smaller_than/remove_images_smaller_than.py
478
3.546875
4
# put this file in the same folder as images, and set your height and width from PIL import Image import glob import os for filename in glob.glob('*.jpg'): #assuming jpg #print(filename) #file, ext = os.path.splitext(filename) image=Image.open(filename) width, height = image.size image.close() #close the file...
60209ad440c3e568c665b4bcfb4106079499c62b
ayush7garg/RGB-Gray
/video.py
336
3.578125
4
import cv2 def gray(image): gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)#cvtColor converts an image from one color space to another return gray cap = cv2.VideoCapture("path of the video file") while(cap.isOpened()): _,frame = cap.read() gray_image = gray(frame) cv2.imshow('result',gray_image) ...
41357bb12afc7cb165d872d10b1ceaa7f3636c4d
deartc/Fitnesspythonproject
/dancestepsthree.py
938
3.9375
4
import random ### Here you must define random for use. Otherwise, python3 will return as "radiant" not defined player = input("Player, choose your dance: ").lower() rand_num = random.randint(0,2) if rand_num == 0: computer = "bolero" elif rand_num == 1: computer = "hustle" else: computer = "samba" ...
a8374941d3c8ea5b4c9bf43a65ba16326f096c9d
karolinaewagorska/lesson2
/data.py
2,281
3.84375
4
# Задание 1 # Необходимо вывести имена всех учеников из списка с новой строки names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in names: print(name) # Задание 2 # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём. names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in ...
ed465eb2bfb4ae99f828b704b0296cb2dc31f9b5
Goodusernamenotfound/c4t-nhatnam
/session7/districts.py
468
3.90625
4
name = ["ST", "BĐ", "BTL", "CG", "ĐĐ", "HBT"] population = [150300, 247100, 333300, 266800, 420900, 31800] # highest = 4 # lowest = 0 # print("District with highest population:", name[highest], "with", population[highest], "residents") # print("District with lowest population:", name[lowest], "with", population[lowest]...
85b53898c2dada92118141c243070bd8447da15f
daviddumas/pmls05-demo
/samples/representation.py
624
3.578125
4
'''Demonstrate computing 2x2 matrix representation from strings''' # ---- BEGIN code from presentation slide ---- import numpy as np def representation(gen_matrices): def _rho(x): if len(x) == 0: # identity matrix return np.eye(2) elif len(x) == 1: # generator ...
65885e96aca4b958d6ca03ffcfc6d2cb95a479ca
gsudarshan1990/Python_Sets
/Doc_Strings/example1.py
2,631
4.21875
4
def add(a,b): """Addition of two integers and returns the resulting integer""" return a+b help(add) print(add.__doc__) class Triangle: """ methods: find_area() provides information about the area of the trianlge find_perimeter() provides information about the perimeter of the triangle ...
aa63576d2224fae9538f04c76eb06657f1eb3eea
Atabekarapov/Week7_multiple_inheritence_Task
/multiple_inheritence.py
5,008
3.859375
4
# TASK1. WEEK7. ATABEK # 1) '''Будильник Создайте класс Clock, у которого будет метод показывающий текущее время и класс Alarm, с методами для включения и выключения будильника. Далее создайте класс AlarmClock, который наследуется от двух предыдущих классов. Добавьте к нему метод для установки будильника, при вызове ко...
b68fc9da284f54f00786e180c0e5817c52bcc0ad
acreel0/Creel-MATH361B
/NumberTheory/N1_Collatz_Creel.py
3,246
4.34375
4
# Defining Collatz Function def collatz(a0,N): # a0 = initial term # N = total number of terms to compute coll_list=[a0] for ii in range(N): if (coll_list[ii]%2 == 0): term = coll_list[-1]/2 else: term = 3*coll_list[-1]+1 ...
eb644b92348a0b2c2995b861b69740cc717de603
ArnasKundrotas/algos-python
/binary-search-rot-array.py
903
3.5
4
############## # UNSOLVED ############## # Binary search # Rotated arr # Sorted arr [2,3,6,7,9,15,19] was rotated (shifted) # arr: [6, 7, 9, 15, 19, 2, 3] # index: 0 1 2 3 4 5 6 # left mid right # mid right # ...
6770d9342cf3def621c90e57439204e101e7594a
webdeziner/tools
/python/count-html-tags/search.py
586
3.5625
4
# -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup from collections import defaultdict occurrences = defaultdict(int) __author__ = 'Webdeziner.se' searchUrl = raw_input('Which url to scan: '); def make_soup(url): response = requests.get(url) return BeautifulSoup(response.content, 'lxml') ...
851cf7a22e835b0408fca21c5ffeb8a3632bc3bb
AbdelhamidElKrem/Day4
/main.py
764
4.15625
4
import random; import check; Rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' Paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________...
36c68c3326031651681648059c7e3fc983a04753
Naeel90/les2
/les5/__init__.py
192
3.5625
4
def convert(C ): F=C*1.8+32 return F def tabel(): print('{0:10}{1:9}'.format('F','C')) for i in range(-30,50,10): print('{:} '.format(convert(i)),(i)) tabel()
a04cc4d6808ebd8f956094692ceb3ba4cd280b7c
JyHu/PYStudy
/source/sublime/base/py02.py
845
4.09375
4
#coding:utf-8 #auther:jyhu # list tuple # # List # classmates = ['Michael', 'Bob', 'Tracy'] print(classmates) print(len(classmates)) for i in classmates: print('My name is %s ;' % i) for i in range(len(classmates)): print('NO. %d name is %s' % (i, classmates[i])) print(classmates[0]) print(classmates[-2]) ...
f0d2d51f2721a672e44770dcf116dac96428dc94
Sree-vathsan/leetcode
/CheckIfItIsAStraightLine.py
1,190
3.765625
4
""" You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,...
0b33e7c2a0ed9b0e3dfe8d35f82f52aea07dc9b9
gaolichuang/book-algorithm-datastruct
/solution/dynamicprogram/scrambelstring.py
1,740
3.640625
4
''' Scramble String My Submissions Question Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a ...
5c76512702d032ff57060d9eec6c3b3ade15483f
gandresr/Numerical-Analysis
/Optimizacion.py
4,667
3.515625
4
# -*- coding: utf-8 -*- #Metodo para evaluar la funcion en un punto x #Recibe como parametros W0, L, E, I (Si no se ingresan se toman valores predeterminados) def f(x,W0=5400., L=700., E=20000., I = 1500.): return W0/(120*E*I*L)*(-(x**5)+2*(L**2)*(x**3)-(L**4)*x) #Metodo para evaluar la primera deri...
7a54aba27fc99a76788ecec08c7c92f5f9036463
lime2002/Test
/keskiarvo.py
225
3.796875
4
val1 = int(input('anna 1.luku\n')) val2 = int(input('anna 2.luku\n')) val3 = int(input('anna 3.luku\n')) sum = val1 + val2 +val3 avg = sum / 3 print("lukujen",val1,',',val2, "ja",val3, "keskiarvo on","{:.2f}".format(sum))
a05587b110c62223bd2bf54b4f1152761605bb79
hyunjun/practice
/Problems/hacker_rank/Algorithm/Arrays_and_Sorting/20141231_QuickSort_In_Place/solution2_1.py
814
3.734375
4
def print_ar(ar): print " ".join([str(a) for a in ar]) def partition(ar, l, r): pivot_item = ar[l] left = l right = r while left < right: while ar[left] <= pivot_item: left += 1 while ar[right] > pivot_item: right -= 1 if left < right: ar[left], ar[right] = ar[right], ar[left] ...
23b7fd3bb1209db3e8ad0e2cec91807a401ce6ce
agerista/code-challenge-practice
/pramp/shortest_substring.py
1,041
4.0625
4
def smallest_substring(arr, s): """ >>> smallest_substring(['x','y','z'], 'xyyzyzyx') 'zyx' >>> smallest_substring(['a','c','e'], 'cceccaeceeacc') 'cae' >>> smallest_substring(['a','x','e'], 'cceccaeceeacc') '' """ head = 0 tail = len(arr) shortest = '' while head <= ...
c48dcf77225c49cad5ea676fe0f64e54a928beda
yoshiaki-ki/python-basic-lesson
/network/create_json.py
439
3.515625
4
import json j = { "employee": [ {"id":111, "name":"Mike"}, {"id":222, "name":"Nancy"}, ] } print(j) print("#########") print(json.dumps(j)) # jsonは必ずダブルクオート(”)で値を囲むこと # jsonファイルへの書き込み with open('test.json', 'w') as f: json.dump(j,f) # jsonファイルの読み込み with open('test.js...
4bf20bfc152b1594f2d3d3fe2eb30d0c47e80087
Adlaneb10/Python
/Class_notes/classs.py
531
3.953125
4
class Student(object): """Simple student class""" def __init__(self, first="", last="", id=0, grade=0): # initializer self.first_name_str = first self.last_name_str = last self.id_int = id self.grade = grade def __str__(self): return "{} {}, ID: {}".format(se...
0667b4cbc247db7221a8887e217b4eb89e34757a
rentheroot/Learning-Pygame
/Following-Car-Game-Tutorial/Adding-Images.py
1,237
4.21875
4
#learning to use pygame #following this tutorial: https://pythonprogramming.net/displaying-images-pygame/?completed=/pygame-python-3-part-1-intro/ #imports import pygame #start pygame pygame.init() #store width and height vars display_width = 800 display_height = 600 #init display gameDisplay = pygame.display.set_m...
7a28eb4876999c9babd1399a6e4661879cbd2bd2
yujieyen/ryPat2021_code
/Python-Data-Analysis-Third-Edition-master/Chapter04/.ipynb_checkpoints/ch4_ry-checkpoint.py
7,240
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Import required libraries NumPy, polynomial and matplotlib import numpy as np import matplotlib.pyplot as plt # Generate two random vectors v1=np.random.rand(10) v2=np.random.rand(10) # Creates a sequence of equally separated values sequence = np.linspace(v1.min(),v...