blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ee29f552846c7ef7d9973ca037cdf94d91a6d296
WalshCBryan/christmas_break_python
/basic_exercises.py
1,328
3.75
4
import multiprocessing import os # prints twinkle twinkle properly formatted print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a " "diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!") # accept a users first and la...
ce756028137827ada1bcce91a96f75a044a882ad
daniel-reich/ubiquitous-fiesta
/fRjfrCYXWJAaQqFXF_24.py
355
3.609375
4
def primorial(n): primo = 2 num = 3 num_of_times = 0 while True: if num_of_times == n-1: return primo z = 1 for i in range(num - 3): if num % (i+2) == 0: z = 0 break if z == 1: primo *= num n...
9a866fc7740f4f1359595928a6f6955649206e12
kardasiremsu/Learning-Python
/Hatalar ve İstisnalar/çiftmi.py
588
3.8125
4
""" Bir sayının çift olup olmadığını sorgulayan bir fonksiyon yazın. Bu fonksiyon, eğer sayı çift ise return ile bu değeri dönsün. Ancak sayı tek sayı ise fonksiyon raise ile ValueError hatası fırlatsın. Daha sonra, içinde çift ve tek sayılar bulunduran bir liste tanımlayın ve liste üzerinde gezinerek ekrana sadece çif...
66ea835b09a3a29c9d23a7997738def3de32bfc8
paulrich1234/recover
/test.py
347
3.640625
4
import pandas as pd a=pd.DataFrame(data=[[1,2,5,8],[3,7,9,10],[4,10,61,7]],index=['a','b','c'],columns=['cc','bb','bbe','dde']) # print(a) c = a.loc[['a','b']].sum(axis=0) c=pd.Series.to_frame(c).T c.index=['rr'] # print(ff) e=a.drop(['a','b']) # print(e) print(c) d=pd.concat([e,c]) print(d) a='ABC CIN' if 'ABC' ...
77da39a4b5d97e3a7f78663c8f2b4f3db1a5477b
pedestrianlove/10901_Python_THU
/HW/HW10/6.4/10.py
233
4.1875
4
# Fibonacci Sequence def Fibonacci (n): if n in [0, 1]: return n return Fibonacci (n - 1) + Fibonacci (n - 2) # Driver code n = int (input ("Enter a positive integer: ")) print ("Fibonacci number: {:d}".format (Fibonacci (n)))
f63eb3a5eb86f21421a927cb48e58c9e2f5e519c
varun-deokar/Cipher-Algorithms
/viginere_cypher.py
923
4.15625
4
def input_function(): message = input("Enter a string\n") key = input("Enter a key\n") return message, key def key_generation(message, key): new_key = "" size = len(key) for i in range(len(message)): new_key = new_key + key[i % size] return new_key def encrypt(message, key): ...
c8c9a0b9e9e3a2459ed6db0168de6084f16e06e5
iCodeIN/competitive-programming-5
/leetcode/Tree/second-minimum-node-in-a-binary-tree.py
835
3.875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findSecondMinimumValue(self, root): """ https://leetcode.com/problems/second-minimum-node-in-a-binary...
6fe357631a46597e61f2bb623eeda80b1f43fee6
Hyperdraw/FridayClub
/Word_Guess.py
2,414
3.921875
4
import random from time import sleep as s STAR_WARS = [] loop = 0 counter = 0 JD = 0 lol = 0 Number = 5 print(''' Welcome to WORD GUESS ''') s(3) mil = input(""" DIRECTIONS (PRESS ENTER TO CONTINUE) 1. Pick a difficulty 2. Enter 5 words that the computer can pick from 3. Wait while the computer picks a random word from...
eab3ac8186e27780132968e440971fe16ee953a1
mahimadubey/leetcode-python
/permutations_ii/solution.py
873
3.875
4
""" Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. """ class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype:...
5a73be9fbd1a764082fc2186e7ded136180be764
Alex19-91/Python
/Lesson_4/4.2.py
142
3.875
4
my_list = [1,2,3,4,4,5,4,5,6,7,6,8] new_list = [my_list[num] for num in range(1,len(my_list)) if my_list[num]>my_list[num-1]] print(new_list)
bda2758917fd44cc7424a561e1d97ebee1884397
cherryzoe/Leetcode
/110. Balanced Binary Tree.py
4,098
4.375
4
# Given a binary tree, determine if it is height-balanced. # For this problem, a height-balanced binary tree is defined as a binary tree # in which the depth of the two subtrees of every node never differ by more than 1. 解题思路 - 一般BST的问题,首先往divide & conquer的思路去想 - 一棵二叉树是不是平衡二叉树 => 左子树是不是平衡二叉树?右子树是不是平衡二叉树? - 如果任意一颗子树不平...
18e5f032a9a4af2e6ac9518c1951834ffea7d74e
RakeshSuvvari/Joy-of-computing-using-Python
/birthday_paradox.py
921
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 12 20:56:04 2021 @author: rakesh """ import random import datetime birthday=[] i=0 while(i<120): year = random.randint(1895,2020) if(year%4 == 0 and year%100 != 0 or year%400 == 0): leap = 1 else: leap = 0 month = ra...
4151019dbc37dea946e8a2aea7518fd329cd29d0
anselb/Syllables-and-Graphs
/graph.py
33,046
3.9375
4
#!python from collections import deque import random import string class Vertex(object): """Helper class that defines vertices and vertex neighbors.""" def __init__(self, vertex_id): """Initialize a vertex and its neighbors. id: a number or string to identify the vertex neighbors: s...
19093b25c9d014975345e52337c321a38d55f0ee
Harpreet456/pcoders
/snakewatergun.py
1,455
3.953125
4
import random print("WELCOME TO SNAKE,WATER,GUN GAME:-)") user_pt=0 comp_pt=0 for i in range(1,11): lst = ["Snake","Water","Gun"] comp = random.choice(lst) user = input("Enter your choice i.e\nSnake\nWater\nGun\n") if(comp==user): print("NO WIN,NO LOSE") user_pt+=0 com...
9e3add3960506fe5e004d0760d63aba6e0455a9d
Amirtha2000/Amirtha-varshini
/primechk.py
157
3.96875
4
#!/bin/python a=int(input("Enter a number efor prime check")) fac=0 for i in range(1,a-1): if(a%i==0): fac=1; if(fac==0): print("ITS A PRIME")
93d98e233231ae589f1c5b4a9c11172559429e54
JBreidfjord/minigames
/guessthenumber.py
734
4.125
4
import random num = random.randrange(101) print('Number is between 0 and 100\n') guess = None score = 0 while guess != num: while not guess: try: guess = int(input('Guess the number: ')) if 0 <= guess <= 100: score += 1 else: print('Sor...
5fa19e29fcd6562d3b9680291d006731c85fff0a
ronaldjayrjover/pythonBootcamppractice
/looping_in_python/unluckyNumber.py
636
4.09375
4
''' loop through number 1-20 for 4 and 13, print "x is unlucky" for even numbers, print "x is even" for odd numbers, print "x is odd" ''' for x in range(1,21): if x == 4 or x == 13: print(f"{x} is unlucky") elif x % 2 == 0: ### modulo(%) means if there is no remainder then its even print(f"{x} ...
b4dca63ceeee2ab71a08e0971f7a880f9883c61c
Poornimaaj/PYTHON
/upper.py
167
4.15625
4
string=input("Enter string:") count1=0 for i in string: if(i.isupper()): count1=count1+1 print("The number of uppercase characters is:") print(count1)
acffb02c3da756efe8eeec8bcf429b54de563e8c
ShwetaD123/MyPythonDOC
/Factorial.py
1,356
4
4
''' With recurtion function ''' def fact(n): if n==1: return n else : return n*fact(n-1) # print(fact(10)) ''' With IF Else statement ''' ''' def facto(num): factorial = 1 if num<0: print('Factoraial is not found for negative number :',num) elif num == 0: ...
b518c33620a9358b529bbf3f1e795e636a34d69f
ahmad174/python1
/python.py
1,863
4.09375
4
"""Q1""" print("Hello") print("\tHello") print("\t\tHello") """Q2""" print(" Orange Academy "*20) """Q3""" x=float(1) y=float(2.8) z=float('3') w=float('4.2') print(x,y,z,w,sep='10') """ 1.0102.8103.0104.2 """ print(x,y,z,w,sep='---') """ 1.0---2.8---3.0---4.2 """ """Q4""" a=int(input('Press First Num...
4b00951049611df92143c7ddbf045b4f25cf9286
Peter-Feng-32/Algo-and-ML
/Python/RandomTopics/lambda.py
253
4.09375
4
# Anonymous functions - lambda # Key Points: # No name # One expression # Any number of arguments # Lambda function doesn't have a name, # Instead we assign it(as an object) to a variable. f = lambda a, b: a + b result = f(5, 6) print(result)
308065db17a29ca7faaab080cd997563145e76a8
ParshvaTimbadia/Aglorithms
/Easy/Closest element in Binary Search Tree.py
2,569
4.15625
4
#Problem Statement: https://www.geeksforgeeks.org/find-closest-element-binary-search-tree/ *** The code itself is quite simple to follow. The important thing to note here is that in BST all the values to the left are smaller than the parent, whereas all the value to the right are greater than the parent. So, when yo...
2467d880ae64a433e5d3ce40bc6b60aa4b346a03
trinnawat/leetcode-problems
/find-median-from-data-stream.py
1,248
3.71875
4
''' https://leetcode.com/problems/find-median-from-data-stream/ ''' class MedianFinder: def __init__(self): """ initialize your data structure here. [1, 3, 4] [7, 13, 20] max_heap will maintain left order [-4, -3, -1] min_heap will maintain right order [7, ...
44c31268e4267fc67daf6f35aebae0d80ae3eb70
rai8/python-crash-course
/dictionaries.py
685
3.90625
4
#there are more like Objects syntax in Javascript #the keys should be unique-- no duplicates monthConversions={ "Jan":"January", "Feb":"Febraury", "Mar":"March", "Apr":"April", "May":"May", "Jun":"June", "Jul":"July", "Aug":"August", "Sep":"September", "Oct":"October", "Nov":...
43d0005fa6e7e0cb74fcf5e7fe999a934b941231
dustinpfister/examples-python
/for-post/python-control-flow/s1-if/expresions.py
172
3.5
4
x = 5 y = 10 a = x < y print( a, type(a).__name__ ) # True bool b = x > y print( b, type(b).__name__ ) # False bool c = x == y print( c, type(c).__name__ ) # False bool
c1c99d4d3c8c28142501b3594a90b0658cd6ebc3
TheAlgorithms/Python
/project_euler/problem_587/sol1.py
2,671
3.5625
4
""" Project Euler Problem 587: https://projecteuler.net/problem=587 A square is drawn around a circle as shown in the diagram below on the left. We shall call the blue shaded region the L-section. A line is drawn from the bottom left of the square to the top right as shown in the diagram on the right. We shall call th...
e15282203c4b3bce16039dc4fd4095ae8c775cbb
alinabalgradean/HackerRank
/leap_year.py
462
4.4375
4
def is_leap(year): """Checks if a year is a leap year or not. A year is a leap year if the following conditions are met: 1) the year is divisible by 4 AND 2) the year is not divisible by 100 but it is with 400 Args: year [int]: The year to calculate Returns: leap [B...
6a2f73fb19182c0c98bcf1f62fd25e7e2c745193
carlhinderer/python-exercises
/daily-coding-problems/problem448.py
437
3.71875
4
# Problem 448 # Hard # Asked by Google # # Given an array of strictly the characters 'R', 'G', and 'B', segregate the values # of the array so that all the Rs come first, the Gs come second, and the Bs come # last. You can only swap elements of the array. # # Do this in linear time and in-place. # # For examp...
1fdcea0b8dd9bddec4d43d995f0113aabdcf0cd6
Andmontc/holbertonschool-interview
/0x00-lockboxes/0-lockboxes.py
584
3.9375
4
#!/usr/bin/python3 """ Lockboxes Method """ def canUnlockAll(boxes): """ Determines if all the boxes can be opened """ keys = [0] for key in keys: # loop through the keys box = boxes[key] for nkey in box: # get the new key in each box if nkey not in keys an...
b45818eec8a70c1dd4368aaa1638391a601e8673
PowerDos/Study-Notes
/Python/基础知识/if elif.py
140
4
4
# if elif num = int(input('input number:')) if num > 9: print('大于9') elif num == 9: print('等于9') else: print('小于9')
36d1096ebc8489014edd9689e81f2717e4569467
moisesquintana57/python-exercices
/tema_12_operadores_objetos/ejer1.py
925
4.125
4
# definimos nuestra clase lista class Lista: # inicializamos nuestra clase # como atributo utilizaremos una lista def __init__(self,lista): self.lista=lista # método para imprimir la lista def imprimir(self): print(self.lista) # redefinimos la suma def __add__(self,valor): n=[] for x in range(len(sel...
f1628f68430b02b844711bd2655a360e0c904030
jacobovsky/numeric_matrix_processor
/processor.py
6,404
4.03125
4
import sys import copy def display_menu(menu='MAIN'): if menu == 'MAIN': print("\n1. Add matrices\n" "2. Multiply matrix by a constant\n" "3. Multiply matrices\n" "4. Transpose matrix\n" "5. Calculate a determinant\n" "6. Inverse matrix...
e5d6e8df73776fa74063a00b8411c70f5bae4b67
sj9x/Coding-Example-Game-Blackjack
/Blackjack_Unicode/Blackjack_Main.py
3,813
3.890625
4
#1. MAKE ALL THE FEATURES for the player such as update score # see if the current hand or all hands are already lost or bust, update chips # as functions within the class # 2. We do not need to pass deck1 everytime if we do p1.deck = deck1 and d1.deck1=deck1 # it will be fine. Also look a class inheritence # If we mak...
203dbe82cfca57af84d715390299ecedeba5a333
jmerizia/google_foobar
/minglish_lessonTRIAL1.py
2,593
3.6875
4
# Minglish Lesson (TRIAL) def answer(words): # Goal: For each pair of consecutive words, # find the largest common prefix. Subtract this prefix # from its respective word and compare the next letter. # Combine all of these letter comparisons import os order = [] for i in range(len(words) - ...
2575ce48428f7520af625f7f2c74765e3e0e2d63
Jackthebighead/recruiment-2022
/algo_probs/newcoder/classic/nc53.py
528
3.625
4
# 题意:删除链表的倒数第n个节点 # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @param n int整型 # @return ListNode类 # class Solution: def removeNthFromEnd(self , head , n ): # write code here # 三指针 pre,cur,fast = None,head,...
007d9f05b741a07d0c7f457bb307a3ad25b5be02
Pabitha-1/python
/B47.py
106
3.546875
4
p=[] num=int(input()) for i in range(0,num): q=int(input()) p.append(q) p.sort() print(p[0],p[num-1])
4cd5fb8a476aa346c8e22688d1610bea5d20c532
BrunoSilvaBR/PythonExercicio
/ex017.py
400
4.0625
4
from math import sqrt CO = float(input('Qual é o cateto oposto ?')) CA = float(input('Qual é o cateto adjacente ?')) HI = sqrt(CO**2+CA**2) # HI = (CO**2+CA**2)**(1/2) --- > SEM IMPORTAÇÃO # HI = math.hypot(CO,CA) ---- > OUTRA DE SE FAZER print(' O comprimento do cateto oposto é {}\n O comprimento do cateto adjac...
fdf13497674d5fbae1bfcab9efad380706e85a58
jmccardle/AdventOfCode2020
/puzzle21.py
4,778
3.640625
4
##The seat layout fits neatly on a grid. Each position is either floor (.), ##an empty seat (L), or an occupied seat (#). For example, the initial seat ##layout might look like this: ## ##L.LL.LL.LL ##LLLLLLL.LL ##L.L.L..L.. ##LLLL.LL.LL ##L.LL.LL.LL ##L.LLLLL.LL ##..L.L..... ##LLLLLLLLLL ##L.LLLLLL.L ##L.LLLLL.LL ## #...
bff7ab216e05da785402ec6dfc0307e32a1249f5
OneMoreSecond/WizardGame
/strategy/human.py
2,868
3.578125
4
from game.card import SuitCard from typing import Dict, Set, List, Optional from game import Card, Board, Suit from helper import value_check, print_separator from .strategy import Strategy __all__ = [ 'HumanStrategy' ] class HumanStrategy(Strategy): def __init__(self, player: int, trump: Optional[Suit], ha...
bccbc534c4ccfe500e824bc4a25669c76f1e86c9
tj1234567890hub/pycharmed
/cubod.py
115
3.78125
4
res=0 def cubed(numb): numb=int(numb) res = numb ** 3 return res res=cubed(5) print("Result is ", res)
92fc3b38cd327b222072a75ec6c19624addd0150
raghulrider/boredom_python
/list_overlap.py
224
3.5625
4
import random a = random.sample(range(1,20),19) b = random.sample(range(1,25),24) c = [x for x in a if x in b] result = [] for element in c: if element not in result: result.append(element) print(c) print(result)
7364f05eb422c551add2040ec5a960ca37bb3938
hmoshabbar/ATM_Machine_Project_Using_Python
/nested_loops_atm_project.py
4,248
4
4
# Nested loops Program for a bank ATM: import time print "......................Welcome To SBI ATM....................." restart=("Y") chances=3 Account_balance=5000.00 while (chances>=0): PIN=int(input("Enter Your 4 Digit PIN:")) if PIN==(1234): #if PIN==(1234) or (1457): #if PIN==(1234):...
7b76e30d9375316cf4fc5cade5297ec65d1dc3aa
Janardhanpoola/100exercises-carbooking
/ex_24.py
227
3.5625
4
import sqlite3 con=sqlite3.connect("database/database.db") cursor=con.cursor() cursor.execute("SELECT country FROM countries where area>2000000") rows=cursor.fetchall() print(rows) con.close() for i in rows: print(i[0])
d8f35c9f84c93b33fbd85057939ddc2e04986c96
muzafferAyd/Python-basic-projects
/matrisToplama.py
245
3.65625
4
# -*- coding: utf-8 -*- liste1=[[1,2,3],[1,2,3],[1,2,3]] liste2=[[3,3,3],[3,3,3],[3,3,3]] sonuc =[[0,0,0],[0,0,0],[0,0,0]] for x in range(0,3): for y in range (0,3): sonuc[x][y]= liste1[x][y]+liste2[x][y] print(sonuc)
653868a475618b3b3f6c9a4ba7da849c4c465e3d
zarkaltair/Data-Scientist
/Coursera_courses/OOP_and_design_patterns/03_week/Assignments/01_Decorator/deco_test.py
3,317
3.65625
4
# from inspect import isabstract from abc import ABC, abstractmethod # import pdb class Hero: def __init__(self): self.positive_effects = [] self.negative_effects = [] def get_positive_effects(self): return self.positive_effects.copy() def get_negative_effects(self): retu...
637449cd7c6b0abd9e84cff8b3b8daa0c166f541
dmconard/Rack-O
/Project3b.py
7,914
3.921875
4
""" CS 115 Project 3 - Rack-O! Author: Dana Conard Description: Whoppppp """ import sys import random numCards = 60 # Total number of cards rackSize = 10 # Number of cards in player hands def get_top_card(card_stack): """ Gets the top card from any stack of cards and returns it as an integer. ...
1ea0285c97e9412af6416d05b515c0b319d2a21d
swamyuma/data-structures
/dynamic-programming/generate-fibonacii.py
1,426
4.3125
4
# what is a fibonacci sequence? # https://en.wikipedia.org/wiki/Fibonacci_number # Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. # sequence: 1 1 2 3 5 8 ... # f(5) # / \ # f(4) f(3) #...
631297a44dee7dd85236b605f80eba3a859ff12e
GrupoAzao/Z0
/TestesSW/hack2mif.py
1,536
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Curso de Elementos de Sistemas # Desenvolvido por: Luciano Soares <lpsoares@insper.edu.br> # Data de criação: 5/04/2017 import argparse import os # rotina para traduzir de HACK para MIF def traduz(nome_arquivo): with open(nome_arquivo, 'r') as arquivoHack: hack = ...
328f682b2930852de314b4b183efeecc54f28bc6
BravoChos/DataStructure
/Recursion/Homework/Problem1/python/Problem1.py
609
4.125
4
""" Problem 1 Write a recursive function which takes an integer and computes the cumulative sum of 0 to that integer For example, if n=4 , return 4+3+2+1+0, which is 10. This problem is very similar to the factorial problem presented during the introduction to recursion. Remember, always think of what the base case w...
fe128c3e4217e598d3c76e4fd82af65ca0da004b
Vigneshg98/Data-Structures-Concepts
/levelordertraversal.py
753
3.8125
4
from queue import Queue class node: def __init__(self,data): self.data=data self.left=None self.right=None def levelorder(root): if root is None: return q=Queue() q.put(root) while(1): nodecount=q.qsize() if(nodecount == 0): ...
d62fe8ddae74ebe96d8a6d6922ff2f1e8d2552fb
Renato0402/Uri-Online-Judge
/python/uri2709.py
712
3.703125
4
if __name__ == '__main__': while True: try: entrada = int(input()) numbers = [] number = 0 checkPrime = 0 for i in range(0,entrada+1): numbers.append(int(input())) for i in range(len(numbers)-2,-1,-numbers[len(numbers)-1]): number+=numbers[i] ...
99f0e630c6ac663ef2f412b460b954afa69e1e9a
mell00/code-samples
/Python/console/os.py
5,484
3.515625
4
#OS MODULE# import os #Return list of attributes and methods of an object: dir(object_name[index_value]) #Return current working directory of a process: os.getcwd() #Navigate to a file path: os.chdir("filepath_excluding_module_os") print(os.chdir()) ##Prints 'filepath/module_os'## #Return list of files and folders...
1feb23418c9a21d64640872fc82f6c1e90f38692
miblazej/codes
/Python/Python_Crash_Course/Python35/Hello World1.py
925
3.890625
4
# this is a commend in phyton name = "eric" print("Hello " + name.title()+",would you like to learn some Python today") print(name.lower()) print(name.upper()) print(name.title()) name1 = "julius caesar" print("Once "+ name1.title()+" said: As a rule, men worry more about what they can't see than about what they can"...
8f763dc1fc3d839c3444c2ebbf85aca55f91a7fd
clovery410/mycode
/python/chapter-1/lab3-exec2.py
428
3.984375
4
def hailstone(n): if n == 1: return 1 elif n % 2 == 0: print(n / 2) return 1 + hailstone(n / 2) else: print(n * 3 + 1) return 1 + hailstone(n * 3 + 1) result = hailstone(9) print(result) #The Answer def hailstone1(n): print(n) if n == 1: return 1 ...
ade99c2136bc88ba88719c7c4307a729e6964e3b
victorsaad00/URI---PYTHON
/1011.py
105
3.859375
4
R = float(input()) pi = 3.14159 volume = float((4*pi*(R*R*R))/3) print("VOLUME = %0.3f" %volume)
340774f277a9dbbfb1aef0c16293ba3a865fe792
njustbyq/Algorithms
/Python/1.1.py
1,589
4.03125
4
""" 如何实现链表的逆序 """ class Node: def __init__(self, data, next): self.data = data self.next = next class SingleLink: def __init__(self, head): self.head = head def reverse(link: SingleLink): if link.head is None or link.head.next is None: return None cur = link.head.next ...
62c89de420fc5439ab419e4b7efe799cd7c19d96
Yelp/PyStaticConfiguration
/staticconf/readers.py
4,917
3.765625
4
""" Functions to read values directly from a :class:`staticconf.config.ConfigNamespace`. Values will be validated and cast to the requested type. Examples -------- .. code-block:: python import staticconf # read an int max_cycles = staticconf.read_int('max_cycles') start_id = staticconf.read_int('...
b0369c5d4ee97c748a487b8a7c4f15d915cb1b1a
jkbockstael/projecteuler
/euler014-proc.py
634
3.671875
4
#!/usr/bin/env python3 # Problem 14: Longest Collatz sequence # https://projecteuler.net/problem=14 import sys def euler014(bound): best_start = 0 best_length = 0 for start in range(1, bound): number = start length = 0 while number != 1: number = number // 2 if number ...
b5d5c25d75cced8bdfd281754ed0bd0fe3735d48
leo-skinner/CursoEmVideoPython
/CursoEmVideo/Mundo1/Exercicios/Exe022_Upper_Lower_Split.py
767
4.28125
4
#Crie programa que leia o nome completo e mostre: #- O nome com Uppercase #- O nome com Lowercase #- Quantas letras ao no total, sem considerar espaços #- Quantas letras tem o primeiro nome. nome = str(input('Digite seu nome completo: ')).strip() #para eliminar possíveis espaços no início e final da string. p...
4e1850ff29da36905c31b0ed02306895d80361c9
gowthammk/Leetcode-January2021-Daily-Challenges
/Day 6.py
747
3.734375
4
# Kth Missing Positive Number # # Solution # Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. # # Find the kth positive integer that is missing from this array. # # # # Example 1: # # Input: arr = [2,3,4,7,11], k = 5 # Output: 9 # Explanation: The missing positive integer...
279ba841b7ee227bc88b0924b93e8386fcb99fb0
RaihanHeggi/pythonProgramChallenge_40
/Fifth Challenge (Multiplication and Exponential App)/Multiplication and Exponent Table App.py
878
4.40625
4
import mpmath as mp print("Welcome to the Multiplication/Exponent Table App\n") #getting data name = str(input("Hello, what is your name: ")) name = name.title().strip() number = float(input("What number would you like to work with: ")) message = name + ", Math is cool!" #calculate multiplication the print ...
24d99a3d6b42db663a18848edcaa3116c28030a8
Tiago1704/VariosPython2
/Programa1.py
1,367
3.875
4
import random def listaAleatorios(n): for i in range(n): lista[i] = random.randrange(0,n) return lista def listarLista(n): for i in range (n): print (lista[i]) def Quicksort(lista,inf,sup): if (inf<sup): I=inf J=sup pivot=lista[inf] ...
8517d5c9665290b9a622e5682918b8215478bbfd
colbeezy/reporting-tool
/reporting_tool.py
1,687
3.640625
4
#!/usr/bin/env python """using Python 2.7""" import psycopg2 def top_articles(): """ Returns the 3 most-viewed articles of all time and the number of views they've received. """ database = psycopg2.connect("dbname=news") cursor = database.cursor() cursor.execute( """SELECT * ...
fabfb3bb920c510e9a8605c1224ffd04602b198c
araschermer/python-code
/Web scraping and automation/web scraping (beautiful soup)/scraping empire best 100 movies list/main.py
1,412
3.5625
4
from bs4 import BeautifulSoup import requests import re URL = 'https://www.empireonline.com/movies/features/best-movies-2/' response_text = requests.get(URL).text soup = BeautifulSoup(response_text, 'html.parser') # print(soup.prettify()) # in the response we find (by looking up any number between 1 and 100; since the...
30e50d4ca7ca4db4d7c3e49e6b7466a4a9fc4a19
PLUTOLEARNS/computerprogramsreal
/if percentage 18072020.py
281
4.21875
4
# this is using the elif statement. mr = float(int("Enter your percentage : ")) if 90 <= mr < 100: print ("Your Grade is A+.") elif 80 <= mr < 90: print ("Your Grade is A.") elif 60 <= mr < 80: print ("Your Grade is B.") else : print ("You have failed.")
4f1d97c2aee9a6d058c3e39a7098ada9b47b1cd5
Alexv035/AlgorithmsPyton
/Lesson3/Les_3_Task_1.py
427
3.515625
4
# Task 1 # В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. Примечание: 8 разных ответов. num = [0] * 8 for i in range(2, 100): for y in range(2, 10): if i % y == 0: num[y - 2] += 1 for i in range(2, 10): print(i, ' - ', num[i - 2])
cd08d64e1a51b68d1e4edd230cd52e71cf77da04
cookie-yang/machine-learning_pacman
/search.py
7,032
4.15625
4
""" In search.py, you will implement generic search algorithms which are called by Pacman agents (in searchAgents.py). """ import util class SearchProblem: """ This class outlines the structure of a search problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class...
f8260f0e914aef0339a1e7ffac522d0aa206b8e7
a8ksh4/junk
/Python/examples/EXAMPLES/fmt_params.py
571
4.03125
4
#!/usr/bin/env python import sys person = 'Bob' age = 22 print "{0} is {1} years old.".format(person, age) print "{0}, {0}, {0} your boat".format('row') print "The {1}-year-old is {0}".format(person, age) print "{name} is {age} years old.".format(name='Bob',age=22) print "{name} is {age} years old.".format(name=perso...
e8c9c25b5af1b598650108c2c5e49ffa1e70699f
subhakarks/UC-DSA
/P2/p3_rearrange_array_digits.py
1,873
3.90625
4
#!/usr/bin/env python3 """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ import unittest def merge_sorted_lists(left, right): l_idx = 0 r_idx = 0 merged = [] while (l_idx < len(le...
40b011babd06da872f226973b3912c8b30446dd9
QitaoXu/Lintcode
/Alog/class9/exercises/medianOfKSortedArrays.py
2,244
3.546875
4
class Solution: """ @param nums: the given k sorted arrays @return: the median of the given k sorted arrays """ def findMedian(self, nums): # write your code here if not nums: return 0.0 n = sum([len(arr) for arr in nums]) ...
1d803158f1f6698fac259b61b66d9673febbb8d3
shengyuhappy/01-python-kids
/WhatsMyGrad.py
278
3.890625
4
grade = eval(input("输入你的分数(0-100): ")) if grade >= 90: print("你得到了A! :)") elif grade >= 80: print("你得到了B!") elif grade >= 70: print("你得到了C!") elif grade >= 60: print("你得到了D!") else: print("你得到了F. :( ")
bbe65aafdd0a740868ff2630b4a5016b886f4d02
Jay0421/scm-ninja.github.io
/sample.py
393
4.21875
4
''' 1. Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. ''' def list_end(a): return a[0], a[-1] print(list_end(a = [5, 10, 15, 20, 25])) # 2 def ar...
cb68341d069a34c98e383ac635da1c391c50e4ca
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4354/codes/1613_1803.py
267
3.65625
4
senha = int(input("digite uma senha de 4 digitos: ")) d1 = senha // 1000 d2 = (senha % 1000) // 100 d3 = ((senha % 1000) % 100) // 10 d4 = ((senha % 1000)% 100) % 10 d1 = d1 * 5 d2 = d2 * 4 d3 = d3 * 3 d4 = d4 * 2 somatorio = (d1 + d2 + d3 + d4) % 11 print(somatorio)
eef931660677825f01aa1d278570520042007a54
ly21st/my-algorithm
/python-vsc/geekbangtrain/week01/1c/1c_PageTurn.py
1,104
3.515625
4
# 翻页的处理 import requests from bs4 import BeautifulSoup as bs # bs4是第三方库需要使用pip命令安装 # Python 使用def定义函数,myurl是函数的参数 def get_url_name(myurl): user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36' header = {'user-agent':user_agent}...
2e1b9c9440cd6d24f4f1c78a711f48fe3f0eb311
egin10/speech_recognition
/speech_test.py
2,548
3.53125
4
import speech_recognition as sr import webbrowser as wb import urllib.request import urllib.parse import re r = sr.Recognizer() result = '' with sr.Microphone() as source: r.adjust_for_ambient_noise(source) # here while True: print("Say something!") audio = r.listen(source, phrase_time_limit...
ea8b0ca8ab48118bac8386d4d99a653b2f319410
UWPCE-PythonCert-ClassRepos/Wi2018-Online
/students/ScottL/lesson03/lists.py
1,648
4.40625
4
#!/usr/bin/env python3 # Scott Luse, List Lab, Feb 04, 2018 # SERIES-1 fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] print(fruit_list) '''starting with a set list of fruit, ask the user for another fruit and append''' user_fruit = input("Enter the name of a new fruit (Avacado): ") fruit_list.append(user_fru...
a0b7594ce86cd595b3d2bf1dd2e00e60cce6be75
brunadelmourosilva/cursoemvideo-python
/mundo1/ex034_aumentomultiplo.py
384
3.765625
4
#ler o valor do salario #se for maior que 1.250 calcule um aumento de 10% #se for igual ou inferior calcule um aumento de 15% sal = float(input('digite o valor do salário para calcular seu aumento: ')) if sal > 1250: a = sal * 1.10 print('o novo salário é de R${:.2f}'.format(a)) if sal <= 1250: b = sal * ...
4efef75a306fada2ae343a335656f973fb19e8ff
csJd/oj-codes
/leetcode/92.reverse-linked-list-ii.py
1,160
3.921875
4
# # @lc app=leetcode id=92 lang=python3 # # [92] Reverse Linked List II # # https://leetcode.com/problems/reverse-linked-list-ii/description/ # # algorithms # Medium (34.61%) # Likes: 1340 # Dislikes: 97 # Total Accepted: 205.1K # Total Submissions: 577.2K # Testcase Example: '[1,2,3,4,5]\n2\n4' # # Reverse a li...
25c6098258b55b45cd63a8656a97a563981f5ac2
xingweiyong/python_code
/py_TemporaryFile.py
1,543
3.984375
4
#coding:utf-8 #python tempfile ''' import tempfile 如何你的应用程序需要一个临时文件来存储数据, 但不需要同其他程序共享,那么用TemporaryFile 函数创建临时文件是最好的选择。其他的应用程序 是无法找到或打开这个文件的,因为它并没有引用 文件系统表。用这个函数创建的临时文件,关闭后 会自动删除。 ''' import os import tempfile def make_file(): '''创建临时文件,不过创建后,需要手动移除 os.remove(file) '''...
4c2dbdbd53ea06834589f0b75960c90c02b6eb63
MyrinNaidoo12/ComSci
/CSC1015F/Assignmet1/triangle.py
388
4.28125
4
#Program to calculate area #Myrin Naidoo # NDXMYR001 import math a = eval(input("Enter the length of the first side: ")) b = eval(input("Enter the length of the second side: ")) c = eval(input("Enter the length of the third side: ")) s = (a+b+c)/2 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) print("The area of ...
62a775faace24dee529c5c9b7a6b73ba0082f89c
Mallets/SimPype
/simpype/random.py
4,844
3.765625
4
""" :class:`~simpype.random.Random` is a custom dictionary accepting the following format as value: .. code-block :: python sim = simpype.Simulation(id = 'test') myrand = simpype.Random(sim, { initial_time : lambda_function ... }) Where each dictionary element is so defined: * ``initial_time`` is the elemen...
944f5f280542a465719b2f5892b3372215b66879
nartojunior/ppgti0006-atividades
/atividade-lista4/q4-done.py
755
3.59375
4
class Turma: # Construtor def __init__(self): self.alunos = dict() self.size = 0 pass pass # ToString def __str__(self): return str(self.alunos) def addAluno(self, nome, cpf): self.alunos[nome] = cpf self.size += 1 pass def getCPF(s...
83872c77cadecc5ce9a1143e2c47b104ff7db28a
AntonMAXI/Python_lessons_basic
/lesson06/home_work/hw06_easy.py
4,322
4
4
# Задача-1: Написать класс для фигуры-треугольника, заданного координатами трех точек. # Определить методы, позволяющие вычислить: площадь, высоту и периметр фигуры. import math class Treug(): def __init__(self, A=None, B=None, C=None): self.A = A self.B = B self.C = C print('То...
4d1ed4273be01a911f219f5ac4a921fc7d3dbbfb
ELISA-IE/lorelei_demo
/lorelei_demo/scripts/counter/count_plain_text.py
1,338
3.84375
4
# this script counts term frequency in plain text. It uses space as delimiter. # term frequency is used for morphology analysis import argparse import codecs import sys def count(plain_text): term_frequency = dict() num_lines_processed = 0 for line in codecs.open(plain_text, 'r', 'utf-8'): terms ...
ac62d7df5fbfa2bd188f4e0b5fa655d66e848f77
joyrexus/ldp
/code/lib/python/util/report.py
1,535
3.96875
4
# -*- coding: utf-8 -*- '''Basic printing and reporting utilities.''' def tostring(x): ''' Convert a unicode string, normal string or number value to a UTF-8-encoded string. ''' return (x if type(x) is unicode else str(x)).encode('utf8') def stringify(x, sep="\t"): ''' Convert a stri...
7420749c28c7faee05f12c0e8d5501b25f6c0b32
Kelompok4TI-42-12/Binary-Search
/quizalpro.py
489
3.9375
4
def BinarySearch(list1,key): low = 0 high = len(list1)-1 Found = False while low <= high and not Found: mid = (low+high)//2 if key == list1[mid]: Found = True elif key > list1[mid]: low = mid+1 else: high = mid-1 if Foun...
8f25e6ed816d09d91a1ccc6bcf43a348a25cc277
chava96/metodosNumericos
/newton-raphson.py
475
4.03125
4
# f(x) = x^3 + 2x - 1 # f'(x) = 3x^2 + 2 # f''(x) = 6x #2,4,6,8,10 iteraciones (0,5) [0,5] ... (0,5] o [0,5) #NEWTON - RAPHSON xi = -1 xi1 = 0 xr = 0 N = 10 #Por pasos N for x in range(0,N): #[0,N) print(xr) xr = xr - ((xr**3 + 2*xr - 1)/(3*(xr**2) + 2)) print("La raiz real es: " + str(xr)) #Hasta que sea igual en ...
381df4fe9750835f8c3be0216f2ecb862b57245e
JHeisecke/MantenimientoDeAutos
/Proyecto/Interfaz Caracteres/util.py
3,091
3.890625
4
import os #________________________________Util__________________________________________ #Validadores para distintos casos y necesidades def cls(): """Permite limpiar la consola de python para que sea mas comodo usarla""" os.system('cls') def input_opcion(text, opciones): """ Recibe dos parametros: 'tex...
5c214576c3cbae1b15f894fa1f14e205acae4183
artivnv/learn-homework-1
/if2.py
1,508
4.0625
4
""" Домашнее задание №1 Условный оператор: Сравнение строк * Написать функцию, которая принимает на вход две строки * Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0 * Если строки одинаковые, вернуть 1 * Если строки разные и первая длиннее, вернуть 2 * Если строки разные и вторая с...
84b3c54f03f6928d2f44827769d5ad5d418ce3a3
chanfe/daily-code-challenge
/py_checkio/py_checkio_completely_empty.py
2,495
3.546875
4
# You need to figure if a wellfounded and wellsized iterable is completely empty. # # An iterable x0 is wellfounded if there is no infinite sequence # # x1,x2,x3... such that ... in x3 in x2 in x1 in x0 (where in is meant iteratively, x(n+1) will be encountered while iterating through xn). # A wellfounded iterable is...
0bf7a0c4182c755df3585ba3588766aa13228a90
gustycooper/cpsc110
/code/ch5grades2.py
383
3.796875
4
grades = [88, 79, 62, 95, 82] highest = lowest = grades[0] gradessum = 0 for index in range(len(grades)): gradessum = gradessum + grades[index] if grades[index] > highest: highest = grades[index] if grades[index] < lowest: lowest = grades[index] index = index + 1 print('Ave: ', gradessum...
ddaad2779095b0cbe8e42f8aef93366a53840beb
Lamisa-Musharrat/sample
/python/sal.py
130
3.546875
4
enum=input() ehour=input() esalh=input() esal=float(ehour)*float(esalh) print("NUMBER =",enum) print("SALARY = U$ %.2f"%esal)
bd579d6938ddff0a59d24283e7f3787958b35bac
Sngunfei/algorithms
/sword2offer/IsPopOrder.py
555
3.6875
4
""" 给定两个序列,第一个是压栈顺序,判断第二个序列是否是可能的弹出顺序。 1 2 3 4 5 3 4 2 1 5 1 3 2 """ def isPopOrder(push, pop) -> bool: pop_pos = 0 push_pos = 0 stack = [] while push_pos < len(push): stack.append(push[push_pos]) push_pos += 1 while stack and stack[-1] == pop[pop_pos]: stack.pop(...
b0551e16a65eee138b3b296012e1598386b7ceac
CLCdawn/Hello-world
/PycharmProjects/dataScience/sortList.py
409
3.578125
4
input_string = input()[1:-1] array = input_string.split(',') array = [i.strip() for i in array] try: array = [int(i) for i in array] except Exception as e: array = [str(int(i[1:-1])) for i in array] for i in range(len(array)-1, 0, -1): for j in range(0, i): if array[j] > array[j+1]: temp...
8f72484640ebc62d1f6270f6c650ab8125d2755d
tade147/-
/plus.py
393
4
4
print("Please give me two numbers, I'll plus them.") print("Print 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number == 'q': break seconde_number = input("\nSecond number: ") try: result = int(first_number) + int(seconde_number) print(result) ...
89100f78399d9315b5ec32c5a0daa7debad7f499
EugeneMondkar/hackerrank-code
/Practice_Exercises/002_find_runner_up.py
365
3.625
4
# Problem Link: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_value = max(arr) runner_up = min(arr) for x in arr: if x > runner_up and x < max_value: ...
350711afcbfc7e14775be57285af74bebdc7e294
john27328/stepic_algoritm
/priority_queue.py
2,266
3.546875
4
class PriorityQueue: def __init__(self): self._d = [0,] def insert(self, value): self._d.append(value) self._d[0] += 1 currentIndex = self._d[0] perentIndex = self.perentIndex(currentIndex) while (self._d[currentIndex] > self._d[perentIndex] and currentIndex...
7b348c0edef225588dc5b868a52f36864aaf7962
aca-ml-training/ml_homeworks
/Practical3_Sh/decision_tree.py
7,479
3.859375
4
import numpy as np from collections import defaultdict import builtins class DecisionNode(object): """ DecisionNode is a python class representing a node in our decision tree """ def __init__(self, column=None, value=None, false_bran...
aa74765624809399a13df7d2b3261bba03319ed7
qwerty-123456-ui/pythontuts
/sum8.py
163
4.09375
4
name="isha" age=19 if(name=="isha" and age==19): print("true") else: print("false") if(name=="isha" or age==19): print("true") else: print("false")
f766b1612c450c70e6a2509ee78de10d97f1a746
Tjasa1/advent_of_code_2020
/day3-2.py
1,711
4.125
4
#Advent of Code 2020: Puzzle 3, Part 2 #1 import the data with open("day3.txt", "r") as inputfile: data = inputfile.read() #2 Separates slope into the list of lines slope_in_lines = data.split("\n") slope_height = len(slope_in_lines) #print(slope_height) #3 Separates lines into lists of characters true_slope = [...