blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8e0281a00c02313a9667e7243c2c6457535ea0ad | binderclip/code-snippets-python | /packages/bisect_sp/binary_search_list.py | 1,709 | 4.125 | 4 | import bisect
def reverse_bisect_right(a, x, lo=0, hi=None):
"""Return the index where to insert item x in list a, assuming a is sorted in descending order.
The return value i is such that all e in a[:i] have e >= x, and all e in
a[i:] have e < x. So if x already appears in the list, a.insert(x) will
... |
b14a2758d85cc179536230387134f34b26df5df9 | gr3grisch/awesomePython | /code/command_lines.py | 279 | 3.796875 | 4 | import sys
if __name__ == '__main__':
arguments = sys.argv()
if arguments == 3:
a, b, c = tuple(arguments)
for i in arguments: (
print('%s %s %s' % (a, b, c)))
else:
print('iLLegal number of arguments: must be 3')
|
d93a5e4c86c1b4120a85db352cff3e90b9a4296c | timeisthelimit/IRCServer | /server.py | 6,379 | 3.5625 | 4 | #!/usr/bin/env python3
# Socket code inspired by and taken from RealPython tutorial
# on sockets (https://realpython.com/python-sockets/)
from messageparser import MessageParser
from client import Client
import serverfunctions as sfn
import socket
import selectors
import time
command_handlers = {'JOIN':sfn.handle_JOI... |
fb55ff6cb66e4d4e90f2eef2066c39d256bf8825 | GiovannaPazello/Projetos-em-Python | /Lista 3/Exercicio 6.py | 339 | 3.875 | 4 | '''Faça um programa que leia um número digitado pelo usuário. Depois, informe todos os
números primos gerados até o número digitado pelo usuário.'''
n = int(input("Verificar números primos até:"))
cont=0
nPrimos = []
for i in range(2,n):
if (n % i == 0):
cont += 1
if(cont==0):
nPrimos.append(n)
prin... |
53a254993bba196b165c27623c7ff99882fbcba3 | manhalrahman/Turtle-Module-Shapes | /turtle_polygons.py | 1,058 | 4.40625 | 4 | from turtle import Turtle, Screen
from random import randint
timmy = Turtle()
timmy.color("black") #Need not be there
my_screen = Screen()
# This code moves the turtle upwards a little bit as the shapes will grow downwards and may escape the screen
timmy.penup() #So the we don't see the turtle moving up to the top of ... |
6261e3572a1be749b24a3f76a429b6dfb5634c9e | casheljp/pythonlabs | /examples/4/working_with_lists.py | 502 | 3.828125 | 4 | #!/usr/bin/env python3
lis = [10, 20, 30, 40, 20, 50]
fmt = "%32s %s"
print(fmt % ("Original:", lis))
print(fmt % ("Pop Last Element:", lis.pop()))
print(fmt % ("Pop Element at pos# 2:", lis.pop(2)))
print(fmt % ("Resulting List:", lis))
lis.append(100)
print(fmt % ("Appended 100:", lis))
lis.remove(20)
print(fmt % (... |
279a50786dff9fd06ac053b2a3d2bf4d66e21d5d | apabon03/datacademy-python-cardio | /area-triangulo.py | 1,289 | 3.9375 | 4 | def tipo_triangulo(lado_a, lado_b, lado_c):
if lado_a== lado_b and lado_b == lado_c:
print("El triángulo es equilatero")
elif lado_a != lado_b and lado_b == lado_c:
print("El triángulo es Isósceles")
else:
print("El triángulo es Escaleno")
def area(base, altura):
return (base *... |
55f21f7565072d2a2ff6fd2adc28052c8a41c46b | ruzguz/python-stuff | /8-lists/hangman.py | 2,392 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
... |
692063a16414f4defdc57fdb0e3a08a4c7ae408b | trewto/guitarchoardchanger | /guitar.py | 763 | 3.5625 | 4 |
l = ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"]
l1 = ["Am","A#m","Bm","Cm","C#m","Dm","D#m","Em","Fm","F#m","Gm","G#m"]
print("How many Choard?")
n = input()
n = int(n)
d = []
i = 0
while i<n:
f = input()
d = d + [f]
i = i +1
print("====================")
def scale_up(choard,level):
c = num(choard)
... |
af35ac15ec5b9ec2cd702b72827693d7082e7409 | unmeg/misc-ML | /pytorch-blitz-notes.py | 5,382 | 3.984375 | 4 | """
Notes to self for http://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html
Looking at the network diagram, we take an input that is 32x32x3 and we convolve, downsample
and then spit it out into some fully connected layers.
Let's unpack.
To go from input >> C1, we see a convolution. The input is ... |
71325f81b9817867d79f1fc4ae27fd3a918223d2 | prafulpatel16/python-practice | /python-basics/3_assign_vars.py | 117 | 3.828125 | 4 | a = 5
print("The value of a is:" + str(a))
a = [1,2,3,4]
for i in range(4):
print(a[i], end = "")
|
997e4d9104098fa182eaea1cdd1eac3935052eb1 | mcndjxlefnd/CIS5 | /adder/main.py | 2,350 | 3.609375 | 4 | import tkinter as tk
#import variables
high = 1
low = 0
source = high
def transistor (collector,base):
if base:
return collector
else:
return low
def gate_and (A,B):
return transistor(transistor(source,A),B)
def gate_or (A,B):
if transistor(source,A):
return high
elif transistor(source,B):
return high
... |
775bcbaa02ca25d70ef353757f3dca88b59ab9a8 | srikrishna98/Machine-Learning-Assignments | /perceptron.py | 1,027 | 3.59375 | 4 | def predict(row, weights):
activation = weights[0]
for i in range(len(row) - 1):
activation += weights[i + 1] * row[i]
return 1.0 if activation >= 0.0 else 0.0
# Estimate Perceptron weights using the formula used in class
def train_weights(train, l_rate, n_epoch):
weights = [0.0 for i in range... |
ba469fcaea1709778700ee45ffe097dc16e4dde9 | kiran9k/Assignment2 | /k_way_merge.py | 3,654 | 3.640625 | 4 | #k-way merge sort
#!/usr/bin/python
import math
import time
import random
start=time.time()
def heapify(b,d):
N=len(b)
if(N>1):
h=int(math.ceil(math.log(N,2)))
l=int(math.floor((len(b)/2.0)))
if(h==0):
h=1
for k in range(0,h):
for i in ra... |
92a2bf3ddc5462e043a56e5ee2da66dc027507a8 | flacogabrielc/Selenium_Python | /Clase 3/EjC2_profe.py | 520 | 3.9375 | 4 | nombre= input("Ingrese el nombre: ")
apellido= input("Ingrese el apellido: ")
mate= int(input("Ingrese la nota de matematicas: "))
lite= int(input("Ingrese la nota de literatura: "))
fisi= int(input("Ingrese la nota de fisica: "))
prom= (mate + lite + fisi) /3
print ("El alumno " +nombre + " " +apellido+ " "+" tiene ... |
250551b54b46542f2715fd50d08d0b50b3dfb6e2 | emlynazuma/leetcode-dalico | /290wordPattern.py | 454 | 3.5 | 4 | class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
_s = s.split(" ")
if len(pattern) != len(_s):
return False
seen = {}
seen_r = {}
for p, c in zip(pattern, _s):
if p not in seen:
seen[p] = c
if c not in ... |
2a0e449339b04888eab179e05946b4d5bebec81a | wraikes/pythonds | /ch_1/ex_14.py | 1,864 | 3.546875 | 4 | import random
class Card:
def __init__(self, suit, num):
self.suit = suit #heart; diamond; club; spade
self.num = num #2-10, J, Q, K, A
class Deck(Card):
def __init__(self):
self.deck = []
self.suits = ['H', 'D', 'C', 'S']
self.nums = [str(i) for i in range(2,11)] + ['J... |
05c7ec1410234df904791559cf5353622dfe7cb6 | Capoqq/InteligenciaComputacional | /primer taller/punto23.py | 880 | 4.09375 | 4 | dineroInicial = 1000000
compra = int(input("De cuento es el valor de su compra: "))
if compra < 500:
dineroInvertido = compra*0.7
credito = compra*0.3
interes = credito*0.2
print(f"Esta es la cantidad de dinero a invertir {dineroInvertido} ")
print(f"Este es el valor del credito { credito }")
pr... |
281b2cb47ab2c3fa7fcf47f454268689c87367ec | HenryDavidZhu/PyGame-Space-Invaders | /spaceinvaders.py | 5,421 | 3.84375 | 4 | '''
PyGame remake of Space Invaders
Author: Henry Zhu
Date: 07/18/16
'''
from pygame import *
import random
import sys
class Sprite:
'''
A Sprite class that can initialize a sprite based on an image, and display it.
Parameters:
filename -> the path of the image to be used
... |
878f9f3e59bd52aa97d7dc5934e9f2e5a344538c | Almaz97/hackerrank | /basic_data_type/nested_lists.py | 720 | 3.859375 | 4 | from operator import itemgetter
if __name__ == '__main__':
students = [["Harry", 23.3], ["Benny", 23.3], ["Almaz", 32.3], ["Sarah", 11.1]]
# for _ in range(int(input())):
# name = input()
# score = float(input())
# students.append([name, score])
students.sort(key=itemgetter(1), rev... |
dde8d8bdacad05c4b95acad74b66a02168095376 | shrikantayya/shrigh | /fuction.py | 170 | 3.609375 | 4 | def main():
a=eval(input("enter the number"))
while not(a<0):
print(list((range(a))))
break
else:
print("error")
main() |
ecb20e18ee8a637d44e24d9ba9a89d3cb52799a7 | Wave1994-Hoon/data-structure-study-using-python | /Queue1/QueueWithNode.py | 991 | 3.96875 | 4 | class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedQueue(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def isEmpty(self):
return not bool(self.head)
def enqueue(... |
6c0a6fdb8572cd5dce58fd25c4d2cb26dd064172 | venkatesh799/DataStructures-Algorithms | /Hackerrank/Two Strings.py | 600 | 3.9375 | 4 | '''
Given two strings, determine if they share a common substring. A substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring a . The words "be" and "cat" do not share a substring.
Sample Input :
2
hello
world
hi
world
Sample Output :
YES
NO
'''
def twoStrings(s1,... |
5e9d2ab9b98beefe93b7a7827c1365ddf893b978 | pecet/pytosg | /TwitterStatsLib/InsertableOrderedDict.py | 1,030 | 3.640625 | 4 | """ Simple module to add InsertableOrderedDict, variant of OrderedDict with insertafter method """
# pylint: disable=E1101
# disable error while accessing private member of OrderedDict
from collections import OrderedDict
class InsertableOrderedDict(OrderedDict):
""" OrderedDict extending class which adds metho... |
0758a2baf2301e67c2c21425151793f820a223d4 | fahmoreira/L-Python | /cursoemvideo/repo/mundo1/ex021.py | 182 | 3.609375 | 4 | print('==== Desafio 21 ====')
#Faça um programa em Python que abra e reproduza o áudio de
# um arquivo MP3.
from playsound import playsound
playsound(r"C:\\temp\\Calvin.mp3")
|
95d1a6491b9c41adf6b043a1dfda0bc2b39fd38e | fzingithub/SwordRefers2Offer | /4_LEETCODE/1_DataStructure/5_Tree/1_BinaryTree/遍历/层次/JZ32_从上到下打印二叉树.py | 605 | 3.625 | 4 | class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Soluton:
def PrintFromTopToBottom(self, pRoot):
'''
借助队列
:param pRoot:
:return: List
'''
if not pRoot:
return []
Que... |
eb9651d9844134f7cbf28fff5e49ddf062110ef1 | he44/Practice | /leetcode/2020_08_challenge/0808_closest_bst_value.py | 707 | 3.796875 | 4 | from typing import *
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
closest = root.val
... |
98449a278ca1a48a6a133d5e973f5d1b0ca72512 | shifelfs/shifel | /1.py | 285 | 3.5 | 4 | //print the max occurence of number and the number by concatenating the list
l=list(input().split())
a=""
b=[]
for i in l:
a=a+i
for i in range(0,10):
i=str(i)
c=a.count(i)
b.append(c)
m=max(b)
print(m)
for i in range(0,10):
if b[i]==m:
print(i,end=" ")
|
f7f50dbf79380944d492a966b0cbbf0c6e952b31 | kleberandrade/uri-solutions-python-3 | /uri1002.py | 212 | 3.859375 | 4 | # define o valor de pi conforme o problema
pi = 3.14159
# lê a entrada (raio do circulo)
raio = float(input())
# calcula a área do circulo
area = pi * (raio**2)
# exibe o resultado
print ("A=%.4f" % (area)) |
ce14097efe3622d36caf1d1a2f8c9d523c068fb7 | DamienAllonsius/deep_control | /main.py | 1,644 | 3.96875 | 4 | """
Author : Damien Allonsius & Simone Totaro
Date : 29/11/2018
Python Version : 3.6
Main function for deep control.
Take a PDE equation (for example parabolic)
and discretize it. For the moment : dimension space = 1.
The code works this way:
_ Select an initial condition on the mesh
_ Take a random control v
_ Take... |
40ddc4c2d50386dad8848775201bdf454db2cc9e | shadowstep666/phamminhhoang-labs-c4e25 | /labs3/homework/f-math-problem/freakingmath.py | 571 | 3.59375 | 4 | from random import *
from calc import eval
def generate_quiz():
# Hint: Return [x, y, op, result]
x=randint(0,9)
y=randint(1,9)
error=randint(-1,1)
op=choice(["+","-","*","/"])
result=eval(x, y,op) + error
return [x, y, op, result]
def check_answer(x, y, op, result, user_choice):
if u... |
7389f37d48a1da47b0d589ad33bdce627437bc73 | robinyms78/My-Portfolio | /Exercises/Python/Learning Python_5th Edition/Chapter 4_Introducing Python Object Types/Examples/Dictionaries/Missing Keys/Example3/Example3/Example3.py | 168 | 3.796875 | 4 | D = {"a": 1, "b": 2, "c": 3}
# Index but with a default
value = D.get("x", 0)
print(value)
# if/else expression form
value = D["x"] if "x" in D else 0
print(value) |
f6101ade3db39ef2656af5e50efc30373890221d | PDXCodeGuildJan/KatieCGBootcamp | /book_work_through.py | 349 | 4.0625 | 4 | def temp_converter():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees fahrenheit. :)")
calculator()
def calculator():
answer = eval(input("Enter an expression: "))
print(answer)
def fact(n):
if n == 0:
return 1
... |
023cc1ff4de2107c91ddae8dc32b7fb9f9e31eb3 | Tech-Amol5278/Python_Basics | /c19 - working with OS/os module part-2.py | 719 | 3.8125 | 4 | # OS module part 2
# to get the folder-subfolders and files from given directory
import os
import shutil
x_dir = os.walk(r'D:\amol_lap_data\python_tutor')
for current_path,folder_names,file_names in x_dir:
print(f'current path: {current_path}')
print(f'folder name: {folder_names}')
print(f'file name: {file... |
84d5545cc7a794a73a3cd368995000d17403d0ca | JetCrazy/cs | /python/1.3.5.py | 254 | 3.53125 | 4 | def how_eligible(essay):
count = 0
if "?" in essay:
count = count + 1
if "," in essay:
count = count + 1
if "!" in essay:
count = count + 1
if "\"" in essay:
count = count + 1
print(count) |
a0e3be65c412ec412191263e0f02848d372f3204 | henryji96/LeetCode-Solutions | /Easy/690.employee-importance/employee-importence2.py | 801 | 3.65625 | 4 | """
# Employee info
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
... |
5e0b5663909a0f778bffa354c3452ff982fc61fe | AneervanCoder/Data-Science-and-Machine-Learning | /Pandas/delete_column.py | 615 | 3.671875 | 4 | import pandas as pd
mydict = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87] }
s=pd.Series(mydict)
print(s)
print("#########################")
#create dataframe
df_marks = pd.DataFrame(mydict)
print... |
7782abbda92e41b3f7f911e7fc709aa4b3b75112 | jainanuj261/hack_2020 | /check_parenthesis.py | 750 | 3.9375 | 4 | def areParanthesisBalanced(expr):
stack = []
for char in expr:
if char in ["[", "(", "{"]:
stack.append(char)
else:
if not stack:
return False
curr_char = stack.pop()
if curr_char == '(':
if char != ')':
... |
131c1698f960bef0eebdea533381a16f20287f0f | MylesAustin13/normal-repo | /03/piglatin.py | 353 | 3.921875 | 4 | def piglatinify(str):
format = ""
if(str[0] == "a" or str[0] == "e" or str[0] == "i" or str[0] == "o" or str[0] == "u"):
format = str + "ay"
else:
format = str[1:] + str[0] + "ay"
return format
testA = piglatinify("thumb")
print(testA)
testB = piglatinify("apple")
print(testB)
testC = p... |
bcf046eda87272fe3d9961f4f586f6af0eab97d7 | bermec/python | /src/projectmodules/text_file.py | 1,495 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: rog
#
# Created: 02/08/2010
# Copyright: (c) rog 2010
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env py... |
2741bc9859de0398494f1bed32d2f224ad5fb9d0 | LizinczykKarolina/Python | /Algorithms/ex8.py | 120 | 3.6875 | 4 | #8. Write a Python program to sort a list of elements using the merge sort algorithm.
def merge_sort(a_list, l, r):
|
f86e5b5a9f86e0b0d7a5b71c715718b47be4f761 | andrew-uwb/TripleDES | /3Des.py | 23,783 | 3.59375 | 4 | #!/usr/bin/python3
import sys
import random
#for bit manipulation
from bitstring import BitArray
#for initial password hash
from Cryptodome.Hash import SHA256
#This class contains all the methods used for encrypting and decrypting with triple DES,
#as well as the methods for generating the key file. Below this class ... |
6b02b7be2571d448479b64e57d0ba8678da10582 | Mihango/hello_python_udacity | /tuples.py | 272 | 3.609375 | 4 | # assigning tuples
dimension = 12, 14, 15
print(dimension)
# destructuring a tuple
length, width, height = dimension
print(f'length: {length} width: {width} height: {height} ')
# compare tuples
tuple_a = (1, 2)
tuple_b = 1, 2
print(f'{tuple_a == tuple_b} {tuple_a[0]}')
|
8b6e91c2a6f92097b74c0b2d471928adea9c6b31 | jgj9883/Data-Analysis | /데이터 분석 프로젝트/analyze/Numpy/Numpy_01.py | 615 | 3.734375 | 4 | import numpy as np
# 배열 가로 축으로 합치기
array1 = np.array([1,2,3])
array2 = np.array([4,5,6])
array3 = np.concatenate([array1, array2])
# print(array3.shape)
# print(array3)
# 배열 형태 바꾸기
array1 = np.array([1,2,3,4])
array2 = array1.reshape((2,2))
# 배열 세로 축으로 합치기
array1 = np.arange(4).reshape(1, 4)
array2 = np.arange(8)... |
ae779f7f29a3c7c2d11e9ba5d1836afaa0b540d9 | NeisserMS/Java-Course-UPAO | /Ejercicios Básicos - Python/Trabajo_Ejercicio8.py | 401 | 3.796875 | 4 |
precio_segundo = 0.25
horas = float(input("Ingrese la cantidad de horas: "))
minutos = float(input("Ingrese la cantidad de minutos: "))
segundos = float(input("Ingrese la cantidad de segundos: "))
total_segundos = horas*3600 + minutos*60 + segundos
costo_total = total_segundos*precio_segundo
... |
03e23adc290cfb44aa687b1361a191a4537eb161 | DahlitzFlorian/why-you-should-use-more-enums-in-python-article-snippets | /colour.py | 197 | 3.6875 | 4 | # color.py
from enum import Enum
class Colour(Enum):
RED = 1
GREEN = 2
BLUE = 3
c = Colour.RED
print(c)
print(c.name)
print(c.value)
print(c is Colour.RED)
print(c is Colour.BLUE)
|
2e3b6fe91e5f4db441dc821862f216c1c068edad | sandeepkumar8713/pythonapps | /26_sixthFolder/02_patching_array.py | 1,665 | 3.703125 | 4 | # https://leetcode.com/problems/patching-array/
# Question : Given a sorted integer array nums and an integer n, add/patch elements to the array such
# that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
# Return the minimum number of patches required.
#
# Example : Inp... |
7e69a844edb608bb562ed0251d9fe54a3436cb50 | tikishabudin/pythonLessons | /day3functions.py | 825 | 3.640625 | 4 | def myFx():
print("This is my function")
def myFx2(dog, dog2, param3):
print("This is the dog: ", dog)
print("This is the other dog: ", dog2)
print("I'm not even sure what this is: ", param3)
print("-"*20)
def myFx3(param1 = "Something", param2 = "Hahahaha", param3 = 42):
print("This is param1... |
5a15bf5b7ba0bb0e5aad1ea98f66604072134e6c | alokjs89/DataScience_Assignment3 | /Acadgild_Datscience_Assignment3.py | 640 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 01:28:29 2018
@author: ALOK
"""
# This python code converts lowercase to uppercase and uppercase to lowercase
#Sample input
myinput = "AltERNating"
#Function that converts lowercase to uppercase and uppercase to lowercase
def switch_lowerupper(string):
... |
ecf94130999a2398f7261d9da9a35b62f42236a3 | vincentlambert/Codewars | /src/langton_s_ant.py | 2,651 | 3.71875 | 4 | def ant(grid, column, row, n, direction=0):
print("[init] grid : %s" % grid)
print("[init] column : %s" % column)
print("[init] row : %s" % row)
print("[init] n : %s" % n)
print("[init] direction : %s" % direction)
for i in range(0, n):
if (grid[row][column]) == 1:
# WHITE
... |
91717c7dc4c079fc6e6554449f1b822a776d0624 | David-Xiang/Online-Judge-Solutions | /210710/LCOF41.py | 1,617 | 3.9375 | 4 | # LeetCodeOffer 41
# Find Median from Data Stream
# Priority Queue
# large_half is small root heap
# small_half is large root heap and all of its elems are negative value
# large_half might store one more elem
from typing import List
import heapq
class MedianFinder:
def __init__(self):
"""
initia... |
0ecec0b841a5f421d43fe31d4ab023f7260b99d7 | cpm205/Machine-Learning | /Udemy/ML A-Z/Machine_Learning_AZ_Template_Folder/Machine Learning A-Z Template Folder/Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/my_cnn.py | 7,169 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 23:04:02 2018
@author: Derek
"""
#Part 1 - Building the CNN
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initia... |
6f01bda382ad3bb0fbeec369c65c8a85ac6007ec | arpita-ak/APS-2020 | /Hackerrank solutions/Medium- Climbing the Leaderboard.py | 987 | 3.921875 | 4 | """
Climbing the Leaderboard: https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(s, scores, a, alice):
uniq=[0]*(s+a)
j=0... |
f46b7eb87bf75c9b94bb5ba2da1a9da5ee064e97 | vitalyryzhkov/vitaly_ryzhkov | /home_work_14_17.py | 1,721 | 4.125 | 4 | # task_14
"""
def is_even(number):
result = number % 2
return result == 0
# if result == 0:
# return True
# else:
# return False
# print(type(is_even(5)))
print("Number is even?:", is_even(int(input("Enter any number: "))))
"""
# task_15
# from math import *
#
# x1 = 1
# x2 = 2
# y1 = 8... |
18e22c5e90d26213b99b93223e15b21ef8611d1d | RoqueFM/TIC_20_21_1 | /suma_gauss.py | 390 | 3.75 | 4 | Python 2.7.18 (v2.7.18:8d21aa21f2, Apr 20 2020, 13:25:05) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> def suma_gauss():
n_final=input("Inserte nmero final: ")
suma_acumulada=0
for cont in range(0,n_final+1):
suma_acumulada=suma_acumulada+c... |
f227e8830b1a31842ec2c0f632f3c481ea632666 | EmonMajumder/All-Code | /Python/PaintCalculator_Remix.py | 1,773 | 4.46875 | 4 | #Don't forget to rename this file after copying the template for a new program!
"""
Student Name: Emon Majumder
Program Title: IT Programming
Description: PaintCalculator_Remix
"""
#Paint Shop Calculator
#Program to calculate the number of gallons of paint required to paint a room, if provided the room dimensions
def ... |
0ecc9f0ba6caae0aa78e00ad8a052e81aed75aaf | thabbott/prisoners-dilemma | /Telepath.py | 1,442 | 3.75 | 4 | from Prisoner import Prisoner
"""
Telepath: a Prisoner who can read (a limited number of opponents') minds
"""
class Telepath(Prisoner):
"""
Track opponents' first two moves and the round number
"""
def __init__(self):
self.iround = 1
self.opp_first_move = True
self.opp_second_... |
4d13996d26a3061d87231b2eaea467d4e264ec4c | Simplon-IA-Bdx-1/the-movie-predictor-nicoOkie | /utils.py | 250 | 3.921875 | 4 | def split_name(name):
name_list = name.split(" ")
for name in name_list:
firstnames = (len(name_list) - 1)
firstname = " ".join(name_list[:firstnames])
lastname = name_list[firstnames]
return (firstname, lastname)
|
bdd7aa12a76b6e02fec3cc125d381db9f323df08 | henningBunk/advent-of-code-2020 | /day-3/main.py | 1,129 | 3.71875 | 4 | import re
def read_input_as_list(filename):
return [line for line in open(filename, 'r')]
def read_input(filename):
return open(filename, 'r').read()
def count_trees(input):
return count_trees_w_slope(input, 3, 1)
def count_trees_w_slope(input, right, down):
my_position = 0
trees = 0
for... |
77bf6299b90b63d5c2cacbf4b6a2a7b876a28ba6 | EmaSMach/info2020 | /desafios/complementarios/condicionales/desafio3_menor_de_3.py | 800 | 3.9375 | 4 | # Desafío 3: Determinar si el primero de un conjunto de tres números dados, es menor que los otros dos.
numbers = []
while True:
num = int(input("Ingrese un número: "))
numbers.append(num)
if len(numbers) == 3:
break
print(numbers)
menor = numbers[0] == min(numbers)
if menor:
print("El prime... |
b4db96e67daa54a64aebcfcaee2a7d90b2d09e11 | Lehcs-py/guppe | /Seção_05/Exercício_03.py | 448 | 4.09375 | 4 | print("""
3. Leia um número real. Se o número for positivo imprima A raiz quadrada. Do contrário, imprima o número ao quadrado.
""")
num = float(input('Insira um número real, positivo = √x, negativo = x².: '))
if num >= 0:
raiz = num ** 0.5
print(f'O número é positivo, portanto, sua raiz quadrada é {rai... |
cc8e392108491c68e4366938d0124fdd3c2bff1e | daniel-reich/ubiquitous-fiesta | /YwXwxa6xmoonFRKQJ_22.py | 515 | 3.6875 | 4 |
def josephus(n):
def find_left(n, l):
for i in range(1, len(l)):
j = (n+i)%len(l)
if l[j] == 'a':
return j
if n < 2:
return False
else:
ind = 0
ind_n = -1
arr = ['a' for z in range(n)]
... |
30d33c7a2b9b0c7174e792fadd5754d5bc0d2ffb | rachel-ker/MLPipeline | /HW3/etl.py | 7,233 | 3.5 | 4 | '''
ETL - Explore, Transform and Load Code
Rachel Ker
'''
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
###################
# Read Data #
###################
def read_csvfile(csvfile):
'''
Reads in csv and returns a pandas dataframe
Inputs: csv file path
Returns a ... |
982400d452e42189567474bd9ab55b5900ebb462 | chetho/python-learning | /hackerrank/Interview Preparation Kit/Warm-up Challenges/1.py | 581 | 3.796875 | 4 | #!/bin/python3
# Sock Merchant
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
pairs = 0
freq_sock = {}
for item in ar:
if item in freq_sock:
freq_sock[item] += 1
else:
freq_sock[item] = ... |
9e6045174ae444f36deb9ddf54c388b34bdfb7e9 | bobhall/bobhall_euler | /euler/37/bob.py | 1,456 | 3.625 | 4 | from factors import isPrimeFactors
# I'm just going to put this comment here.
#
# A number n, is right truncatable if n is prime, and it continues to be prime as you "peel" off digits from the right:
# Eg. 31139 -> 3113 -> 311 -> 31 -> 3 (these are all prime, therefore 31139 is a right-truncatable prime)
#
# This ... |
ca6fec6168b97a6e4082f1a738d6b7f3792a2383 | lukistar/Discworld | /TP/h3/1.py | 1,244 | 4.15625 | 4 | #!/usr/local/bin/python
#school - ТУЕС
#class - 11Б
#num - 20
#name - Красимир Светославов Стойков
#task - Да се съберат номерата от една колонка зажисимост от нещо в някоя друга. От csv файл
def is_int(s):
try:
int(s)
return 1
except ValueError:
return 0
def read_CSV(FILE):
import c... |
222b254915ce6ae53762a13a3dbd9c58cc9846fc | 6306022610113/INEPython | /test3.py | 187 | 3.890625 | 4 | # try block to handle the exception
try:
my_list = []
while True:
my_list.append(int(input()))
# if the input is not-integer, just print the list
except:
print(my_list)
|
7f4f33804bf437fb231e2f7a8f3035ed817b7467 | pranaychandekar/dsa | /src/stacks/stacks.py | 2,013 | 4.375 | 4 | import time
class Stacks:
"""
This class is an implementation of a Stack data structure.
:Authors: pranaychandekar
"""
def __init__(self):
"""
This method initializes a Stack.
"""
self.stack: list = []
def push(self, data):
"""
This method add... |
55542edc5a6dd52412fd92926ed3cb1862438c3a | suraj-yathish/Coding-Challenge-Pacman- | /main.py | 1,438 | 3.8125 | 4 | """
This main function invokes pacman with the commands
Input: File with the commands e.g. test_command_1.txt
Output: Pacman object
How to Invoke: python main.py input/test_command_1.txt
"""
import sys
from utils import readFile,preprocessCommands
from pacman import Pacman
from direction import Direction
from grid im... |
c865916c9cb416826a7793b45a8d583137c09294 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/ntnlus001/question3.py | 545 | 3.671875 | 4 | def check(ls):
for j in range (9):
for n in range(9):
if ls[j].count(ls[j][n]) > 1:
print("Sudoku grid is not valid")
cols = [[row[i] for row in ls] for i in range(9)]
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) > 1:
print("Sudoku grid is not valid")
an... |
e61754e2c02b0df80bff1065f73d6bcbb317c0ee | chenhuang/leetcode | /connect.py | 3,153 | 4.34375 | 4 | '''
Populating Next Right Pointers in Each Node
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initia... |
6d736af009e0715520192f50de3159adcd6291b8 | anebz/ctci | /01. Arrays and strings/1.5. levenshtein.py | 1,682 | 3.640625 | 4 | import unittest
def levenshtein(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if s1 == s2:
return True
len1 = len(s1)
len2 = len(s2)
flag = False
if len1 == len2: # equal lengths
for i in range(len1):
if s1[i] != s2[i]:
if flag:
... |
246f8eb1b14863b7061c419dc7a4362ab2e45b3e | oden6680/AtCoder | /other/tenpuro2012_A/tempCodeRunnerFile.py | 113 | 3.65625 | 4 | S = input()
S = list(S.split(' '))
res = []
for i in S:
if i != ' ':
res.append(i)
print(S.join(',')) |
ed9d5c1beced88de51c45128eeeab707fde692dd | PavanKReddi/NetworkAutomationUsingPython | /open_excel_file.py | 859 | 3.640625 | 4 | # open_excel_file.py
import xlrd
def open_excel_file(workbook_name):
workbook = xlrd.open_workbook(workbook_name)
worksheet = workbook.sheet_by_name('Sheet1')
return worksheet
def main():
'''
Open "switch_list.xlsx" and display its data
'''
worksheet = open_excel_file("switch_list.xlsx")
nu... |
cee407494f07f0176e7217fda18d4ce3a74ca883 | conorfalvey/Coding-Samples | /Karan-Example-Project-Solutions/Python/Numerical/ChangeReturn.py | 828 | 3.859375 | 4 | import math
def change(n):
total = str(math.floor(n * 100)/100)
n = int(n * 100)
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while (n >= 5):
if (n - 25 >= 0):
quarters = quarters + 1
n = n - 25
elif (n - 10 >= 0):
dimes = dimes + 1
... |
6f0dcfb67ccf54b624f8b418f4bdff244ebb17cd | lixinchn/LeetCode | /src/0108_ConvertSortedArrayToBinarySearchTree.py | 1,444 | 3.859375 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
@staticmethod
def create(arr):
head = None
this = None
left, right = False, False
prev_nodes = []
for val in arr:
node = TreeNode(val)
... |
4b2d3b19cdb41a9fb095c6ee6476a3cb13250126 | unlimitediw/LCContest | /Contest_102.py | 5,934 | 3.515625 | 4 | import math
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
even = []
odd = []
for digit in A:
if digit % 2 == 0:
even.append(digit)
else:
odd.append(digit)
... |
3f0addba2e7310cf1bfff519ec0a6041a4b83fa4 | FWNT/ycsh_python_course | /L07/ttt_check_wins.py | 1,901 | 3.65625 | 4 | # 撰寫一程式,檔案名稱 ttt_check_wins.py
# 定義棋盤格狀態變數 cell_1 ~ cell_9 與目前的棋子變數 chess 如下,
# 檢查該棋子是否已經在該盤面上取得勝利條件,
# (任意直線上的三個格子的棋子皆和目前的棋子相同),
# 如果已經取得勝利條件,顯示 '{棋子} 勝利,結束程式',並退出程式
# (請替換其值)
# 棋盤格變數:保存棋盤狀態的變數
# 變數編號對應的棋盤位置如下
# 1 | 2 | 3
# ---+---+---
# 4 | 5 | 6
# ---+---+---
# 7 | 8 | 9
cell_1 = ' '
cell_2 = ' '
cell_3 = 'o'... |
a723bb6e8db3faf3625f6432ed28b0fed6b5dcba | dabanin/GeekBrains_Python | /hw01_hard.py | 1,673 | 3.5 | 4 | __author__ = 'Абанин Дмитрий Сергеевич'
# Задание-1:
# Ваня набрал несколько операций в интерпретаторе и получал результаты:
# Код: a == a**2
# Результат: True
# Код: a == a*2
# Результат: True
# Код: a > 999999
# Результат: True
# Вопрос: Чему была равна переменная a,
# если точно известно, что её значение не ... |
b236f7feca0b1a1408e578b4878eff1435c2d4b4 | zhaozhenyu/push | /python复习/p4/problem4.py | 526 | 3.53125 | 4 | import numpy as np
def unnest(alist):
k=[] ### append alist to k and k is str type
flat_list=[]##
for i in alist:
k += str(i)
for i in k:
if str.isnumeric(i):
flat_list.append(int(i))
return flat_list
#
# a=[[2,2,2],[3,3,3],[4,4,4]]
# print(unnest(a))
# z=[]
# print(type(... |
01c167f122dad687b2337c36184075ad561b8ec7 | paulosergio-dev/exerciciopython | /questao14.py | 1,001 | 3.921875 | 4 | '''
Elabore um programa que leia o salário de um empregado e com base na tabela abaixo calcule
e informe sua gratificação e seu salário líquido.
'''
salario = float(input("Informe o salário: "))
if salario < 2000:
aumento = 5
resultado = salario + (salario * aumento/100)
print("Sua gratificação é ... |
d6e80f3b183efa3cb03b926f893c37d11ec88f03 | USTH-Coders-Club/API-training | /caller.py | 393 | 3.84375 | 4 | #import the library to make http request
import requests
#URL of the API
URL = "http://127.0.0.1:5000"
dating_id = input("Id of the guy you want to flirt")
param ={
'id':dating_id,
}
#Make an API request and store date to r
r = requests.get(url= URL, params=param)
#Json data
data = r.json()
#extract count fro... |
6c7d8f09d8987fc9836b67f4a2c86b769676c850 | wmsj100/CodeSpace | /python/project/mao_pou_xun_huan.py | 833 | 4.15625 | 4 | """
先不想着用递归调用,
先实现思路
走一次循环,再循环中比较相邻俩个值的大小
"""
import sys
def sort_max_list(list):
for index, num in enumerate(list):
if index == len(list) - 1:
break
else:
if num > list[index+1]:
list[index], list[index + 1] = list[index+1], num
print(list)
def sor... |
ebf795126773c6ea82c8aaab05b248a4c0fb7995 | bufordsharkley/advent_of_code | /2016/day19.py | 1,199 | 3.546875 | 4 | num = 5
def last_elf(num):
elfs = [x + 1 for x in range(num)]
position = 1
while len(elfs) > 1:
if position == 0:
position = len(elfs) % 2
elfs = [x for ii, x in enumerate(elfs) if ii % 2]
else:
position = (1 + len(elfs)) % 2
elfs = [x for ii, x in enumerate(elfs) if not ii % 2]
... |
9ced2b736545ce4b6b3c2eac7c68aa833754ae43 | RishabhK88/PythonPrograms | /5. DataStructures/SortingLists.py | 708 | 4.6875 | 5 | numbers = [3, 51, 2, 8, 6]
# List is sorted in ascending order
numbers.sort()
print(numbers)
# List is sorted in descending order
numbers.sort(reverse=True)
print(numbers)
# Below is used to sort the list and print but not change the original list
print(sorted(numbers))
print(sorted(numbers, reverse=True))
# ... |
a05174f2d4cd3540cfd28c181d5d8fae37cc4d2a | jetboom1/python_projects | /files/romeo and julietta.py | 649 | 3.859375 | 4 | '''Возникли проблемы с получением доступа к файлу через интернет, поэтому пришлось скачать его локально'''
from operator import itemgetter
with open('intro.txt') as romeo:
counts = dict()
for i in romeo.readlines():
words = i.lower().split()
for k in words:
if k in counts:
... |
42f9e087749c4f300554a07f330e83b284ac9879 | sassyst/leetcode-python | /leetcode/contest/N-RepeatedElementinSize2NArray.py | 342 | 3.625 | 4 | def repeatedNTimes(A):
"""
:type A: List[int]
:rtype: int
"""
A.sort()
i, j = 0, 1
while j < len(A):
if A[i] == A[j]:
return A[i]
else:
i += 1
j += 1
s = [1, 2, 3, 3]
ret = repeatedNTimes(s)
print(ret)
s = [2, 1, 2, 5, 3, 2]
ret = repeate... |
0e168013704c64fd99b323d89584df1074be6506 | zois-tasoulas/DailyInterviewPro | /p21/p21.py | 913 | 3.703125 | 4 | def minimalSubarray(lst, s):
leftIndex = 0
arrayLength = len(lst)
minSubarray = arrayLength + 1
currentSum = 0
for rightIndex, element in enumerate(lst):
currentSum += element
if currentSum > s:
while currentSum > s and leftIndex <= rightIndex:
currentSum ... |
d8c7507f42fcb479ef7ebf8560cb5343348f7178 | kjnh10/pcw | /work/atcoder/abc/abc019/B/answers/232803_nanae.py | 324 | 3.671875 | 4 | import sys
def solve():
s = input() + '#'
ans = s[0]
pch = s[0]
cnt = 1
for ch in s[1:]:
if ch != pch:
ans += str(cnt) + ch
cnt = 1
pch = ch
else:
cnt += 1
ans = ans.rstrip('#')
print(ans)
if __name__ == '__main__':
sol... |
b92dbe12c992ea13d2e1409e2800712c2577ebb4 | A01378649/Snake | /snake.py | 3,732 | 4.21875 | 4 | """
This program contains functions to run the game of snake.
Welcome to snake!
You move with the arrows.
Avoid crashing with the walls or your own body.
Eat the food to grow.
Good luck!
"""
# Related third party libraries.
from turtle import update, ontimer, setup, \
hideturtle... |
ed0780241767285486b4ed1e3c8e7f0510afc5ba | Amaayezing/ECS-10 | /FractionAddRadhav/frac_add.py | 1,922 | 4.03125 | 4 | #Raghav Dogra & Maayez Imam 11/13/17
#Fraction Add program
def is_int(num):
if len(num) == 0:
return False
elif num.strip().isdigit():
return True
elif num.strip()[0] == '-' and num.strip()[1:].isdigit():
return True
else:
return False
def gcd(a, b):
if a < b:
... |
7d4e5f0fb0460d3b9bb11a5f24c037aa5a0073e5 | JorgeTowersmx/python2020 | /sentencias.py | 163 | 4 | 4 | name = "Diego1" #Asignacion de valor a una variable
if name == "Diego":
print("Aupa Diego")
else:
print("¿Quien eres?")
print("¡No eres Diego!") |
ed56bca392cab999198a8b22dd33eb00cf00439e | bzelditch/EPI | /Ch8/test.py | 371 | 3.5625 | 4 | from search import DFS, BFS
from queueG import Queue
from graph import Node
root = Node(1)
b = Node(3)
c = Node(4)
d = Node(10)
e = Node(11)
root.addNeighbor(b) # There's a better way
b.addNeighbor(root)
b.addNeighbor(e)
e.addNeighbor(b)
root.addNeighbor(c)
c.addNeighbor(root)
c.addNeighbor(d)
d.addNeighbor(c)
#p... |
a1d3a80c9775890ab0b71a9b74972c03a1739e4a | AdamZhouSE/pythonHomework | /Code/CodeRecords/2526/58547/261475.py | 191 | 3.875 | 4 | def func():
arr0 = [int(x) for x in input()[1:-1].split(",") if x.isdigit()]
arr1 = [int(x) for x in input()[1:-1].split(",") if x.isdigit()]
print(sorted(arr0 + arr1))
func()
|
6a7d2a8d06995e9b6113b98e545ac5f48b46b53f | wyh19/PythonCrashCourse | /8-函数/1-定义函数.py | 3,508 | 4.1875 | 4 | # 函数就是带名字的代码块,用于完成具体的工作;如果一段代码会多次被执行,那么应该考虑将其定义为函数,然后调用函数执行该段代码
# 函数定义的形式为
# def 函数名():
# """函数说明(可选)"""
# 函数体(缩进)
def greet_user():
"""显示简单的问候语"""
print('Hello')
# 函数调用
greet_user()
# 通过参数,想函数传递额外数据,使其具备更多功能
def greet_user2(username):
"""显示姓名的问候语"""
print("Hello, " + username.title() + "!")
... |
dccb8b00f8a465622970e9c76232a0483faeb1d0 | lraulin/algorithms | /js/sort/bubble_sort.py | 415 | 4 | 4 | # Don't ever use! This is the worst sorting algorithm!
# O(n^2)
def bubble_sort(arr):
swapped = True
while swapped:
swapped = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = True
print(arr... |
4b1d353ce66f7289ef71cdc6169af352687fcf8f | shin-kanouchi/NLP100knock | /test064.py | 769 | 3.5625 | 4 | #!/usr/bin/python
#-*-coding:utf-8-*-
#2014/06/17 17:12:21 Shin Kanouchi
"""(64) 63の結果を用い,TF*IDF値が高い名詞句トップ100のリストを作成せよ.このとき,数字を含む表現はトップ100のリストから除外せよ."""
def sort_tf_idf():
import re
dict = {}
for line in open("63_output_tf_idf.txt"):
word,tf_idf,tf,df = line.strip().split("\t")
r = re.compile(r"[0-9]")
if not... |
98b2a446f91d3b0045878ce4eb0cfdae2219225c | jisshub/python-django-training | /unittesting/test2.py | 1,333 | 3.734375 | 4 | import unittest
import calc
class TestCalc(unittest.TestCase):
def test_add(self):
self.assertEqual(calc.add(10, 20), 30)
self.assertEqual(calc.add(-1, -1), -2)
self.assertEqual(calc.add(-1, 1), 0)
def test_multiply(self):
self.assertEqual(calc.multiply(20, 20), 400)
... |
beb20ed70cebb3811ad634dd50df807008e5424c | galicminer/Tec | /TC1028/Python/Ejericicio4 Algoritmos.py | 333 | 3.84375 | 4 | print("Test de aptitud para la licencia de conducir")
print("Cuenta usted con una identificacion oficialsi/no")
iden=input()
print("ingrese su edad numericamente")
edad=int(input())
if(iden=="si")and(edad>=18):
print("esta usted habilitado para recibir licencia")
else:
print("usted no esta habilitado para recib... |
a4d2fa34c8bd70770397a64cbe0fde8386dfa56e | chris-bk-song/python-101 | /python_exercise_two.py | 359 | 4.21875 | 4 | # Step 0: Document the problem
# Prompt user to input their name and print out welcome mesage with their name
# Step 1: Setup/Configuration
name = input('What is your name? ')
name_length = len(name)
# Step 2: Result/Output
greeting = f'Welcome, {name.upper()}! \n YOUR NAME HAS {name_length} LETTERS IN IT! AWESOME!' ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.