blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b831426b723d857fd9e624e5ad74e55988f681da
tianyangche/learning-python
/src/practice_function.py
1,989
4.46875
4
def greet_user(): """ Display a simple greeting. """ print 'hello!' greet_user() # multiple parameters def greet_user(first, last='Che'): print last print first # positional arguments greet_user('Terry', 'Che') # keyword arguments greet_user(last='Che', first='Terry') # default value greet...
dc3e8b8ad7afe35711ab6f1d0cc24295127f530e
joshavenue/python_notebook
/notebook2/all_any.py
587
4.25
4
nums = [55, 44, 33, 22, 11] if all([i > 5 for i in nums]): print("All larger than 5") if any([i % 2 == 0 for i in nums]): print("At least one is even") for v in enumerate(nums): print(v) ## all = take all iterable and check, say you wanna check 5 item in the list and make sure all is true, use all ## any =...
e2899150d46f95d3ee03ab3a463c071551204c39
reyesg29/fundamentos
/origin.py
285
4
4
name='guadalupe reyes martinez' age=32 istall=False height=1.52 print(name + " tiene "+str(age)+" años") print("{} tiene {} años".format(name,age)) print(f"{name} tiene {age+10} años y es \ alto {istall} y mide {height}") print(name.upper()) print(name.lower()) print(name.title()) print(name*5)
6a34496d114bc6e67187e4bc12c8ff874d575de0
BrightAdeGodson/submissions
/CS1101/bool.py
1,767
4.28125
4
#!/usr/bin/python3 ''' Simple compare script ''' def validate(number: str) -> bool: '''Validate entered number string is valid number''' if number == '': print('Error: number is empty') return False try: int(number) except ValueError as exp: print('Error: ', exp) ...
bb8c8fca2ec4375b70b70ac6aee3a6caa1b750b2
cajopa/adventofcode
/2018/geometry.py
8,770
3.53125
4
from numbers import Number import math class Vector: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f'<Vector ({self.x},{self.y})>' __str__=__repr__ def __eq__(self, other): return isinstance(other, Vector) and tuple(self) == tuple(...
39325e6351e1cb9ad48c7c62111c361fdbe2ffc8
buscaroli/web-scraping-python
/beautiful_soup/wscraping07.py
1,085
3.90625
4
# LEARNING WEB SCRAPING WITH PYTHON # Matteo # # Retrieving all the URLs from a single page from urllib.request import urlopen from urllib.error import HTTPError, URLError from bs4 import BeautifulSoup def validateURL(url): '''Validates the given URL''' try: html = urlopen(url) except URLError: ...
f090d8450d04f9126afee93f3ed65ab64d5b7325
AleefNoor/AleefNoor.github.io
/Python/draw_shapes.py
328
4.4375
4
from turtle import * import math # Name your Turtle. t = Turtle() sides= int(input("Number of sides?")) # Set Up your screen and starting position. setup(500,300) x_pos = 0 y_pos = 0 t.setposition(0, 0) ### Write your code below: for x in range(sides): forward(100) right(360/sides) # Close window on click. exiton...
bfa12cb1ef74c3120b77a8a381e20faa527b015e
lwyaoshen/Python
/test/0001.py
599
4.09375
4
#问题描述:第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? import random def gen_code(length = 6): code_list = []; for i in range(10): code_list.append(str(i)); for i in range(65,91): code_list.append(chr(i)); for i in range(97,123): code...
3e3653728cbbaa59a46bf2c87756b66528a106a9
vutran/blackjack
/game.py
32,532
3.671875
4
""" Project: Blackjack Author: Vu Tran Website: http://vu-tran.com/ """ # import modules import simplegui, random # configurations GAME_WINDOW_WIDTH = 600 GAME_WINDOW_HEIGHT = 600 GAME_WINDOW_SIZE = (GAME_WINDOW_WIDTH, GAME_WINDOW_HEIGHT) CARD_IMAGE_SRC = "https://www.dropbox.com/s/cd6ik0pmrnk97nm/cards.png?dl=1" #...
12253927cc6dc785b6a9be414498fa0892bdf905
thenicholascoder/python-object-oriented-python
/python-first-class.py
548
3.71875
4
class PartyAnimal: x = 0 def party(self): self.x = self.x + 1 print('So far', self.x) # function party(parameter){ # parameter = parameter + 1 # console.log('So far', parameter) # this will create an instance of the class with an parameter xy = PartyAnimal() # using an as paramet...
6fff0e7900996678e3c944ac73595cf6a5b82501
jzijin/leetcode
/933.最近请求次数.py
662
3.578125
4
class RecentCounter(object): def __init__(self): self.mystack = [] def ping(self, t): """ :type t: int :rtype: int """ self.mystack.append(t) count = 0 length = len(self.mystack) i = 0 while i < length: ...
b6ef2d40391fdce3cb86987e34cfd543c9a6d071
Cbkhare/Challenges
/InterviewBit_Trees_ValidBST.py
2,075
4.125
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def insert(self,b): if self.val: if b < self.val: if self.left is None: self.left = TreeNode(b) else: ...
1691b43b90ed915d5a180ce8af8cc3f7a38a5671
Vidhi23Chauhan/akademize_grofers_python
/08_even_odd.py
506
4.28125
4
n = int(input("Enter a number: ")) if (n % 2 == 0): print("Given number is even") else: print("Given number is odd") print("--End of program--") """ vidhichauhan@Admins-MacBook-Pro akademize-grofers-python % python3 08_even_odd.py Enter a number: 25 Given number is odd --End of program-- vidhichauhan@Admins...
174389add9222eb567682076afd679b8acb12bb5
ikhlestov/computational_geometry
/tests/test_predicates.py
731
3.578125
4
from algorithms.predicates import turn, points_turn_value, line_segments_turn_value from algorithms.primitives import Point, LineSegment def test_turn_left(): assert 1 == turn( Point(5, 10), Point(5, 20), Point(0, 15) ) def test_turn_right(): assert -1 == turn( Point(5, 1...
f840e6284f15ffff5b7e4047b78e4321b0241b91
acpfog/python
/6.00.1x_scripts/Week 2/Problem Set 1/item_order.py
1,098
4.34375
4
# Write a function called item_order that takes as input a string named order. # The string contains only words for the items the customer can order separated by one space. # The function returns a string that counts the number of each item and consolidates them in # the following order: salad:[# salad] hamburger:[# ha...
47a21915d18851463f03b12788d2013e24aa3bc7
Naysla/Machine_Learning
/5_Case Study School Budgeting with Machine Learning in Python_/30_Implementar modelos de interacción en scikit-learn.py
2,090
3.546875
4
#Implementar modelos de interaccin en scikit-learn #Es hora de agregar funciones de interaccin a su modelo. El PolynomialFeaturesobjeto en scikit-learn hace justamente eso, pero aqu se va a utilizar un objeto de interaccin personalizada, SparseInteractions. Los trminos de interaccin son una herramienta estadstica que l...
4a57b10a0201359983b83a8d7ad78f7f5b2118f6
KhlopotovAI/codewars-py
/unique/kata.py
241
3.578125
4
# https://www.codewars.com/kata/unique-in-order/train/python def unique_in_order(iterable): res = [] prev = None for e in iterable: if e == prev: continue res.append(e) prev = e return res
834b422a30096dbb44ee34a54162c7b659cea4c5
yaash45/HackerRankSolutions
/ProblemSolving/sock-pair.py
560
3.703125
4
#!/bin/python3 # https://www.hackerrank.com/challenges/sock-merchant/problem import math import os import random import re import sys # Complete the sockMerchant function below. def sockMerchant(n, ar): freq_graph = [0]*101 full_pair_count = 0 for sock_number in ar: freq_graph[sock_number] += 1...
4c4e4f2202ed5490a730e9943f249de224868235
ahammadshawki8/DSA-Implementations-in-Python
/CHAPTER 10 (maps, hash tables and skip lists)/counting word frequencies.py
628
4.09375
4
freq = {} filepath = input("Enter a path name: ") for piece in open(filepath).read().lower().split(): # we have to define the path of the file # only consider alphabeticcal character within this piece word = "".join(c for c in piece if c.isalpha()) if word: #require alleast one alphabetical character ...
fe086ae0253196522a4d8aec768029d7b3db3dda
samuelpordeus/varzea-analise
/equipe.py
743
3.5
4
class Equipe: def __init__(self, name): self.name = name self.players = [] self.attacking_power = None self.defensive_power = None self.calculate_AP() self.calculate_DP() def add(self, player): self.players.insert(0, player) def info(self)...
2544c2b933a25af97826a8ec4ae50509090ca8fc
ShourjaMukherjee/Dummy
/11thcodes/Lists/ASSIGN 103 - LIST - Leader of List (1).py
666
3.640625
4
def accept_list(n): L=[] for i in range(n): a=int(raw_input("Enter Element at index %d :- "%i)) L.append(a) return L def leaderList(L): l=len(L) R=[] for i in range(l): if i==0: if L[i]>L[i+1]: R.append(L[i]) elif i==l-1:...
ee9abe39cf0ce9b922e34828c88a49f65b7ea977
ROBot26/hangman
/Hangman/Hangman.py
2,976
3.78125
4
import random ##---------------------------- Importing word from word bank filename='Word library.txt' numLines = 0 with open(filename,'r') as fin: for line in fin: numLines = numLines+1 print"Number of lines is %i" % numLines word_index=random.randint(1,numLines) print"Number of inde...
7ae55172784d7c8435c776c1d7db22f4db6db7e6
wndtanaka/Introduction-to-Programming
/Week_4/filter.py
118
3.71875
4
import sys file = sys.argv[1] index = sys.argv[2] for word in open(file): if word[0] == index: print(word)
04c9c6b6c8943a79d8047596e10c4244ff4cd206
GabrielRCAmaral/Brincando-de-Python
/URI/1153.py
149
4.0625
4
# -*- coding: utf-8 -*- def fat(n): if n==1: return 1 if not n: return 1 return fat(n-1)*n n=int(input()) print fat(n)
ef276892f92c9518d6a527c65c982bb727addc81
jbbenavidesr/curso-python-prea
/Clase6/validation.py
173
3.90625
4
choice = int(input("pon 0: ")) while choice < 0: print("Ese numero es negativo.") choice = int(input("Escoge de nuevo: ")) print(f"tu numero fue {choice}")
b2a8bf1352633d76126fd1fea6b273b07053d6b7
angelvv/HackerRankSolution
/Python/03.Sets/30.SetAdd.py
225
3.90625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT country = set() for n in range(int(input())): country.add(input()) print(len(country)) # One-liner #print len({input() for x in range(int(input()))})
cbef106e977ce9340b209ce46a9cd9fa6ef1940a
vmred/codewars
/katas/6kyu/regex pattern to check if string has all characters/solution.py
806
4.6875
5
# Task: # Your function should return a valid regular expression. # This is a pattern which is normally used to match parts of a string. # In this case will be used to check if all the characters given in the input appear in a string. # Input # Non empty string of unique alphabet characters upper and lower case. # Ou...
1a6a036e78728c72fd4bb139f35743d56a77d9ee
sommano/pythonHW
/l101/Chap12ex2.py
424
3.890625
4
class Point: def __init__(self, init_x, init_y): """ Create a new point at the given coordinates. """ self.x = init_x self.y = init_y def get_x(self): return self.x def get_y(self): return self.y def distance_from_origin(self): return ((self.x ** 2) + ...
da6e38898cd516dcf6f38a4ef42c3986bdccd810
aman-bhatia/dia-0
/resize_to_double(replication)/main.py
478
3.515625
4
import cv2 import numpy as np img = cv2.imread("../lena.jpg") def resize_replicate(x): ''' Resizes given image to double the size by replicating pixels ''' (h,w,c) = x.shape result = np.zeros((2*h,2*w,c)) for i in range(h): for j in range(w): result[2*i][2*j] = result[2*i +1][2*j] = result[2*i][2*j +1] = r...
b486b4b8152ed509dd1f9ef71fdf69c06f73dc7a
hmchen47/Programming
/Python/PythonHardway/ex16.py
1,890
4.6875
5
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ # Exercise 16: Reading and Writing Files """ usage: python3 ex16.py test.txt Mary had a little lamb Its fleece was white as snow It was also tasty """ from sys import argv script, filename = argv print("We're going to erase %r." % filename) print("If you don't want t...
988803e078074d34c97ae5aa77391a399a61a824
ThomasRochais/Astrododge
/projectile.py
1,148
3.671875
4
import pygame import os class Projectile(): def __init__(self, rocket): self.rocket = rocket self.game = rocket.game self.image = pygame.image.load(os.path.join("assets/sprites", "bullet2.png")) self.image = pygame.transform.rotate(self.image, -90) self.width, self.height =...
b854f842c5c9f190f195ce50cb9f2b39f4057888
anliu520/pyprogram
/day032/test05.py
771
3.75
4
#Author:Anliu import queue,threading list1 = queue.Queue() #先进先出 list2 = queue.LifoQueue(maxsize=5) #先进后出 def listput(): for i in range(5): #print(i) list2.put(i,block=True,timeout=None) #if queue.Full: # print("撑死了...") listput() #print("len is :",list2.qsize()) #print(list2.g...
6404225d085ea76e3cdc5f146905e072a70b9f37
rjherrera/IIC2283
/T1/subarrays.py
1,004
3.6875
4
from random import randint # BOTTOM UP # ms(i) representa suma máxima hasta el indice i # -> max { elegir el i: i + ms(i - 3), no elegir el i: ms(i - 1) } # Formalmente: # base: i = 0: elementos[0] # base: i = 1: max(elementos[0], elementos[1]) # base: i = 2: max(elementos[0], elementos[1], elementos[2]) # recu: i > ...
1a8434decdb69e7cff735a5e5a6eb665c7d4b7aa
Tuchev/Python-Fundamentals---january---2021
/04.Functions/02.Exercise/01. Smallest of Three Numbers.py
362
4.125
4
def find_smallest(num_1, num_2, num_3): if num_1 < num_2 and num_1 < num_3: return num_1 elif num_2 < num_1 and num_2 < num_3: return num_2 elif num_3 < num_1 and num_3 < num_2: return num_3 num_1 = int(input()) num_2 = int(input()) num_3 = int(input()) result = find_sm...
57a93788728fc36691f605f38f981582ac631aae
UUtest/learnstone
/map-reduce-homework.py
1,520
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce '''def str2float(s): n = 10 ** -(s[::-1].index('.')) return n*reduce(lambda x, y: x * 10 + y, [int(a) for a in s if a is not '.']) def str2float(x): list(x) position = x.index('.') integer1 = list(map(int, x[:position])) ...
04ffa89af83e2b964a8dc6e948fee7711890c520
raul-jr3/PyTuts
/Lists/list_append_extend_length.py
955
4.625
5
# this file consists of list operations : append, extend, length # create a list a = [10, 20, 30, 40, 50] print("original list") print(a) #Append: # to add an element at the end of the list: use the append method print("appending 35 to 'a'") a.append(35) print(a) # Extend : # suppose we have a list b, now we append ...
5bbdc167f4c895bf6f859899c72c4aac755d8baa
swhitelaw/crypto
/Lab2.py
3,353
3.90625
4
'''Assignment: In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in ...
ee8d726df3a2431d4a8912a4f65adf1f5fef7d69
ahmedsaalah/Hotels
/room.py
555
3.546875
4
from hotel import Hotel class Room (): ''' This class consists of main attributes of the rooms ''' def __init__(self, nonrefundable, mealtype,room_category, room_description, code,nightly_prices,room_type): """ constructor """ self.nonrefundable = nonrefu...
ac65d34624ccb59c8c81dcbff45da34b9f9587f7
tintin10q/RandomPythonProjects
/single_dispatch_function.py
453
3.65625
4
from functools import singledispatch @singledispatch def merge(first, second): return first + second @merge.register def _(first: list, second: list) -> list: first.extend(second) return first @merge.register def _(first: dict, second: dict) -> dict: return first | second a = merge({'2': 'a'}, {...
abf6510fd6250990ebd19706991bddefb8599323
konts-olexandr/Laba-1-6
/Сalculator.py
328
3.890625
4
a = int (input("Введіть число номер 1 ")) var1 = input("+, -, *, /, ** ") b = int( input("Введіть число номер 2 ")) if var1 == "+": n= a + b if var1 == "-": n= a - b if var1 == "*": n= a * b if var1 == "/": n= a / b if var1 == "**": n= a ** b print(n)
ee26dfae8a9188b66e7233754e27e92458278ade
JayjeetAtGithub/DS-Algorithms
/test.py
267
3.703125
4
class Node: def __init__(self,val): self.val = val class Tree: def __init__(self): self.root = 45 def put(self,val): self.root = self._put(self.root,val) def _put(self,node,val): node = val return node t = Tree() t.put(23) print(t.root)
9f55bee34de372f609368395d81b5233f84d0d39
muheeb75/my_python_mini_projects
/big-bang-game.py
1,504
4.125
4
import random def game2(): count=0 name=input("Enter your name : ") print("Welcome ",name,"to our big-bang game\n") print("Rules of the big-bang game :\n") print("1.You will get 3 input chances in that 2 input should mach then you will be the winner") print("2.You can enter the number bet...
1294c26b1f71968705baff98cd9708e31c612c12
shaide/sympy
/sympy/geometry/point.py
8,677
3.5
4
from sympy.core import S, sympify from sympy.simplify import simplify from sympy.geometry.exceptions import GeometryError from sympy.functions.elementary.miscellaneous import sqrt from entity import GeometryEntity class Point(GeometryEntity): """ A point in Euclidean N-space defined by a sequence of values. C...
86f8b72c1bb8f424a5da6e75665bb1476abbf5df
coxwm11/CodingProjects
/sim.py
1,630
3.78125
4
import sys def xInput(x): #Prints x values for the number of rows requested for x in range(1,int(x)+1): print (x) def yInput(): #Enter y-values here y_list = list() yInput = raw_input("Press y to begin entering y-values:") #y y = input("Y: ") y_list.append(y) #y1 y1 = in...
b3b8a5d4add2f12e39460bbfd27249442fc984a4
luanaAlm/Python
/Exercicios/2EstruturaDeDecisao/EX10.py
1,000
4.09375
4
""" Faça um programa que lê as duas notas parciais obtidas por um aluno numa disciplina ao longo de um semestre, e calcule a sua média. A atribuição de conceitos obedece à tabela abaixo: Média de Aproveitamento Conceito Entre 9.0 e 10.0 A Entre 7.5 e 9.0 B Entre 6.0 e 7.5 C Entre 4.0 ...
b7df8bcda9afa08995feaec7645d3e6224134c21
MainakRepositor/Web-Scrapping
/web9.py
374
3.84375
4
'''Write a Python program to that retrieves an arbitary Wikipedia page of "Python" and creates a list of links on that page''' from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://en.wikipedia.org/wiki/Python") bsObj = BeautifulSoup(html) for link in bsObj.findAll("a"): if ...
2ec56cfce176db486446555ed05d287b6c441f0f
bgoonz/UsefulResourceRepo2.0
/_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/mini-scripts/python_Join_Two_Tuples.txt.py
84
3.875
4
tuple1 = ("a", "b", "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3)
12bbac7c9cb949fd6ff8a589e589dcc3e88d6c52
qutorial/lockfish
/lockfish/callgraph.py
4,604
3.671875
4
def getStack(node, stack): if node is None: return stack stack.insert(0, node) return getStack(node.back, stack) class CGNode: def __init__(self): self.node = None self.children = [] self.back = None self.recursed = False self.analyzed = False def pprint(self): print(self.spell()...
794685a26be8c9ebb07e1db6f6374856cfde5a74
ThiagoFTelles/python_course
/ex091.py
913
3.859375
4
""" Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário em Python. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado. """ from random import randint from time import sleep from operator import itemgetter ...
5030af647ea681d80ffd7007c1b5f576c9b63ac9
i-m-sayandeep/Codevita-Solutions-2020
/TCS_solution/best_sequence.py
346
3.59375
4
from itertools import permutations def keyCombo(x): y =list(permutations(x)) a=[] for i in y: a.append("".join(i)) return(a) s = input() y = list(map(str,input().split())) keys = "".join(y) combo = keyCombo(keys) combo = sorted(combo) l=[] for i in combo: l.append(s.count(i)) a = l.ind...
b2e7762289c447cb5dce77fcd42cf8966da11052
KabirSinghShekhawat/DFA
/dfa_generate_XML.py
4,904
3.625
4
# import pygraphviz as pgv from pprint import pprint from random import choice as rchoice import xml.etree.ElementTree as ET from xml.dom import minidom number = int(input ("Enter NUMBER: ")) base = int(input ("Enter BASE of number system: ")) def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): """ conv...
bc6d81ce902bd683c836c9fa7d1d4e43a9536937
summerela/intro_programming_python
/Module4/hw3_error_checking2.py
1,146
4.5
4
""" This script asks the users for two numbers, places them in a list, then tells the user the index location of each number, and if it is divisible by 3. The user could break this script by not providing a minimum number that is less than the maximum number. I have used while to prompt the user to enter a new maxim...
9837f791bf826296de83b1dc9f2df11395dad5cd
maxsud1978/100_python_challenges
/11.py
603
3.9375
4
''' Question 11 Level 2 Question: Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output shou...
9aba43d254b8a1695d6f4c8876c22ed5b9a41160
swarnabarathik/Python
/Assignment/elif.py
866
3.9375
4
employee_id=int(input("enter the employee id")) basic_salary=int(input("enter the basic salary")) allowance=int(input("enter the allowances")) monthly_gross_salary=basic_salary+allowance if(monthly_gross_salary<=5000): net_salary=monthly_gross_salary elif(monthly_gross_salary>=5001 and monthly_gross_salary<=10000): i...
2d0cb403e4133e3467c38cad133c0442187ba40e
Shivani161992/Leetcode_Practise
/Array/RemoveElement.py
508
3.65625
4
from typing import List nums = [0,1,2,2,3,0,4,2] val = 2 class Solution: def removeElement(self, nums: List[int], val: int): if len(nums) == 0 and len(nums): return 0 else: i = 0 j = len(nums) while i < j: if nums[i] == val: ...
4b36f0c819530ca5d175619127d4d0a0b4270c21
or1300/Python-project
/WorldOfGames/Live.py
2,056
3.96875
4
import MemoryGame import GuessGame import CurrencyRouletteGame import Score def welcome(name): return "\nHello" + name + " and welcome to the world of Games (WoG). \nHere you can findmany cool games to play\n" def load_game(): global result no_exception = False while no_exception == Fal...
1f75af12944318e47234d5638c1b130bd15d463e
VisveshS/BPlusTree-and-Linear-Hashing
/bplustree.py
2,468
3.59375
4
import sys import bisect MAX_NODE_SIZE = 3#maximum of 3 keys class Node: def __init__(self,keys,children,nextr,leaf): self.keys = keys self.children = children self.next = nextr self.leaf = leaf def split(self): mid = int(len(self.keys)/2) new_key = self.keys[mid] if self.leaf: temp_node = Node(sel...
0a066abda9610ccd5df0ba4d93619afe831613b9
lamyanlok/FTDS
/HackerRank/Day3TimeConversion.py
695
4
4
#!/bin/python3 import os import sys # # Complete the timeConversion function below. # def timeConversion(s): # # Write your code here. # x = s[-2:] hour = s[0:2] rest = s[2:-2] n_hour = int(hour) if x =="AM" and hour !="12": n_hour = str(hour) elif x == "PM" and hour == "12...
364ccca8cd185d0427c76ed9f02a40f63016d143
ytatus94/Leetcode
/python3/142_Linked_List_Cycle_II.py
1,739
4.03125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ # 先用快慢指針找出相遇點 fast, slow =...
e7447b8d3f57b0e114f70f2d7aa3c2a173bc2aeb
EssamB13/puzzle-solver
/word_ladder_puzzle.py
3,527
3.890625
4
from puzzle import Puzzle class WordLadderPuzzle(Puzzle): """ A word-ladder puzzle that may be solved, unsolved, or even unsolvable. """ def __init__(self, from_word, to_word, ws): """ Create a new word-ladder puzzle with the aim of stepping from from_word to to_word using wor...
5eb376688879963c7ceb17e0af5a6ee4501264a5
JLowe-N/Numeric_Matrix_Processor
/Numeric Matrix Processor/task/processor/processor.py
11,691
3.984375
4
import copy class Matrix: def __init__(self, rows, columns, array): self.rows = rows self.columns = columns self.elements = array def create_row(self): return self.elements.append([int(element) for element in input().split()]) # def __str__(self): # print('[') # ...
1bd8631129511b899b4a5063f844591eea7842e3
gpsbird/GFS
/tests/funtionLibraryRecv/serverEmulator.py
1,493
3.5
4
#!/usr/bin/env python ################################################################# # # SERVER EMULATOR FOR FUNCTIONLIBRARY TESTING # ################################################################# import socket, config import functionLibrary as fL port = int(raw_input('What port to connect o...
05e7d710dff49403af0052d3aca143cee32c8991
kingmolnar/DataScienceProgramming
/04-Pandas-Data-Tables/HW04/hw4_template.py
4,442
3.984375
4
# Solutions to homework 4 import numpy as np import pandas as pd # ____ _ _ _ # | _ \ _ __ ___ | |__ | | ___ _ __ ___ / | # | |_) | '__/ _ \| '_ \| |/ _ \ '_ ` _ \ | | # | __/| | | (_) | |_) | | __/ | | | | | | | # |_| |_| \___/|_.__/|_|\___|_| |_| |_| |_| # # Create a functi...
6913b013b1e2feed76f1a899e06e0ee32a902320
taizilinger123/pythonjichu
/02-python高级-2/01-闭包/01-闭包1.py
282
3.5625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def test(number): print("----1----") def test_in(number2): print("----2----") print(number+number2) print("----3----") return test_in ret = test(100) print("-"*30) ret(1) ret(100) ret(200)
2eeb2f643d124172731ef91f9c68b7c8b14f226e
binonguyen1090/PythonExercises
/pick_prime.py
386
4.0625
4
# Pick Primes # Write a method pick_primes that takes in an array of numbers and returns a new array containing only the prime numbers. def prime(n): for i in range( 2, n): if n % i == 0: return False return True def pick(arr): result = [] for i in arr: if prime(i): result.append(i) ...
db5d8c786cf63779649d3e1e3278070cc4fcb719
altoid/leetcode
/py/april_2021_challenges/combination_sum_iv.py
1,332
3.71875
4
#!/usr/bin/env python # https://leetcode.com/explore/challenge/card/april-leetcoding-challenge-2021/595/week-3-april-15th-april-21st/3713/ import unittest class Solution(object): def __init__(self): self.state = {} def combinationSum4(self, arr, target): # numbers in arr are distinc...
3545c0426af8ba4d0b6863d430883f1d6ad29b43
saetar/pyEuler
/done/py/euler_063.py
1,024
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Jesse Rubin """ Powerful digit counts Problem 63 The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ from itertools import count de...
35bbd07171b34d3b55cdd330e60b561de643ac10
anatulea/Educative_challenges
/Linked Lists/04_length.py
688
3.984375
4
from Node import Node from LinkedList import LinkedList def length(lst): # start from the first element curr = lst.get_head() length = 0 # Traverse the list and count the number of nodes while curr: length += 1 curr = curr.next_element return length lst = LinkedList() lst.in...
11d32124461fcfeb60fa43c271438e92582d48a4
bermec/python
/src/books/continue.py
717
3.671875
4
#------------------------------------------------------------------------------- # Name: module2 # Purpose: # # Author: rog # # Created: 02/08/2010 # Copyright: (c) rog 2010 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env py...
45319c46842b4c43d553385498b85613eb98482b
tcrasset/hangman
/utils/game.py
4,894
3.953125
4
from typing import List, Union import random from collections import Counter class Hangman: mandatory_words = ["becode", "learning", "mathematics", "sessions"] blank_char = "*" def __init__(self, possible_words: List[str]): """Creates the Hangman object. Args: possible_words ...
ce3d073e187b40ba3fe610f8a7ee4a4ff07e6ef5
Zhuhh0311/leetcode
/math/reverse.py
1,050
3.578125
4
#给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 #例如:123 --> 321, -123 --> -321, 120 --> 21 #执行用时 :52 ms, 在所有 Python3 提交中击败了12.31%的用户 class Solution: def reverse(self, x: int) -> int: y, res = abs(x), 0 of = (1 << 31) - 1 if x > 0 else 1 << 31 while y != 0: res = res * 10 + y % 10 ...
0f42352b8b1114cc3640672d883e836a164d4b97
yogeshjean12/Thoughtworks-Python-Assignments
/2.2_print_the_pattern_according_to_the_number_of_rows_given_by_the_user.py
460
4.0625
4
no_of_rows=int(input('Enter the number of rows and enter only even number: ')) no_of_stars=1 if no_of_rows%2!=0: for i in range(no_of_rows//2+1): for j in range(no_of_stars): print('*',end='') no_of_stars+=2 print() no_of_stars-=4 for i in range(no_of_rows//2): f...
86fb41560e8134c0c06afd931671f31ca5d0b0fb
StayErk/KernelMethodsUtilities
/FastaGenerator.py
9,220
3.75
4
from random import seed from random import random import os import sys import time """ Questo modulo implementa la generazione di Null Model e Alternate Model utilizzando il Pattern Transfer """ alphabet = ('A', 'C', 'G', 'T') class RandomGenerator(): """ Questa classe si occupa della generazione casuale de...
95627ba31b6c6036b2e67601d60114b7477837cf
trynusnick13/ITEA_AC
/Yurii_Khomych/l_3_oop/decorators/decorators.py
533
3.765625
4
import functools def count_calls(func): # @functools.wraps(func) def wrapper_count_calls(*args, **kwargs): wrapper_count_calls.num_calls += 1 print(f"Call {wrapper_count_calls.num_calls} of {func.__name__!r}") return func(*args, **kwargs) wrapper_count_calls.num_calls = 0 retu...
8e1dec73109fecf4a6a69cfe8b2f966db92dccf8
tjkhara/notes
/python/courses/colt_steele/19_functions_part2/kwargs_exercise.py
635
3.828125
4
# def combine_words(word, **kwargs): # if kwargs == {}: # return word # if kwargs.get("prefix"): # return kwargs["prefix"] + word # if kwargs.get("suffix"): # return word + kwargs["suffix"] # print(combine_words("child")) # print(combine_words("child", prefix="man")) # print(combine_words("child", suffix="ish...
86f3c2013666ea2269b8908e31759fe23eeaf604
YunfeiZHAO/master
/ARS2/ARS2_A20_TD04_Lidar_GPF/pypcd/test.py
624
3.609375
4
if __name__ == "__main__": line = 'joker JOKER-4 4 4 4' p1, p2 = line.split('-') if p1 == 'joker JOKER' or p2 == 'joker JOKER': print('joker JOKER') else: p1 = p1.split() p2 = p2.split() all_card = "3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER" if len(p1) == len(p2): ...
8487812bc395c3ffdc4a8995b474aa9c3c5c74b7
daiyunchao/stupid_way_learn_python
/笨办法学python/ex_42.py
1,028
4.1875
4
#coding=utf-8 # 对象、类、以及从属关系 # 因为 pdf的原因 42节的练习代码出现在了41节中 # 下面是我的一个小练习 class Person(object): def __init__(self,name): self.name=name self.pet=None def set_pet(self,pet): self.pet=pet def person_speak(self): print "Hi, my name is %s" %self.name def pet_sound(self): if (self.pet != None): ...
59a681c9a4922c7a17490bddf0ff2f7a9426b228
sanchitgupta001/OpenCV_with_Python
/Basic_Image_Analysis/Thresholding.py
1,706
3.8125
4
import cv2 import numpy as np img = cv2.imread('bookpage.jpg') # Threshold all pixels with values greater than 12 will be assigned 255 retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY) # Above threshold is being applied to the colored image as such before converting it to grayscale # Below threshold...
a4b3485c0ffbb642173f1fed0aabc287c72bc0b8
littlewhite0208102866666/the-first
/3.py
275
3.8125
4
import turtle def draw_square(t, size): for i in range(360): t.forward(size) t.left(1) window = turtle.Screen() window.bgcolor("lightgreen") john = turtle.Turtle() for i in range(1): draw_circle(john.size)
3306bdf21d0c8d999b1f487e78b60c8c007c51ef
heba-ali2030/data_types
/area_of_triangle.py
273
3.96875
4
# write a function def area_triangle(b,h) to compute the area of triangle : formula is area= s*b*h def area_triangle(b,h): area= 0.5 * b * h print("the area of a triangle of base", b, "and height", h, "is", area) area_triangle(3,5) # area_triangle(6,9)
f8725b74a597822c3ffd3a4e7357540a3060b67a
ultimatumvizz/python50
/py39.py
771
3.53125
4
#Evaluating a postfix expression class stack: def __init__(self): self.items=[] self.t=-1 def push(self,item): self.t+=1 self.items.insert(self.t,item) def pop(self): self.t-=1 def size(self): return self.t def isempty(self): return self.items==[] def top(self): return self.items[self.t] st=stac...
a47410ad1c67ed3fde92e0c64caec6cfab25cd83
AymanNasser/Python-For-Everybody-Specilization
/Using Database/Week3/Inserting to relational table.py
2,394
3.6875
4
import sqlite3 import xml.etree.ElementTree as ET from relational_table import create_tracks_table create_table('tracks.sqlite') # Connecting a file Tracks connection = sqlite3.connect('tracks.sqlite') # Cursor is kind like a handle cur = connection.cursor() def lookup(dict, key): found = False for child in ...
689daeaeb9b50e34bb0068c4f59c26642df7624b
MrJouts/learn-python
/ch4/13.buffet.py
318
3.859375
4
foods = ("fideos con salsa", "empanadas", "pizza", "ñoquis", "pastel de papa") print("--- Menú") for food in foods: print(food.title()) # foods[0] = "fideos con crema" foods = ("fideos con crema", "canastitas", "pizza", "ñoquis", "pastel de papa") print("--- Nuevo menú") for food in foods: print(food)
f94a0e690c33da62a1d64d3bca4c62cfc8004156
jailukanna/Python-Projects-Dojo
/04.100 Python Exercises Evaluate and Improve Your Skills - AS/Exercise 51-75/exercise_51.py
503
3.84375
4
# Question: The code produces an error. Please understand the error and try to fix it # print(type("Hey".replace("ey","i")[-1]) # Answer: print(type("Hey".replace("ey","i")[-1])) # Explanation: # This code produces a SyntaxError: unexpected EOF while parsing which means that Python found an unexpected End Of File wh...
cc45f729c871907942675197730832982d1503ad
Oscar-Oliveira/Python-3
/13_Object_Oriented_Programming/C_OOP_Part_3/main.py
2,050
4.03125
4
""" OOP - Game """ import random from room import Room from character import Hero, Enemy DIRECTIONS = ["N", "S", "E", "W"] def layout(castle): castle.append(Room("Room 1", "Room identified by id 1")) castle.append(Room("Room 2", "Room identified by id 2")) castle.append(Room("Room 3", "Room id...
99ebeb6e405a2d0aa3ec7481d75ee2cb0b195a24
ParzivalMarcos/EstudosPython
/Udemy - Curso Python/args.py
1,221
4.65625
5
""" Entendendo o *args - O *args é um parâmetro como outro qualquer, isso significa que voce poderá chamar de qualquer coisa, desde que começe com asterisco Exemplo: *xis Mas por convenção, utilizamos *args para defini-lo O que é *args? O parâmetro *args utilizado em uma função, coloca os valores extras informados ...
ad0e90d1fbcfb865d6395de3fe2d5d5d130a46d2
ckceddie/OOP
/OOP_car.py
1,015
3.8125
4
class Car(object): def __init__(self, price, speed, fuel, mileage): self.price = price self.speed =speed self.fuel = fuel self.mileage = mileage def display_all(self): if self.price > 10000 : tax = 0.15 else: tax = 0.12 print "==...
2990463ed7737f10ef151d55a08f88e38da4fd86
Khrystynka/LeetCodeProblems
/96_unique-binary-search-trees.py
510
3.546875
4
# Problem Title: Unique Binary Search Trees class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ memo = {} memo[0] = 1 memo[1] = 1 def calcnum(k): if k in memo: return memo[k] else: ...
d22939ef731f52124d3d20e3886e6a9268a968ef
shani25/Auto-encoder
/autoencoder.py
6,859
3.53125
4
from random import seed from random import random from math import exp import numpy as np from datetime import datetime from matplotlib import pyplot as plt # Initialize a network def initialize_network(n_inputs, n_hidden, n_outputs): network = list() hidden_layer = [{'weights': [random() for _ in range(n_in...
35f72c580a8b44aff5f78df33a058d7f07b0e8eb
lidia01/chavez-cabrera-lidia
/chavez_cabrera/ejercicio31.py
302
3.5
4
#ejercicio31 #declaracion de variables precio_del_juego1=0.0 precio_del_juego2=0.0 precio_del_juego1=float(input("ingrese precio del juego1:")) precio_del_juego2=float(input("ingrese precio del juego2:")) #processing t=(precio_del_juego1+precio_del_juego2) if(t<24): print("buen juego") #fin_if
aa993b6ff45c8137b262e1dfa5d14772880db19a
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4181/codes/1644_2704.py
133
3.53125
4
nota= float(input("valor")) bon = input("S/N") var = (nota*10)/100 if(bon.upper() == "S"): print(nota + var) else: print(nota)
d5081981fef0fc3313daa699a0daf8785bca0b58
edinpark01/Cracking_the_Coding_Interview
/Chapter 01 - Arrays and Strings/04 - Interview Questions/My Solutions/exercise_1.4.py
2,310
4.53125
5
""" @Student Braulio Tonaco @Date 07/12/18 1.4 Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A PALINDROME is a word or phrase that is the same forwards and backwards. A PERMUTATION is a rearrangement of letters. The PALINDROME does not need to be l...
04b8212e2d62b10b60c31f1ff6ff360491e52a1a
felipemanfrin/Python-Zero-ao-Zeno
/venv/teste.py
571
3.609375
4
manipulador = open ('D://Downloads//texte.txt','w+') manipulador.write('esse eh meu novo testinho/npulando a linha e bora ver ser pega mais de u ma linha') manipulador.seek(0) print('Metodo read():') print(manipulador.read()) '''manipulador.seek(0) #volta para o começo da linha no arquivo, pois toda vez que ele lê o a...
9d6dd560b1f7e1fe1de912dbb7c6a2fb0bb79eea
savithapalanivel/python
/largerstring.py
168
4.03125
4
def largerstring(str,n): result="" for i in range(n): result=result+str return result print(largerstring('savi ',2)) print(largerstring('ajay ',3))
b984e041f9b6afe87ba7a98df899c144da1b69c1
argyroudis-george/various
/rescaled_range.py
5,813
3.6875
4
#Rescaled_Range_Analysis # Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from tabulate import tabulate import math import statistics as stat import scipy.stats #Functions def average_function(alpha): avrg = sum(alpha)/len(alpha) return avrg #data input, creation of DataFram...
fec7d0da65f782a0c62a284eeffa88d9ee792d2c
shanthivimalanataraajan01/code
/set6digit.py
84
3.609375
4
a=int(input()) b=str(int(a)) for i in range(0,len(b)): print(str(b[i])+' '+end="")
50c69b856f10d79285ff55355c35399f6d6ab7dc
bhupendpatil/Practice
/Python/oopsOver.py
512
3.953125
4
# Overloading def add(instanceOf, *args): if(instanceOf=='int'): result = 0 if(instanceOf=='str'): result = '' if(instanceOf=='float'): result = 0.0 for i in args: result+=i return result add('int',1,2,3,4,5) add('float',1.0,3.6,4.90) add('str','python','2323',' tuo...
c9995afdfbea27570318fed2970021edf4a9a3d4
mrDonald009/GeekUniversity
/3. алгоритмы_языка_python/Урок 7. Практическое задание/task_3.py
2,834
3.609375
4
""" 3. Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой – не больше медианы. Задачу можно решить без сортировки исходного ма...
05ee90aa842debe26a2bf0e1d9ab5ca349e38946
ikumen/rosalind
/solutions/bs_revc.py
1,099
3.734375
4
#!/usr/bin/env python ''' bs_revc.py: Complementing a Strand of DNA Problem: In DNA strings, symbols 'A' and 'T' are complements of each other, as are 'C' and 'G'. The reverse complement of a DNA string s is the string s^c formed by reversing the symbols of ss, then taking the complement of each symbol (e.g., the ...
b2272221f7a060bf64f3ce154f409c30b6425545
hyuhyu2001/python_study
/Datatypes/dict_summary.py
6,615
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: jinzj @desc: """ ''' 字典是另一种可变容器模型,且可存储任意类型对象。 典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示 d = {key1 : value1, key2 : value2 } 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 ''' # 创建字典 # 1、空字典 d1 = {} D2 = {'name': {'first': 'diege', ...