blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d24b165d83989787fc1516850c3f3418a24142b9
RafaelHuang87/Leet-Code-Practice
/25.py
925
3.609375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head or not k: return None value = [] result_temp = [] temp ...
2b221d3e6dbe190a80f59b77d02c36d8bfb4a0fd
RafaelHuang87/Leet-Code-Practice
/35.py
549
3.96875
4
class Solution: def searchInsert(self, nums: [int], target: int) -> int: if not nums or target <= nums[0]: return 0 if target > nums[-1]: return len(nums) start, end = 0, len(nums) - 1 while start < end: mid = (start + end) // 2 if nu...
3abc6d0986de7b15e284ac400318fdfae44a3a60
RafaelHuang87/Leet-Code-Practice
/148.py
961
3.84375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head slow, fast = head, head.next while fast and fas...
7a95cdb909f1810ccea3796d440e63c219ed97fa
RafaelHuang87/Leet-Code-Practice
/290.py
469
3.625
4
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: str_list = str.split() if len(str_list) != len(pattern) or len(set(str_list)) != len(set(pattern)): return False d = {} for i in range(len(pattern)): if pattern[i] not in d: ...
eb3fa1ea563202becab214ba64ed4b6cc318c28a
RafaelHuang87/Leet-Code-Practice
/36.py
1,021
3.671875
4
class Solution: def isValidSudoku(self, board: [[str]]) -> bool: row = [[False]*9 for _ in range(9)] column = [[False]*9 for _ in range(9)] matrix = [[False]*9 for _ in range(9)] for i in range(len(board)): for j in range(len(board[0])): if board[i][j] != ...
ec81ff70fe299cdc80f013479c128b8d1f152a7a
RafaelHuang87/Leet-Code-Practice
/130.py
829
3.5625
4
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ r = len(board) if not r: return c = len(board[0]) def bfs(board, i, j): if 0 <= i < r and 0 <= j < c and bo...
0eac896f64f3a6110066f3260d6bb868ab2524ce
RafaelHuang87/Leet-Code-Practice
/20.py
382
3.84375
4
class Solution: def isValid(self, s: str) -> bool: left = {'{': '}', '[': ']', '(': ')'} stack = [] for i in s: if i in left.keys(): stack.append(i) else: if not stack or left[stack.pop()] != i: return False ...
8058ca28d8ca65acff434a59265e69cee0f101c0
bugi/codeeval
/moderate/2/soln.py2
1,255
3.578125
4
#!/usr/bin/python2 # https://www.codeeval.com/open_challenges/2/ import sys def doit(fi): n_lines = None lines = [] for line_raw in fi: if line_raw == '\n': continue line = line_raw.strip() if n_lines is None: n_lines = int( line ) continue lines.a...
fadf020fa79c54e51edc74da68db6848813be022
bugi/codeeval
/easy/3/palprime.py2
699
3.96875
4
#!/usr/bin/python2 # https://en.wikipedia.org/wiki/Palindromic_prime # https://www.codeeval.com/open_challenges/3/ def isprime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False # reject even numbers for x in range(3, int( n ** 0.5 )+1, 2): if n % x == 0: return Fal...
5476cac49379e011d4ca78226e1e80c3f3c85b79
bugi/codeeval
/easy/18/soln.py2
507
3.90625
4
#!/usr/bin/python2 import sys def is_power_of_2(x): if not x > 0: return False return not ( x & (x-1) ) def doit(line_raw): line = line_raw.strip() a = line.split(',') x = int(a[0]) n = int(a[1]) if not is_power_of_2(n) : return y = n while y < x: y += n print y if _...
bf43ed7f7bcfc8d06dfe854b66be17d650f2bbad
dapotter/Fire-weather
/FWP_Blog/app.py
3,177
3.6875
4
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:test123@localhost/flaskmovie' #'sqlite:////tmp/test.db' db = SQLAlchemy(app) # -------------------------------------------...
524e939c2e9c6a37110852f64810a043ec1836a4
cookiepringle7/cssi
/week3/Notes/addlasswork.py
152
3.515625
4
def add(x=5, y=6): return x=y print(add(12,13)) print(add()) print(add(15)) #Note: Default values must not have standard parameters trailing them
dcd9c339115266ebe34e768ae932619e2c18575d
mredul-NSL/nsl_exam_resources
/Exam_Codes_stage_1/D2_recursion.py
435
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 25 12:18:29 2021 @author: Mredul """ import os def visit_directory(base_path): try: folders = os.listdir(str(base_path)) except: pass for folder in folders: print(folder) files = visit_directory(base_pa...
6814d483932c63d8d9f184a38927b51ba412e0e8
LeslieK/PyScheme
/modularity.py
5,785
4.28125
4
""" using streams to modularize a program without storing state each stream value represents a state successive values represents values over time streams allow you to go back in time; i.e. roll back state! Ex. 3.81, 3.82 """ from pairs import integers_starting_from, integers from iterStreams import stream_map, stream...
2c3ddf1423554ac348ee69a5d3e86c0b1b280d93
BenediktSexyMan/Vef2
/Verk2/Book.py
750
3.640625
4
class Book: def __init__(self, id, title="Undefined Title", description="Undefined Description", author="Undefined Author"): self.__title = title self.__description = description self.__author = author self.__ID = id @property def ID(self): return self.__ID @pro...
28034ee53bbfe0d075c722284a29b776b5871f72
Yosri-ctrl/holbertonschool-interview
/0x16-rotate_2d_matrix/0-rotate_2d_matrix.py
269
3.734375
4
#!/usr/bin/python3 """ rotate 2d matrix 90 degre """ def rotate_2d_matrix(matrix): """ rotate 2d matrix """ copy = matrix.copy() for col in range(len(matrix[0])): tmp = [] for row in reversed(copy): tmp.append(row[col]) matrix[col] = tmp
ce8304d2c716b371f9ebddd1cecd76440abbd2a7
hollisneel/KnotModels
/computations/misc/file_to_dict.py
739
3.734375
4
# open the file # -> read all (type is a string) # ---> put the string into stringToDict def file_to_dict(filename): z = open(filename) Str = z.read() if Str[0] == "{": Str[0] = "" if Str[len(Str)-1] == "}": Str[len(Str)-1] == "" str = Str.replace("}","") Colon_Comma = [-1] Dict = {} z.close() for a in ...
1f524ae1932e4373c72d6860a66d127afe9844c1
svangordon/latrones
/util/game_logic.py
10,110
3.609375
4
from string import ascii_lowercase from fen import serialize_fen_string, deserialize_fen_string def convert_alg_to_point(game): def curried(coord): col = int(ascii_lowercase.find(coord[0])) + 1 # dummy col row = int(coord[1:]) if not 0 < col <= game["board_width"]: raise ValueEr...
a8060b02173dcd29f6bed51fc48e3bfca3ab9577
credwards27/cse491-numberz
/sieve_mod/sieve.py
795
4.0625
4
# implementation of the sieve of eratosthenes as a module # list of all found prime numbers _primeslist = [2] # check if a number is prime # iterate through all numbers in primes list # modulo divide the current possible prime by all numbers in the primes list def _is_prime(primes, n): for i in primes: if...
0479d9954fb902d745c3bf7ecd6e5ac8cabaca78
SamTheWarlock/PasswordSystem
/passsys.py
4,314
4.03125
4
def redoAO(): print("Perform an action:") print("1. Change a password.") print("2. Delete an account") print("3. Log Out") inp = input("What would you like to do? Enter a number: ") if inp == "1": changeacc = input("Which account would you like to modify the password on?: ") if c...
d362dea5755de457a5b8c6ebdfdcfc113510a2bb
brennobrenno/udemy-python-masterclass
/Section 7 & 8/47.py
1,140
3.796875
4
# decimals = range(0, 100) # my_range = decimals[3:40:3] # print(my_range == range(3, 40, 3)) # # print(range(0, 5, 2) == range(0, 6, 2)) # Numbers are different but sequence of values is the same... aka: end result # print(list(range(0, 5, 2))) # print(list(range(0, 6, 2))) # # r = range(0, 100) # print(r) # # for i ...
9415130a67174709590995958955ffea055343e0
brennobrenno/udemy-python-masterclass
/Section 13/checkdb.py
365
4.09375
4
import sqlite3 conn = sqlite3.connect('contacts.sqlite') name = input("Please enter a name: ") # LIKE below is for upper and lowercase for row in conn.execute("SELECT * FROM contacts WHERE name LIKE ?", (name,)): # Tuple containing a single value... print(row) ...
a09e6de32320dca2795f35f7218ec5bd4d4f85bb
brennobrenno/udemy-python-masterclass
/Section 11/spam.py
1,525
4.15625
4
def spam1(): def spam2(): def spam3(): z = " even" z += y print("In spam3, locals are {}".format(locals())) return z y = " more " + x # y must exist before spam3() is called y += spam3() # do not combine these assignments ...
1f6689ff4d8990151ca329843ec12486157182b3
brennobrenno/udemy-python-masterclass
/Section 7 & 8/43.py
863
4.21875
4
# list_1 = [] # list_2 = list() # # print("List 1: {}".format(list_1)) # print("List 2: {}".format(list_2)) # # if list_1 == list_2: # print("The lists are equal") # # print(list("The lists are equal")) # even = [2, 4, 6, 8] # another_even = even # # another_even = list(even) # New list # another_even2 = sorted(...
fe0c54eeade29457cfa21e1e0558c2e18cd9e444
eqtrqq4fg/githaein
/section02-1.py
682
3.65625
4
#section02-1 #파이썬 기초 코딩 #print 구문의 이해 print("hello python") print('''hello''') #separator 옵션 사용 print("T","E","S","T",sep="") print('niceman','google.com',sep='@') #end 옵션 사용 print('welcome to',end='\n') print('the black paradise',end='\n') #format 사용 print('{0} and {1}'.format('You','Me')) #format말고 c언어처럼 print("%...
b5e8ed2fa2164a839b3d771e390a9c9452e4e947
wsklxts/python-django
/demo/test.py
594
3.578125
4
import types class Student: def __init__(self,age,name): self.age=age self.__name=name def learn(self): print( self.age) s = Student(12,"六六"); class Student2(Student): def __init__(self, name, gender): super().__init__(name, gender) self.name = name sel...
75e0df36cec9007a7b0b500855cacb0980b1ecee
BrunoVirgu/LProg2017.2
/LAB_PROG/src/mochila.py
1,425
3.625
4
def distancia(s1, s2): if len(s1) < len(s2): return distancia(s2, s1) if len(s2) == 0: return len(s1) anterior = range(len(s2) + 1)#o anterior é o tamanho da menor string for i, k in enumerate(s1):#for citando e enumerando atual = [i + 1] for j, l in enumerate...
a6df17c793d8e38a5422dfdef37f7b2148d1bdb2
BrunoVirgu/LProg2017.2
/LAB_PROG/src/op.py
2,775
3.640625
4
class Times(): def __init__(self,numero): self.__numero = numero self.__ouro = 0 self.__prata = 0 self.__bronze = 0 self.__total = 0 def getNumero(self): return self.__numero def getouro(self): return self.__ouro def setouro(...
3ee3605090711baedbf86f331e793ca3f94ca2f7
LiraNeto/APA
/APA.py
1,054
3.84375
4
def insertionSort(v): i = 1 j = 0 n = len(v) atual = 0 while i < n: atual = v[i] j = i - 1 while (j >= 0) & (atual < v[j]): v[j+1] = v[j] j = j -1 v[j+1] = atual i = i + 1 def selectionSort (v): i = 0 j = 0 n = len(v) iMin = 0 for j in xran...
5f9bebe247ca79ed4a1d0a2aae3f9d335fcc823a
cdunn6754/LeetCode
/Python3/206_Reverse_Linked_List/reverse_list_iter_3.py
793
3.9375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = n_node = None curr = head ...
09b5cb98b2326179cdefa23b6a3845559fddbe59
cdunn6754/LeetCode
/Python3/109_convert_sorted_list_to_bst/convert.py
967
3.96875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedListToBST(...
bc52bb0c6e5acaea87a181d2e14002632a40da23
cdunn6754/LeetCode
/Python3/Remove_Nth_Node_19/remove_nth_node.py
991
3.859375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ d = False (_, d) = se...
e21ecef3217a6cafe21fc04e363c3915d65ba3df
cdunn6754/LeetCode
/Python3/695_MaxAreaIsland/MaxAreaIsland_2.py
2,002
3.546875
4
class Solution: def is_water(self, p): if ( p[1] > self.max_j or p[0] > self.max_i or p[0] < 0 or p[1] < 0 or self.grid[p[0]][p[1]] == 0 ): return True return False def add_to_island(self, p, island): if se...
c32c6345d9b1a70bdc7808b55c0e3360480c1b0f
cdunn6754/LeetCode
/Python3/11_Container_w_most_water/most_water.py
742
3.546875
4
import unittest class Solution: def maxArea(self, height: 'List[int]') -> 'int': lower = 0 upper = len(height) -1 max_area = 0 while lower < upper: curr_area = min(height[lower], height[upper])*(upper-lower) max_area = curr_area if curr_area > max_area else m...
120f9bc356f3c6802447fdbdb53782b2bf32388f
cdunn6754/LeetCode
/Python3/Maximum_Subarray_53/maximum_subarray_2.py
405
3.578125
4
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ max_sum = nums[0] c_sum = nums[0] for num in nums[1:]: if c_sum + num > c_sum: c_sum += num else: c_sum = num ...
2b38dd62c58b4f18c1b90069dbaf17ad9769d0eb
prettyquail/Python
/NAD/MY-master/Root Finding Techniques/Regula_falsi_method/RegularFalsy.py
552
3.78125
4
import math def f(x): return x*x - x -1 def RegularFalsy(a,b): if (f(a) * f(b) >= 0.0): print("Invalid Interval\n") return m=(a*f(b)-b*f(a))/(f(b)-f(a)) while (abs(f(m))>= 0.01): m=(a*f(b)-b*f(a))/(f(b)-f(a)) if(f(m)...
90fd201fc9652ac1148367c083860c1db92b351a
prettyquail/Python
/Intersection and Union of Sets.py
441
3.515625
4
>>> odds=set([1,3,5,7,9]) >>> evens=set([2,4,6,8,10]) >>> primes=set([2,3,5,7]) >>> composites=set([4,6,8,9,10]) >>> odds.union(evens) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} >>> evens.union(odds) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} >>> odds {1, 3, 5, 7, 9} >>> evens {2, 4, 6, 8, 10} >>> odds.intersection(primes) {3, 5, 7} >>> pri...
2b18d39c07ac818fd58be4e2071c444f5c0a3b2c
peony11/nlp100_python
/chapter_1/04.py
833
3.5
4
#coding:utf-8 """ 04. 元素記号 "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ. """ sentence = "Hi He Lied Because Boron Co...
60d4bafeb2be3629414ee423426342213c8a8a7a
peony11/nlp100_python
/chapter_2/19.py
736
3.71875
4
#coding: utf-8 """ 19. 各行の1コラム目の文字列の出現頻度を求め,出現頻度の高い順に並べる 各行の1列目の文字列の出現頻度を求め,その高い順に並べて表示せよ.確認にはcut, uniq, sortコマンドを用いよ. """ #Usage: python 19.py filename import sys def first_row_list(file): return [line.split('\t')[0] for line in file] def count_frequency(li): s = set(li) d = {x:0 for x in s} for text in li: ...
92e77b1dda1e4a4d5915c27c6d5caf9daef358be
peony11/nlp100_python
/chapter_1/06.py
1,199
3.609375
4
#coding: utf-8 """ 06. 集合 "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ. """ def ngram(seq, n, unit="word"): """ Input: seq(str), n(int), unit("word" or "unit") Output: set of tuples """ res = set() if unit == "word": ...
7a4c6e46d471dee68f06f28956a964fd56559912
wesbasinger/LPTHW
/ex22/interactive.py
1,213
4.15625
4
print "Let's just take a little quiz." print "On this section, you were supposed to just review." points = 0 def print_score(): print "So far you have %d points." % points print_score() print ''' Here's your first question. Which of the following objects have we talked about so far? a Strings b Integers b Functio...
edaff19fc7b3ea2a8ab87e1ab10ad6c029009841
wesbasinger/LPTHW
/ex06/practice.py
739
4.34375
4
# I'll focus mostly on string concatenation. # Honestly, I've never used the varied types of # string formatting, although I'm sure they're useful. # Make the console print the first line of Row, Row, Row Your Boat # Do not make any new strings, only use concatenation first_part = second_part = # should print 'Ro...
7c1a2e06f256b96051695a1ea717589add18d754
wesbasinger/LPTHW
/ex34/practice.py
375
3.890625
4
# Make a list with 5 elements that has "apple" in the 3rd index five_elements = # Make a list with 4 elements that has "beginning index" at the 0st index. four_elements = # Access the song "Thriller" from the following list and assign # it to the variable number_one_hit. eighties_hits = ["Jump", "Thriller", "Can...
ded9c7690be355bbc90d7194b47fc59fb445ac0e
wesbasinger/LPTHW
/ex17/practice.py
434
4.0625
4
# In this practice, you'll do exactly what was in the # exercise reading and in the interactive practice - # copy one file to another. # You'll be moving text from 'alpha.txt' to 'bravo.txt' # 'alpha.txt' has text and 'bravo.txt' is empty # First, open 'alpha.txt' in read mode alpha = # Second open 'bravo.txt' in ...
cf4a99e1a7c7562f04bb9d68cc91673f7d108309
wesbasinger/LPTHW
/ex21/interactive.py
1,924
4.28125
4
from sys import exit def multiply_by_two(number): return number * 2 def subtract_by_10(number): return number - 10 def compare_a_greater_than_b(first_num, second_num): return first_num > second_num print "So far, you've done only printing with function." print "Actually, most of the time you will want your" pri...
50f7a379886e1b687eafe0ae37ff11c2461ec95b
wesbasinger/LPTHW
/ex40/interactive.py
2,919
4.40625
4
from sys import exit print "This is point where things take a turn." print "You can write some really great scripts and" print "do awesome stuff, you've learned just about" print "every major data type and most common pieces" print "of syntax." print "But, if you want to be a real programmer," print "and write applica...
21ba2df77be36f961c9bbdeb3c589d64e1546340
LorandMezei/MathSolver_LorandMezei
/Tokenizer.py
631
3.703125
4
import re class Tokenizer(): @staticmethod def tokenize_math_exp(exp): """ Return an array of strings that contains the tokens of the mathematical expression. Parameters: exp - A string containing a fully-parenthesized mathematical expression. """ # https://...
5112d756ce5912b84c79a52ba6ae7a0fd44f8722
rozoza/uob_fp
/AScounter.py
246
3.671875
4
import csv with open('./ASMO/AS.csv') as file: reader = csv.DictReader(file) count = 0 case = 0 for row in reader: if case != int(row['case']): case = int(row['case']) count += 1 print(count)
184eea920e6f8825ec2fcd9fc61769c27b61d4c8
Rishu97/Google_Drive_Backup
/upload.py
469
3.578125
4
'''this function is called when a new file needs to be uploaded ''' def upload_file(name , mime ,dir_path,fid) : from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() drive = GoogleDrive(gauth) gauth.LocalWebserverAuth() print name, ':',mime f = drive.CreateFile({'...
8603747f172b19d2f515524378ea5c9e36edb2bd
AmenehForouz/leetcode-1
/python/problem-1450.py
1,125
3.671875
4
""" Problem 1450 - Number of Students Doing Homework at a Given Time Given two integer arrays startTime and endTime and given an integer queryTime. The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time qu...
64bd98e9099267c2b5239a12c68a1c0108f4d92a
AmenehForouz/leetcode-1
/python/problem-0832.py
1,144
4.34375
4
""" Problem 832 - Flipping an Image Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image mea...
eae5fcb82c8d1ef088f2bbe0bf48edd95448311b
AmenehForouz/leetcode-1
/python/problem-0657.py
866
3.8125
4
""" Problem 657 - Robot Return to Origin There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. """ class Solution: def judgeCircle(self, moves: str) -> bool: leftRightCount = 0 u...
618a61967434f32cc88180b0ddd3a22da92ba813
AmenehForouz/leetcode-1
/python/problem-0905.py
679
4.0625
4
""" Problem 905 - Sort Array by Parity Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. """ from typing import List class Solution: def sortArrayByParity(se...
e05effda1a8d6caa356f4dfa9400148fd62e1ed1
AmenehForouz/leetcode-1
/python/problem-1281.py
613
3.8125
4
""" Problem 1281 - Subtract the Product and Sum of Digits of an Integer Given an integer number n, return the difference between the product of its digits and the sum of its digits. """ class Solution: def subtractProductAndSum(self, n: int) -> int: sumOfDigits = 0 prodOfDigits = 1 for ...
9f489fa5b55db295368c9ea6ff621fe59f2e37e9
AmenehForouz/leetcode-1
/python/problem-0088.py
625
4.15625
4
""" Problem 88 - Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. """ from typing import List class Solution: def merge( self, nums1: List[int], m: int, nums2: List[int], n: int ) -> None: """ Do not return anything, mod...
e42f00289210a5302d49303a171a085af7b8c909
mpnerd/ch03
/input_multiply.py
154
3.609375
4
a = int(input("첫 번재 수를 입력하세요. : ")) b = int(input("첫 번재 수를 입력하세요. : ")) c = a*b print(a, " * ", b, " = " ,c ,"\n")
2315e0c5f7b08cb87aab56f835a7122e096e5a80
priyankabhalode/Test
/Hungry.py
316
4.15625
4
hungry = input("Are u hungry?") if hungry == "yes": print("eat samosa") print("eat pizza") print("eat burger") print("eat fries") else: #print("Do your home work") thirsty = input("Are u thirsty?") if thirsty == "yes": print("drink water") print("drink soda or coldrink")
35db78d46c40b952775dbd462a92ae28eacc8a81
candaceyw/hashtable_python
/hashtable.py
2,581
3.84375
4
class HashTable(object): def __init__(self, size): # Set up size and slots and data self.size = size self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): # Note, we'll only use integer keys for ease of use with the Hash Function ...
32f5d322d3f4aca536f04dcc1980d772043180cd
nathanielam0ah/homework
/exercise006.py
172
3.71875
4
#!/usr/bin/env python def infinitAdd( *the_number ): sum = 0 for x in the_number: sum = sum + x print(sum) return sum infinitAdd(1, 2, 4, 5, 100)
b55bfbc8b3ded9fb3f4a9f40970a3230bf0453e8
nathanielam0ah/homework
/squares.py
192
3.890625
4
#!/usr/bin/env python3 def sqr(the_number): init = [1, 2 , 3, 4 , 5, 6, 7, 8, 9, 10,] init_two = [] for x in init: init_two.append( sqr(x) ) return the_number * the_number print(init_two)
dbd36cd07e0788e737aead8ec49d723728a9abff
nathanielam0ah/homework
/cel_to_fahr.py
164
4.09375
4
#!/usr/bin/env python def celsius_to_fahrenheit(celsius): fahr = celsius * 1.8 + 32.0 print(fahr) celsius_to_fahrenheit(float(input("enter a number: ")))
1d79a965da3406b42c492b8a9aa2bfd6ae4c1bba
nathanielam0ah/homework
/exercise009.py
230
4.21875
4
#!/usr/bin/env python def maxList(Li): currentMax = Li[0] for index in Li: if index > currentMax: currentMax = index return currentMax myList = ['3', '4', '6', '3', '-100'] print(maxList(myList))
88edab16bb455244933c04d86e456b5ecf399ca5
nathanielam0ah/homework
/python3sql/mysql_where.py
619
3.703125
4
#!/usr/bin/env python3 from mysql_module01 import mydb, mycursor #select with filter sql = "SELECT * FROM customers WHERE address = 'Valley 345'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult: print(x) print("\n") #wildcard characters sql = "SELECT * FROM customers WHERE address LIKE '%...
5321a95b12e589e9b03d063a8d214db0294e7669
vostrikov-ov/Geekbrains_01
/Lesson_7/task_1.py
810
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. Примечание: Списки фруктов создайте вручную в начале файла. ''' citrus_fruits = [ 'Апельсин', 'Лайм', 'Нони', 'Гуава', 'Помело' ] exotic_fruits = [ 'Эшта', 'Гуанаба...
ca32a24c0af0ef991b2c0de86116755a3f3fe0a4
CaptainDaVinci/Code-Sleep-Python
/website_status_check/website_status_check.py
1,103
4.0625
4
import urllib2 #importing library urllib2 (which user might need to install before running the script) import socket #importing socket def check_url( url, timeout=10 ): #creating function to keep code orginized if urllib2.urlopen(url,timeout=timeout).getcode() == 200: #this is checking if the return request of ...
030622a70d0b52144a0b3e604fd7105e97511e0a
dishit2141/Internship-Work
/day3(basic programme)/smallestno.py
246
4.15625
4
no1=int(input("Enter Number 1:")) no2=int(input("Enter Number 2:")) no3=int(input("Enter Number 3:")) if(no1<no2 and no1<no3): print(no1,"is Smallest") elif(no2<no1 and no2<no3): print(no2,"is Smallest") else: print(no3,"is Smallest")
8a231812f7825094efcabe16f699e3281fd5c97d
dishit2141/Internship-Work
/day 2(crud operation in python)/Advance task/crud.py
2,384
3.71875
4
import mysql.connector mysqldb=mysql.connector.connect(host="localhost",user="dp",password="1234",database="employee")#established connection between your database mycursor=mysqldb.cursor()#cursor() method create a cursor object print("\t\t\tEmployee Data Store") print("1. INSERT RECORD") print("2. DISPLAY RE...
bced3c661c5bc7de218fc791fab86f25629ee659
dishit2141/Internship-Work
/day3(basic programme)/leapornot.py
144
4.1875
4
no=int(input("Enter Year to check it's leap or not:")) if(no%4==0): print(no,"is a leap year") else: print(no,"is not a leap year")
b5222fbcfd14219b4ed00df4e8ebec898fe751c1
anilgursahani/bitesofpy
/83/timezone.py
1,124
3.65625
4
from pytz import timezone, utc from datetime import datetime as datetime import pytz AUSTRALIA = timezone('Australia/Sydney') SPAIN = timezone('Europe/Madrid') CHICAGO = timezone('US/Central') NY = timezone('US/Eastern') UTC = timezone('UTC') def what_time_lives_pybites(naive_utc_dt): """Receives a naive UTC d...
143b9f74c94bbc7baca517e71b1ba6adee1769b7
anilgursahani/bitesofpy
/107/save2_passed.py
297
3.921875
4
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and filters out numbers that are both positive and even (divisible by 2), try to use a list comprehension""" evens = [num for num in numbers if num > 0 and num%2 == 0] return evens pass
3763a3384ba6e73f62f15bbd42cff47a5e42bbc8
Done4/Second-hand
/app/tools/helper.py
594
3.734375
4
def is_isbn_or_key(word): ''' 判断q是ISBN还是关键字 isbn13 13个0-9数字组成 isbn10 10个0-9数字组成 含有‘-’ :param q: :return : ''' if len(word) == 13 and word.isdigit(): return 'isbn' if '-' in word and len(word.replace('-', '')) == 10: # isbn10 return 'isbn' return 'keyword' ...
da6106e6aa5268cc241d03472d3ff572f0a63e58
ucsd-cse-spis-2020/spis20-lab03-Sidharth-Theodore
/lab3Letters_pair.py
596
4.5625
5
#Sidharth and Theodore #1.the "anonymous turtle" is the default turtle used if none are created in Code, or the first created if multiple are created #2."turtle" refers to the turtle library while "Turtle()" refers to the turtle class #3.myTurtle.sety(100) import turtle def drawT(theTurtle, size): '''Takes a turtl...
36e105a4cf6480988854ee0c755d83cdcfdeb160
christyaliner111/SIL_DS_Home_Assignment
/create_sql_database.py
792
4.0625
4
import sqlite3 import csv conn = sqlite3.connect('languages.sqlite') cur = conn.cursor() cur.execute('DROP TABLE IF EXISTS languages') cur.execute(''' CREATE TABLE "languages"( "ID" TEXT, "title" TEXT, "subject_lang" TEXT, "year" INTEGER ) ''') fname =input('Enter the languages csv fi...
0c399de5188adb0418cef31a5896a2376afdf4bb
linzifan/python_courses
/misc-Stack.py
1,487
4.40625
4
""" Stack class """ class Stack: """ A simple implementation of a FILO stack. """ def __init__(self): """ Initialize the stack. """ self._items = [] def __len__(self): """ Return number of items in the stack. """ return len(self._it...
f25745af3bab932ad72bea2b9878e14aaa1afc78
linzifan/python_courses
/IPP-Project-3-Stopwatch.py
1,696
3.5
4
# template for "Stopwatch: The Game" import time import simplegui # define global variables global current, game, win current = 0 game = 0 win = 0 # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): return str((t//600))+':'+str((t%600)//100)+str(...
e0dc7ed36f1e2d6775efb41a3471678a0c0f512f
TheYisusPls/Clase_8
/Suma de una lista.py
266
3.765625
4
lista = [] condicion = () fin = "fin" while condicion != fin: condicion = input("Dime numeros al azar: ") if condicion == fin: break lista.append(int(condicion)) print(lista) suma = 0 for numero in lista: suma = suma + numero print(suma)
02e3c2e69361a97c7b18560a54588023a891bb23
divyaswormakai/codingProblems
/Done/12.py
529
4
4
step=input("Enter the number of steps::") arr12=[] arr135=[] steps1=0 steps2=0 for i in range(0,int(step)): if(i==0): arr12.append(1) elif(i==1): arr12.append(2) else: arr12.append(arr12[i-1]+arr12[i-2]) steps1 =arr12[i] for i in range(0,int(step)): if(i==0): arr135.append(1) elif(i==1 or i==2): arr1...
9f5d7dd93d70cdd760345a8fcf5fa376384e3e5a
divyaswormakai/codingProblems
/49.py
438
3.890625
4
# Given an array of numbers, find the maximum sum of any contiguous subarray of the array. # For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, # since we would take elements 42, 14, -5, and 86. # Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take...
1a04369c248521ef73e21dcd7e58351dc32133d3
divyaswormakai/codingProblems
/Done/31.py
704
4.09375
4
# The edit distance between two strings refers to the minimum number of character insertions, deletions, # and substitutions required to change one string to the other. For example, the edit distance between “kitten” # and “sitting” is three: substitute the “k” for “s”, substitute the “e” for “i”, and append a “g”. ...
514fe109710e644314731ae105fb383386ed1edf
ScSteffen/neuralEntropyComparison
/ext/steffensCode/ext/sphericalquadpy/tools/rotations.py
2,324
4.0625
4
"""Rotating cartesian points that live on the unit sphere around a random or specified axis by a random or specified amount""" from numpy.random import rand, randn from numpy import zeros, cos, sin, pi, multiply, matmul from numpy.linalg import norm # pylint: disable=C0103 def rotate(axis, angle, xyz): """Rotat...
9c01efe02ee7eaa0f4184b021909935c12437659
ScSteffen/neuralEntropyComparison
/ext/steffensCode/ext/sphericalquadpy/ldfeLinDisc/vistools.py
692
3.546875
4
import matplotlib.pyplot as plt def scatterplot(points, weights, square=1): x = points[:, 0] z = points[:, 2] area = 1e7 * weights**2 plt.close("all") cm = plt.cm.get_cmap('Dark2') plt.subplot(1, 2, 1) plt.scatter(x, z, s=area, c=square, alpha=0.99, cmap=cm) plt.title("quadrature poin...
c04ea70bb6197efed6af6c7ec9dea8d8a8a1ab5a
Edinburgh-Genome-Foundry/Flametree
/flametree/ZipFileManager.py
6,013
3.5
4
import os import sys import zipfile import re from collections import defaultdict PYTHON3 = sys.version_info[0] == 3 if PYTHON3: from io import StringIO, BytesIO StringBytesIO = BytesIO else: from StringIO import StringIO BytesIO = StringIO StringBytesIO = StringIO EMPTY_ZIP_BYTES = b"PK\x05\x...
754311c45d020d8c6254fe0271b4cd0e97d49a79
EvgeniyPrudnikov/pyprojects
/hackerrank/lol2.py
593
3.53125
4
# https://www.hackerrank.com/challenges/nested-list/problem l = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41.0], ['Harsh', 39.0]] print(l) mn = min(map(lambda x: x[1], l)) mx = max(map(lambda x: x[1], l)) names = [] if mn == mx: for i in sorted(l, key=lambda x: x[0]): print(i[0]) ...
29666a7cca7293ec52aafd28600135debdc494a9
fducha/python
/stepic/Python/step2-14.py
400
3.65625
4
matrix = [] row = input() while row != 'end': matrix += [[int(i) for i in row.split()]] row = input() for row in range(len(matrix)): for col in range(len(matrix[row])): print(matrix[row - 1][col] + matrix[(row + 1) % len(matrix)][col] + matrix[row][col - 1] + ...
867ebc17698f50bf238ed6055f9709de28b4c0de
fducha/python
/stepic/Python/step2-8.py
178
3.5625
4
nums = [int(i) for i in input().split()] if len(nums) == 1: print(*nums) else: for i in range(len(nums)): print(nums[i - 1] + nums[(i + 1) % len(nums)], end=' ')
0fca4483920c9e97eecc3177a82b9e661e64a038
fducha/python
/stepic/Python_Base/step21.py
270
3.640625
4
s, a, b = input(), input(), input() if a in s and a in b: print('Impossible') else: replace_count = 0 repl_s = s.replace(a, b) while s != repl_s: replace_count += 1 s = repl_s[:] repl_s = s.replace(a, b) print(replace_count)
b9b18786e75bd7d2964a37d08c1ded941b636fb9
fducha/python
/stepic/Algorhythms/alg_lib.py
670
3.796875
4
def fib(n): """Вычисляет n-e число Фибоначи""" if n == 0: return 0 a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b def fib_mod(n, m): """ Вычисляет останок от деления n-го числа Фибоначи на m Для вычислений используется метод поиска периода Пизано ""...
a131a6b53256a69f648026c96eae8afe6f88d72f
fducha/python
/stepic/Python_Base/step22.py
166
3.65625
4
string, template = input(), input() count = 0 pos = string.find(template, 0) while pos != -1: count += 1 pos = string.find(template, pos + 1) print(count)
7504e360f71b643a86497dc303badef47b46eb5b
fducha/python
/stepic/Python/step2-12.py
205
3.578125
4
count = int(input()) num = 1 while count >= 0: if count - num < 0: print((str(num) + ' ') * count, end='') else: print((str(num) + ' ') * num, end='') count -= num num += 1
42b575ab2e4ac5b39e5e1b1a2630479b396340dc
lordkevinmo/Car-data-analysis
/data_analysis.py
13,888
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 20 17:36:26 2018 @author: Koffi Moïse AGBENYA Data Analysis """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats path='https://ibm.box.com/shared/static/q6iiqb1pd7wo8r3q28jvgsrprzezjqk3.csv' df = pd...
7f641d667144a103e2d3ee6b5f61be59935325d4
kentsai0606/109021038-20210305
/3月12課堂練習.py
519
3.75
4
class Student: def __init__(self,name,id ,height,weight,gender): self.name=name self.id=id self.height=height self.weight=weight self.gender=gender def showinfo(x): print(x.name,"\t",x.id,"\t",x.height,"\t",x.weight,"\t",x.gender) x1=Student("王小明","109021494"...
a54855e6684d32f95c58a60b0bfbeb32ec034552
Anirudh-Palakkal/Tic-Tac-Toe
/Tic-Tac-Toe.py
18,950
4.03125
4
from random import seed, randint BOARD_SIZE = 3 scene = "menu" x = 0 y = 0 '''Starting function''' def main(): global scene if scene == "menu": drawMenu() pick = input(center_text("Input: ")) while pick not in ['1', '2', '3', '4']: print(center_text(errorMsg())) ...
80181ec4a50a975ee25af0ffbf3e0025a5425c4f
linhlv55/ktpm2013
/triangle/test.py
1,515
3.703125
4
import unittest from math import sqrt from triangle import checkTriangle class MyTest(unittest.TestCase): def test_1_1(self): self.assertEqual(checkTriangle(-1,2,4),-1) def test_1_2(self): self.assertEqual(checkTriangle(1,-1,4),-1) def test_1_3(self): self.assertEqual(checkTriangle(...
c4ff839f933740ca8d8ccda7728968fcf77e085d
jamesthesnake/pythonRecursion
/recurse.py
362
3.5
4
def find_numAs_rec(s,g): newStart=1 value=0 i=0 if len(s)!=0: if s[i]==g: value=1 else: pass else: return value s=s[newStart:len(s)] numAs= value+find_numAs_rec(s,g) return numAs s=raw_input("Ask for string") g=raw_input("Ask ...
e6fe6fb48dce476195e7e4d5835199939bfc8708
jamesthomaskerr/Python-Project
/p_ratestemp.py
446
3.515625
4
# class Ratestemp: # # #arranging relevant information from CSV # def __init__(self, currcode, to_euro, from_euro):# # self.currcode=currcode # self.to_euro = to_euro # self.from_euro=from_euro # # # def __str__(self): # return "Currency:{} To-euro:{} From-Euro:{}"....
f74f78bb3fc27e9abd3158ff8cdbe7a93a7dc8b6
Shruti0899/Stack_to_list
/stcklst.py
1,837
4.25
4
print("list to stack\n") class StackL: def __init__(self): self.menu() def add(self,my_list,l): val=input("value:") if len(my_list)==l: print("\nStack is full.\nCannot add further.\nYou may choose to delete items to proceed.") else: my_list.appe...
21318de08e1887898beacf5b43bee4c674dd4707
EricMontague/Head-First-Design-Patterns-In-Python
/template_method_pattern/caffeine_beverage.py
567
3.890625
4
from abc import ABC, abstractmethod class CaffeineBeverage(ABC): def prepare_recipe(self): self.boil_water() self.brew() self.pour_in_cup() if self.customer_wants_condiments(): self.add_condiments() def boil_water(self): print("Boiling water") def pour...
3edf664f35496ecf289390d1b32216b4169bcca4
EricMontague/Head-First-Design-Patterns-In-Python
/factory_pattern/abstract_factory/pizzas/pizzas.py
1,738
3.671875
4
from abstract_factory.pizzas.pizza import Pizza class CheesePizza(Pizza): def __init__(self, ingredient_factory): self._ingredient_factory = ingredient_factory def prepare(self): print(f"Preparing {self}") self._dough = self._ingredient_factory.create_dough() self._sauce = sel...
246adcf4f0553416bf41bd07e72db7513b9e6a8c
shrikant25/paint
/button.py
2,505
3.640625
4
import pygame from setting import * class Button: # class use to create buttons def __init__(self, bxcoord, bycoord, bwidth, bheight, bcolorcode, bfontname=None, bfontsize=None, btext=None, btextcolor=None): self.bxcoord = bxcoord # x-coordinate self.bycoord = bycoord # y-coordinate self...
85d609dd24718e01362eae33352da3eef5d63bc6
dieduk89/project_euler
/python/exercise 2/code2.py
252
3.859375
4
print "\nMATH EXPRESSION\n" gold_number = (1+5**0.5)/2 def get_fibonacci_number(index): return int(gold_number**(index+1)/5**0.5+0.5) fibonacci = [get_fibonacci_number(x) for x in range(33)] print sum([x for x in fibonacci if x%2==0]) print "\n"