blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7be86cc9451180e7c306d5b4563c0e30036e0d0f | Sa4ras/amis_python71 | /km71/Likhachov_Artemii/4/Task1.py | 163 | 4 | 4 | a = int(input('Input first number: '))
b = int(input('Input second number: '))
txt = 'Bigger number is: '
if a > b:
print(txt, a)
else:
print(txt, b) |
b932d89ec6ecc58b3a75a6abc030bac8c18c6068 | YaohuiZeng/Leetcode | /334_increasing_triplet_subsequence.py | 1,466 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Your algorithm should run in O(n) time... |
0a23b58e4522aea14882eaed7250ce532fec058a | NickSanft/PythonSQLiteFlaskDemo | /DatabaseUtils.py | 3,762 | 3.75 | 4 | from xlsxwriter.workbook import Workbook
import sqlite3 as sql
import Config
con = sql.connect(Config.Database["databaseName"])
# This function creates all necessary tables needed in the SQLite database.
def createTables():
cur = con.cursor()
cur.executescript(Config.Database["createTablesQuery"])
print(... |
71fca7003c8de0a7a2369bdeeca7155a7cfc564c | maysuircut007/python-basic | /56. Arbitrary Arguments (args).py | 281 | 3.640625 | 4 |
# *args = tuple
def add(*agrs):
print(agrs)
print(agrs[0] + agrs[1])
sum = 0
for item in agrs:
sum += item
print(sum)
sum2 = 0
for i in range(len(agrs)):
sum2 += agrs[i]
print(sum2)
add(10, 20, 30, 40) |
666a0710ef2a66a1e827f9140b046b52e34e247c | vikvik98/Algoritmos_2017.1 | /Atividade G/fabio_06_06.py | 807 | 4 | 4 | def main():
#48 a 57
frase = input("Digite uma frase: \n")
nova_frase = ""
for letra in frase:
if is_number(letra):
print(getAlgarismo(letra),end="")
else:
print(letra,end="")
print("\n")
def is_number(letra):
return ord(letra) >= 48 and ord(letra) <= 57
def getAlgari... |
a9e63904be05f205a67c2e5ab57293d85f062616 | labyrlnth/codeeval | /hard/String_List.py | 875 | 3.703125 | 4 | import sys
def generate_strings(letters, number):
if number == 0:
return []
else:
result = []
rest = generate_strings(letters, number - 1)
for letter in letters:
if rest == []:
return letters
else:
for item in rest:
... |
ea8ff12752cd6f8fde54ef844e3d26afbe1c746c | muh-nasiruit/programming-fundamentals | /PF 05 Problems/pf5.py | 885 | 4.125 | 4 | ''' 5. Write multiple functions for making the mark sheet program as you have done in the previous lab.
'''
def m_sheet():
Name = input("Enter Name: ")
FatherName = input("Enter Father Name: ")
RollNumber = int(input("Enter Roll Number: "))
Subjects = []
Marks = []
for i in range(5):
Su... |
19e02d42cd503223639b84ae6fde51afb1498fc7 | aultimus/project_euler | /17_number_letter_counts.py | 904 | 3.671875 | 4 | # http://projecteuler.net/problem=17
# If the numbers 1 to 5 are written out in words: one, two, three, four, five,
# then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out
# in words, how many letters would be used?
#
# NOTE: Do not ... |
6365219b047903298c3d0460b1189f079eb84c0d | J-Keven/aps-design-patterns | /Iterator/problema/main.py | 409 | 4.25 | 4 | """
Um exemplo de problema simples onde temos uma lista de elementos
e queremos percorre-la de formas diferentes.
"""
if __name__ == "__main__":
# lista
lista = [("a", "b"), ("c", "d"), 3]
# mostrando na ordem de inserção
for elemento in lista:
print(elemento)
# mostrando na ordem... |
be74995491f40299d16723e1ad7c4e2e0c2e3785 | edutilos6666/CL_Uebung2 | /Test/ComplicatedTest.py | 1,599 | 3.640625 | 4 | def test1():
assert 1== 1
class ComplexNumber:
def __init__(self, real= 0, imag= 0):
self.real = real
self.imag = imag
def add(self, other):
ret = ComplexNumber()
ret.real = self.real + other.real
ret.imag = self.imag + other.imag
return ret
def subt... |
b571aa429f2df67ba7e63e11cd5ea7bc4320031a | gsandova03/taller3_int_computacional | /punto3.py | 421 | 3.765625 | 4 | num_obreros = int( input('Numeros de obreros: ') )
salarios = []
for n in range( 1, num_obreros + 1 ):
horas = int( input('Horas trabajadas: ') )
if( horas <= 40 ):
pago = horas * 20
salarios.append( pago )
elif( horas > 40 ):
pago = 40 * 20
horas_extra = horas - 40
pago_extra =int( horas_e... |
4376f52db4c2e04cc0884be14ce4e311bafeb048 | LayaJose/Image-Cleaning | /Task1/Task1.py | 2,181 | 3.65625 | 4 | ################
## Task 1 - Tissue identification
## Byron Smith
## 9/10/2020
##
## This code is written to identify tissue from a whole slide image.
## First, we can immediately see that slide background is white and can
## be identified as have red-green-blue values over 0.9 (or 240 on a 0-255 scale).
... |
ea51cefe67289ce2e61ca78fd58b775e6fa424a5 | nidhinbose89/algorithm_study | /heaps.py | 2,528 | 3.953125 | 4 | #!/usr/bin/env python
"""Heap Implementation."""
from copy import copy
class MaxHeap(object):
"""Max Heap Implementation."""
def __init__(self, items):
"""Initializer."""
for idx in range(len(items) - 1, -1, -1):
self.heapify(the_input, idx)
self.items = items
def hea... |
1a851669708e0f307e3f3239bd31afbc1d93e231 | DerekHJH/LearnPython | /numpy/haha.py | 6,713 | 3.59375 | 4 | import numpy as np;
import numpy.linalg as npl;#Linear algebra;
import matplotlib.pyplot as plt;
import time
#from numpy import *; Use this to avoid adding the prefix np.;
#The same as list(range(10));
'''
a = np.arange(10);
print(a);
'''
#ndarry is much faster than list and consume less memory
'''
Sum = np.arange(10... |
5b3439da727601373c182079675c0ed28e836a86 | ClayPalmerOPHS/Y11-Python | /FOR LOOP challenges09.py | 417 | 3.921875 | 4 | #FOR LOOP challenges 09
#Clay Palmer
invites = int(input("How many people do you want to invite to your party? "))
if invites < 10:
for i in range(invites):
print("")
name = str(input("Enter the name of someone you want to invite: "))
print("")
print(name,"has been invited")
pr... |
3177ea41966870eea0b6a2171ffa68049f2df185 | cmrdSurajYadav/adnotepad | /t.py | 303 | 3.546875 | 4 | from PIL import Image, ImageTk
from tkinter import *
a = Tk()
img = Image.open("image/find.png")
image_ = ImageTk.PhotoImage(img)
scroll = Scrollbar(a, orient="vertical")
text = Text(a, width=25, height=15, wrap="none", yscrollcommand=scroll.set)
text.image_create("1.0", image=image_)
a.mainloop() |
8fdad2eb16fac5db921248135b91f66a46dbf524 | eronekogin/leetcode | /2020/design_circular_deque.py | 3,215 | 3.90625 | 4 | """
https://leetcode.com/problems/design-circular-deque/
"""
class ListNode:
def __init__(self, val: int):
self.val = val
self.next = None
self.prev = None
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here.
Set the si... |
ce1ee6b8dceddbf85e92292c3bfc3564fbf69110 | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-12/python/solution.py | 852 | 3.59375 | 4 | def threeSum(nums: [int]) -> [[int]]:
nums.sort()
result = []
n = len(nums)
if not nums or nums[0] > 0 or nums[-1] < 0 :
return result
for first in range(n) :
if first > 0 and nums[first] == nums[first-1] :
continue
third = n-1
target = -nums[first]
... |
afa004c3e247baf2b226a05c594babd8eed9cd1b | moon-shrestha/python_assignment_dec8 | /password.py | 222 | 3.515625 | 4 | #to check if the passords match or not
password = 1234
def fun(pw):
if (pw == password):
print("Passwords match.")
else:
print("Wrong password.")
pw = (input("Enter a password:"))
fun(pw) |
a75e8148c07657cff4cfc272316e0a56e269a468 | brianjp93/desktopcodeeval | /fib/fib.py | 264 | 3.65625 | 4 | import sys
def fib(n):
if n == 0:
return 0
else:
total = 1
last = 1
temp = 0
for i in range(1, n):
total += temp
temp = last
last = total
return total
with open(sys.argv[1], 'r') as f:
for line in f:
n = int(line.strip())
print(fib(n)) |
b14ec4e008d703d7d5f00ea9b3914b8761694575 | shadowlugia567/Visualisation_Project | /W4_Conic.py | 1,036 | 3.8125 | 4 | import matplotlib.pyplot as plt
import numpy as np
G=6.673*(10**-11)
M = float(input('Enter the mass of the bigger body: '))
m = float(input('Enter the mass of the smaller body: '))
rp = float(input('Enter the periapsis in m: '))
vp = float(input('Enter the v in m/s: '))
""" #Data for testing. Using the Sun and t... |
eb2167c8adc1ccf0eef2856010e844c0f968f90c | Brunodev09/Java-OOP-samples | /Python/textGame.py | 426 | 3.734375 | 4 | from random import randint
gameLoop = True
rand_num1 = randint(1,101)
rand_num2 = randint(0,2)
print('Welcome to dragslay! Type play or quit!\n')
while gameLoop:
user = input()
if (user == "quit"):
print('\n----Made by Bruno Giannotti, thanks for playing----')
break
if (user == "play"):
print('OK. Before e... |
925ca46a38cddbfa49170e4c7544284a2fda3b7f | RIPtaDAcomp/hw4_help | /HarrisMHW4.py | 3,505 | 4.15625 | 4 | #===================================================================================================
# Program: ATM Program
# Programmer: Matthew Harris
# Date: 01/29/2018
# Abstract: This program is a simulation of an ATM. It will process deposits,
# withdrawls, and invalid transa... |
e32bb4cb955fdd108b0fe054391fad5b05534d7a | debuitc4/CA268 | /week1/evenodd.py | 213 | 4.0625 | 4 | #!/usr/bin/env python3
import sys
#even print second half of string
#odd print first and last letter
s = sys.argv[1]
if len(s) % 2 == 0:
print(s[len(s) // 2:])
else:
print(s[0] + s[len(s) - 1])
|
94bb58c36c7aa59459797e314ca1603056c31874 | gubarbosa/curso-python | /Mundo2/ex051.py | 387 | 3.859375 | 4 | """Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão."""
def PA():
primeiro_termo = int(input('Primeiro termo da PA: '))
razao = int(input('Razão da PA: '))
decimo = primeiro_termo + (10 - 1) * razao
for x in range(primeiro_te... |
8d81facb0f0406354a06ce86232504cdec7e645d | wer153/leetcode | /0904-leaf-similar-trees/0904-leaf-similar-trees.py | 671 | 3.90625 | 4 | # 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 leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
return traval... |
329690e647c98076045ee727a16e0b4fd5063add | Charlie-Say/CS-161 | /assignments/assignment 5/distance.py | 1,867 | 4.625 | 5 | #! /usr/bin/env python3
# coding=utf-8
'''
write a function that calculates the distance in miles between two cities.
Given the latitude and longitude coordinates of cities, calculate the distance
in miles between them. Then, write a program that prompts for the coordinates of
two cities, uses the function to calcul... |
65154120a9ae2b960d1709761ab26e3b1af3c6c8 | iverson52000/DataStructure_Algorithm | /LeetCode/0084. Largest Rectangle in Histogram.py | 595 | 3.875 | 4 | """
!84. Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
"""
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
s = [... |
d8d6e81e0fcefb77b679dfa9b3d9931d1f6c342f | wljSky/numpy-pandas-exercise | /Matplotlib画图基础/绘制x轴和y轴的刻度.py | 750 | 3.5 | 4 | import matplotlib.pyplot as plt
import random
x = range(2,26,2)#x轴的位置
y = [random.randint(15,30) for i in x]
plt.figure(figsize=(20,8),dpi=80)
#设置x轴的刻度
#plt.xticks(X)
#plt.xticks(range(1,25))
#设置y轴的刻度
#plt.yticks(y)
#plt.yticks(range(min(y)),max(y)+1)
#构造x轴刻度标签,for循环读取x轴刻度并控制产生刻度标签的个数,并以相应的格式显示:{}中,放置format(i)括号中的i,也就是... |
7ce391f5f7d8c192a834e94444bde5204251384e | agvaibhav/python-basics | /trip.py | 498 | 3.671875 | 4 | def hotel_cost(nights):
return 140*nights
def plane_ride_cost(city):
if city=='Charlotte':
return 183
elif city=='Tampa':
return 220
elif city=='Pittsburgh':
return 222
elif city=='Los Angeles':
return 475
def rental_car_cost(days):
rent=40*days
if days>=7:
return rent-50
elif 7>=day... |
600160ce998cf98408d0bbe1b808ddabfefcfd61 | Thejasvikha/Python-programs | /miles to km.py | 205 | 4.25 | 4 | #converting miles to kilometers
def convert():
print("mile to km:")
m=int(input("Enter the number of miles:"))
t=m*1.609344
print("The number of kilometers for",m,"miles is",t)
|
1307d39e7e9accbeee0d5373b6ec1f0f953204ef | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_117/1158.py | 1,911 | 3.609375 | 4 | #!/usr/bin/python
import sys
def is_valley(rows, r, c, N, M):
val = rows[r][c]
up = down = right = left = False
if r > 0: #CHECK UP
up = rows[r-1][c] > val
if r < N - 1: #CHECK DOWN
down = rows[r+1][c] > val
if c > 0: #CHECK LEFT
left = rows[r][c-1] > val
if c < M - 1: ... |
fe41cc99cfccbf15ee02ba924a9a089c436d484f | gabrielwry/InterviewPractice | /Algorithm/LeetCode/132Pattern.py | 1,090 | 3.90625 | 4 | """
Construct a min_list of the min value before this position
Traverse the original array in reverse order, calculate the range from current position to the end of this array
If the range falls into the range of the min_list and the current position, return True
"""
class Solution(object):
def find132pattern(se... |
10532a87a5d40bc524b412324f3b38129edd4850 | ShuaiWang0410/LeetCode-2nd-Stage | /LeetCode-Stage2/Tricks/Problem_56.py | 1,108 | 3.65625 | 4 | '''
56. Merge Intervals
'''
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
... |
9933b96174838ef93c2c03774f278e8bc3b8bf60 | wkujo/RL | /explore_exploit/opt_init_value.py | 1,399 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
class Bandit:
def __init__(self, chance, init_value):
self.rel_win_chance = chance
self.num_pulls = 0
self.mean = init_value
def pull(self):
return np.random.randn() * self.rel_win_chance
def update(self, x):
self... |
722e203c2dca91a675b5b5e010715f6a04c722ec | jawillia18/problems | /submission_002-mastermind/mastermind.py | 1,186 | 3.859375 | 4 | import random
def four_digit_code():
# TODO: Step 1: generate a random 4 digit code
code = random.sample(range(1,8), 4)
return code
def usr_prompt():
usr_input = input("Input 4 digit code: ")
return list(usr_input)
def input_length(usr_input):
# len_code = len(code)
len_input = len(usr_in... |
69c66a453e6a2226519481954dde76bf468a5abc | rohinarora/Algorithms | /Trees/Binary Search Trees/bst.py | 4,617 | 4.21875 | 4 | class BST(object):
"""
Simple BST
Each tree contains some (maybe 0) BSTnode objects, representing nodes, and a pointer to the root.
"""
def __init__(self):
self.root = None
def insert(self,t):
'''
Insert key in BST
'''
new_node=BSTnode(t)
y=None
... |
7509d3d5ce84254abaeb0a2ee23659e944b3fc2b | ryandsowers/assembler | /SymbolTable.py | 1,390 | 3.609375 | 4 | #
#SymbolTable.py
#
#Loren Peitso
#
# CS2001 Project 6 Assembler
# 31 July 2013
#
#complete
#
class SymbolTable(object):
def __init__(self):
self.table = {
'SP': 0,
'LCL': 1,
'ARG': 2,
'THIS': 3,
'THAT': 4,
'SCREEN': 16384,
'KBD'... |
2568b9decb0da5d27ec476e8a94c93ff433f3d17 | Matizsta/Test | /12.7 Skillfactory.py | 361 | 3.65625 | 4 | per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
money = int(input("Введите сумму: "))/100
float_deposit = [i * money for i in per_cent.values()]
deposit = list(map(round, float_deposit))
print(deposit)
print("Максимальная сумма, которую вы можете заработать — ", max(deposit))
|
37680376267cee764480d30d09a71b0834565c68 | Haouach11/assignment | /code11.py | 145 | 3.90625 | 4 | a = range(int(input("enter a number")),int(input("enter a number"))+1)
for j in a:
for i in range(1, 11):
print(j, "x", i, "=", i*j)
|
e881217d32517ed8e5a684d3c14b3cae966ded6a | evandroMSchmitz/learning | /livro-curso-intensivo-de-python/projeto-2-visualizacao-de-dados/Capitulo-15/geracao-visualizacao-matplotlib/mpl_squares.py | 505 | 3.890625 | 4 | import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, "-o", linewidth=2)
# Definir o título do Gráfico
plt.title("Números Quadrados", fontsize=24)
# Nomear os eixos
plt.xlabel("Valor", fontsize=14)
plt.ylabel("Quadrado do Valor", fontsize=14)
# Def... |
2f9244edf6cdf5d93eaf837209d725e64540dd8e | eawasthi/CodingDojo | /Python/Week1/Day1/practiceAtNight.py | 927 | 3.53125 | 4 | x="It's thanksgiving day. It's my birthday,too!"
y=x.replace('day', 'month')
print len(x)
print y
x = [2,54,-2,7,12,98]
min1=x[0]
max1=x[0]
for i in x:
if i > max1:
max1=i
if i<min1:
min1=i
print max1, min1
x = ["hello",2,54,-2,7,12,98,"world"]
print x[0], x[len(x)-1],
x = [19,2,54,-2,7,12,98,32,10,-3,6... |
a2c7cf5d70b93299e143b81eda99dd00fbea43f1 | annalevijeva/Quadratic-equation | /test_equation.py | 465 | 3.75 | 4 | import unittest
from equation import equation
# class EquationTestCase(unittest.TestCase):
# def test_equation(self):
# result = equation(-2, 1, 1)
# self.assertEqual(result, equation(-2, 1, 1))
class EquationTestCase(unittest.TestCase):
def test_solves_equation(self):
"""Solve y=1*(x... |
2df745eaae8bbe311bf75f151c8a852b5967dcbd | willpan/sample-csv | /samplecsv.py | 1,958 | 3.59375 | 4 | #! /usr/bin/env python
"""
samplecsv
A utility to randomly sample data from a csv file
"""
import argparse
import csv
import random
import sys
def sniff(buffer):
"""Determine if csv has header and its dialect"""
sample = buffer.read(4098)
buffer.seek(0)
sniffer = csv.Sniffer()
has_header = sniff... |
715f516aedcb41b9e8c1e049fdcd6005a5b03f0f | shubik22/Project-Euler | /prob_14.py | 522 | 3.84375 | 4 | def longest_collatz(max):
longest_collatz = 1
collatz_dict = dict({1: 1})
for i in range(1, max + 1):
temp_i = i
collatz_len = 0
while temp_i not in collatz_dict:
temp_i = next_collatz(temp_i)
collatz_len += 1
collatz_dict[i] = collatz_dict[temp_i] + collatz_len
if collatz_dict[i] ... |
0740e1a1287ad0337572db7157c523b38020e0cb | dgirija/SDE1 | /dictionary_search.py | 247 | 3.5625 | 4 | import requests
import json
word = str(input("Word? <user inputs a word>(Ex – \“House\”)"))
url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US' + '/' + word.lower()
r = requests.get(url)
data = json.dumps(r.json())
print(data)
|
a45245143c11c7ac18b699b7537bfd96b1585a52 | MinSu-Kim/pandas_study | /8.data_preprocessing/2.duplicate_data/duplicated.py | 505 | 3.53125 | 4 | import pandas as pd
# 중복 데이터를 갖는 데이터프레임 만들기
df = pd.DataFrame(
{
'c1': ['a', 'a', 'b', 'a', 'b'],
'c2': [1, 1, 1, 2, 2],
'c3': [1, 1, 2, 2, 2]
}
)
print('df', df, sep='\n', end='\n\n')
print("# 데이터프레임 전체 행 데이터 중에서 중복값 찾기")
print(df.duplicated(), sep='\n', end='\n\n')
print("# 데이터프레임의 ... |
6a6a83fa40559bfba9c55452b393091459677288 | statickidz/TemarioDAM | /ACTIVIDADES/eclipse-projects/Numeros/src/Actividad5-22/Actividad5-22.py | 923 | 3.671875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 27 de ene. de 2016
'''
# uso de and y or
print" uso de and y or "
print "ABC" and 0
print "ABC" and {}
print "ABC" and []
print "ABC" and ""
print "ABC" and False
print "ABC" and None
print "ABC" or 0
print "ABC" or {}
print "ABC" or []
print "ABC" or ""
print... |
cc5e35dc2bded6d98ace28f4d7e3aafec8eb7dfa | burov4j/ai | /python/lesson3/task4.py | 240 | 3.875 | 4 | def my_func(x, y):
result = 1
for _ in range(abs(y)):
result *= x
return 1 / result
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"Result: {my_func(num1, num2)}")
|
28c8cf00b2a8ddfd6efd855f7e636a40bd1913a2 | Hafisibnuhajar/print-formatting | /tugas 5.py | 345 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
#strings print formating
nama = "Hafis ibnu hajar"
print(f'Nama Dosen pengampu mata kuliah animasi {nama}')
# In[10]:
nama = "Hafis ibnu hajar"
f"Hallo {nama} selamat datang di Dehasen"
# In[12]:
user_nama = input ("siapa nama kamu? ")
print(f'Hallo {user_nama... |
4cb21aba9db21dc3d546bb340f06be9f59165fde | arun246/PythonDataStructures | /python_194/powers.py | 205 | 3.953125 | 4 | def power(x,n):
if n== 0:
return 1
else:
first=power(x,n//2)
res= first*first
if (n%2==1):
return x*res
return res
print(power(2,3))
|
83acb8eb1e81719e4cca83daf299f2922e2a23b2 | sakib-malik/problem_solving | /oops/LLD-Problems/vendingMachine.py | 4,133 | 4.34375 | 4 | """
Problem Statement: You need to write code to implement a Vending machine that
has a bunch of products like chocolates, candy, cold-drink, and accept some
coins like Nickle, Dime, Quarter, Cent, etc. Make sure you insert a coin,
get a product back, and get your chance back. Also, write the Unit test to
... |
bb2865d47bc32187f55f66755e0430a7ccf98279 | MaldoCarre/PythonCursoIntermedioAvanzado | /combinando.py | 451 | 4.15625 | 4 | # de dos listas convinar los valores sin repetir
# primera forma sin list list comprehensions
list1 = [1,2,3]
list2 = [3,4,5]
result = []
for i in list1:
for l in list2:
if i != l:
result.append((i,l))
result.append((l,i))
else:
pass
print(result)
#usando li... |
2fd24529cfdb7505043b25a858d4a0c5f64f8eec | dschonholtz/PsychEconSim | /Controller/SimpleController.py | 1,932 | 3.734375 | 4 | """
The simplest of controllers. Uses a base market and a TextView
"""
class SimpleController:
def __init__(self, text_view, simple_market, rounds=30):
self.view = text_view
self.model = simple_market
self.successful_sellers = 0
self.successful_buyers = 0
self.average_buye... |
4a6e5573431ca4ee3b042655e95c899c22ba8def | cad75/GBLessons | /Lesson_7_HW_2.py | 767 | 3.84375 | 4 | from abc import ABC, abstractmethod
class AClothes(ABC):
@abstractmethod
def get_cloth_count(self):
pass
class Coat(AClothes):
def __init__(self, v):
self.v = v
def get_cloth_count(self):
return self.v / 6.5 + 0.5
class Costume(AClothes):
def __init__(self, h):
... |
40164bb65828d27c7e50380d6f047c41f3594498 | endredaroczy/hackerrank-python | /iterables-and-iterators.py | 528 | 3.546875 | 4 | import itertools as it
def read_from_std():
_ = int(input())
letter_list = input().rstrip().rsplit()
K = int(input())
return {'letter_list':letter_list, 'K':K}
def read_from_file():
f = open('C:\\Users\\dkendre\\source\\repos\\scripts-python\\hackerrank\\input_file.txt', 'r')
_ = int(f.readlin... |
1c66531294e380ca4054de21d208fd05e70f76ea | TheAlgorithms/Python | /bit_manipulation/index_of_rightmost_set_bit.py | 1,483 | 4.28125 | 4 | # Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
def get_index_of_rightmost_set_bit(number: int) -> int:
"""
Take in a positive integer 'number'.
Returns the zero-based index of first set bit in that 'number' from right.
Returns -1, If no set bit found.
>>> get_index_of_r... |
e809af9e059c43de168f6d2877fa5686ec1bc998 | DegardinJonathan/Python | /Exercice de base/1.py | 147 | 3.8125 | 4 | a = int(input('Donnez la valeur de a : '))
b = int(input('Donnez la valeur de b : '))
temp=b
b=a
a=temp
print ('a = ',a )
print ('b = ',b )
|
6ce7a4ce21a8f60e2e858f9f66fbfde1da955c3e | aleexnl/aws-python | /UF2/Practica 22/ejercicio2.py | 780 | 3.765625 | 4 | # definim la funcio posicio lletra.
def pos_letra():
paraula = input('Introdueix una paraula:') # Pedimos al usuario una palabra.
lletra = input('Introdueix una lletra per saber la seba posicio:') # Pedimos una letra.
if lletra not in paraula: # Si la lletra introduida no es en la paraula.
print... |
4debf4217d22ed297272041d814b8313c42d2bac | juansalvatore/algoritmos-1 | /tps/tp0/vectores.py | 520 | 3.84375 | 4 | def diferencia(x1, y1, z1, x2, y2, z2):
"""Recibe las coordenadas de dos vectores en R3 y devuelve su diferencia"""
dif_x = x1 - x2
dif_y = y1 - y2
dif_z = z1 - z2
return dif_x, dif_y, dif_z
def norma(x, y, z):
"""Recibe un vector en R3 y devuelve su norma"""
return (x**2 + y**2 + z**2) ** ... |
85728b6135540121b326be556fa348ca22344c3f | angelmary77/test-repo | /GetPowerValuesUsingLambdaFunction.py | 350 | 3.703125 | 4 | import logging
"""z = lambda x,y:x+y
print z(1,2)"""
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
logging.info('doing calculation')
squares1=list(map(lambda x: x ** 2, [10,20,30,40]))
print squares1
numbers=[1,2,3,4]
squares2=list(map(lambda x:pow(x,2), numbers))
print squares... |
56d9052fd76cc67d535d7fba4d06f1d5fdb30b74 | yogisen/python | /basedeA-Z_-datascience/textVSdict.py | 849 | 3.875 | 4 | f = open("texte.txt", "r", encoding="utf-8")
texte = f.read()
g = open("dictionnaire.txt", "r", encoding="utf-8")
vocabulary = g.read()
tokenized_vocabulary = vocabulary.split(" ")
def clean_text(text_string, special_caracters, replacement_string):
cleaned_string = text_string
for string in special_caracters... |
d2bab1c0b17217f7d8924f58310d69f9fe68ebc7 | Vineet2000-dotcom/python | /algorithms/graphs/Bron-Kerbosch.py | 941 | 3.609375 | 4 | # dealing with a graph as list of lists
graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]]
#function determines the neighbors of a given vertex
def N(vertex):
c = 0
l = []
for i in graph[vertex]:
if i is 1 :
l.append(c)
c+=1
return l
... |
3454e8b6e5c4970a2bed998e42c4b6c61d8b20b8 | gcross/dmrg101_tutorial | /solutions/two_qbit_system.py | 3,453 | 3.53125 | 4 | #!/usr/bin/env python
""" Calculates the entanglement entropy of a two qbit system
Calculates the von Neumann entanglement entropu of a system of two
spin one-half spins restricted to the subspace of total spin equal to
zero.
Usage:
two_qbit_system.py [--dir=DIR -o=FILE]
two_qbit_system.py -h | --help
Options:
... |
61e3306c1ffdd8423421e017c8d118d363df661f | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH15/EX15.21.py | 631 | 4.25 | 4 | # 15.21 (Binary to decimal) Write a recursive function that parses a binary number as a
# string into a decimal integer. The function header is as follows:
# def binaryToDecimal(binaryString):
# Write a test program that prompts the user to enter a binary string and displays its
# decimal equivalent.
def binaryToDeci... |
52a800be400e1dbab18c89c0c3c46d2246d80ba5 | rotemgb/LeetCode | /Two Sum.py | 538 | 3.546875 | 4 | class Solution(object):
def twoSum(self, nums, target):
# Create Hash Table
d = {}
# looping through pairs of indecies and numbers
for i, num in enumerate(nums):
# create a new target to search in dictionary
new_target = target - num
# if not ... |
49e882f90eb31359dc279364fa73d3b44fc8906e | eprj453/algorithm | /PYTHON/BAEKJOON/10870_피보나치수5.py | 175 | 3.59375 | 4 | fibo = [0, 1] + [None] * 19
def get_fibo(n):
if fibo[n] is not None:
return fibo[n]
return get_fibo(n-1) + get_fibo(n-2)
n = int(input())
print(get_fibo(n)) |
550f55b4f8a332a41f81b9621f6fadd3c65b2db6 | ChristopheTeixeira/swinnen | /chapitre-3/part3.py | 113 | 3.671875 | 4 | a = 7
if a > 0 :
print("a est positif")
elif a < 0 :
print("a est négatif")
else:
print("a est nul") |
47bc2d0f4202671907fe80c4a004eb03388ff2ad | mgmarino/RunDB | /utilities/signal_handler.py | 890 | 3.5 | 4 | import threading
"""
SignalHandler handles signals being sent to and from a process.
"""
class SignalHandler:
msg_semaphore = threading.Event()
msg_die = threading.Event()
@classmethod
def msg_handler(cls, signum, frame):
# We've received a msg from the user,
# check the msg semaphore.... |
8f713812f1c2be59cc144a0589b946172ad6d44b | dineshpabbi10/Python | /randint.py | 383 | 3.65625 | 4 | import random
# x = random.randint(5,10)
# print(x)
data = [1,2,3,4,5,10]
def shuffle(data):
data2 = list()
un = list()
length = len(data)
while(len(data2) != length):
x = random.randint(0,length-1)
check = (x in un)
if(not check):
un.append(x)
... |
0f9c7e283384bd7bad98a50931ad27f01ba83c50 | swcide/algorithm | /hanghae/05_4344(평균은넘겠지).py | 1,677 | 3.5625 | 4 | """
대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다.
당신은 그들에게 슬픈 진실을 알려줘야 한다.
첫째 줄에는 테스트 케이스의 개수 C가 주어진다.
둘째 줄부터 각 테스트 케이스마다 학생의 수 N(1 ≤ N ≤ 1000, N은 정수)이 첫 수로 주어지고,
이어서 N명의 점수가 주어진다. 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다.
테스트케이스 = n
list [0] = 학생 수
"""
n = int(input())
for i in range(n):
score = list(map(int, input().spl... |
7b9af265e7fd8157d973923f733dbb72cbb1d5b0 | yWolfBR/Python-CursoEmVideo | /Mundo 1/Exercicios/Desafio013.py | 136 | 3.53125 | 4 | n = float(input('Digite seu salário atual: R$'))
print('Com o aumento, seu novo salário será R${:.2f}'.format(n + (n * (15 / 100))))
|
01b3f83516359dc8d3b10cda5eec101c064d5343 | rishabh-in/DataStructure-Python | /Pattern/RecPattern.py | 385 | 3.8125 | 4 | ## Solid rectangle star pattern
r = 3
c = 5
for i in range(r):
for j in range(c):
print("*", end=" ")
print()
print("\n")
## Hollow rectangle star pattern
row = 4
col = 7
for i in range(row):
for j in range(col):
if i == 0 or i == row-1 or j == 0 or j == col - 1:
print("*", en... |
4d912cce98e72ee7c8f7b2a4193746fe7343d8cd | shikhasingh1797/List | /sum_of_less_than_50_marks.py | 358 | 3.671875 | 4 | students_marks=[23,45,67,89,90,54,34,21,34,23,19,28,10,45,86,9]
length=len(students_marks)
index=0
sum=0
sum1=0
while index<len(students_marks):
if students_marks<50:
sum=sum+students_marks[index]
else:
sum=sum+students_marks[index]
index=index+1
print("total marks less than 50 = ",sum)
prin... |
d5b132b392a91b3cc1c11e2eb70ff527e1d1ae5c | sanjeevseera/Python-Practice | /Data-Structures/String/part2/P036.py | 286 | 4.125 | 4 | """
Write a Python program to format a number with a percentage
"""
x = 0.25
y = -0.25
print("\nOriginal Number: ", x)
print("Formatted Number with percentage: "+"{:.2%}".format(x));
print("Original Number: ", y)
print("Formatted Number with percentage: "+"{:.2%}".format(y)); |
8428e8242e64d80456db49800909587b8fa1b747 | NishanthMHegde/NumpyPractice | /Reshaping.py | 690 | 4.84375 | 5 | import numpy as np
#Reshaping can be used to change the shape of an array
#A shape of an array is given by (m,n) where m is the number of rows and n is the number of columns
#Let us take a 1D array and reshape it into a 2D array with (3,3) shape
x = np.arange(9)
print(x)
#After reshaping
x = x.reshape(3,3)
print(x)... |
a0889882249bd3880ea9797fdd47a77f12088dfb | barinova-iv/geek-python-09-20 | /homework03/task05.py | 1,297 | 3.890625 | 4 | # Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.Пользователь может продолжить
# ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных
# чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится
# сп... |
f65116c972d75671552da880725ca24b95acc486 | natnew/Python-Projects-Sort-Numbers | /sort numbers.py | 1,298 | 4.15625 | 4 | digits = [2, 3, 4, 5,0, 1, 9, 8, 10, 6]
print('Printing original list:')
print(digits)
digits.sort()
print('Sorting the list:')
print(digits)
digits.reverse()
print('Reversing the list:')
print(digits)
digits.sort(reverse=True)
print('Reversing the list:')
print(digits)
more_digits = [1, 0, 2, 3, ... |
59448c4ca19215cb4400b4c26b7cfae62ea0a973 | gabriellaec/desoft-analise-exercicios | /backup/user_026/ch45_2020_04_12_13_39_28_520923.py | 299 | 3.921875 | 4 | numeros=int(input("digite um número inteiro positivo: "))
lista=[]
while numeros>0:
lista.append(numeros)
numeros=int(input("digite um número inteiro positivo: "))
i=0
invertida=[0]*len(lista)
while i<len(invertida):
invertida[i]=lista[len(lista)-i]
i+=1
print(invertida) |
743c932141bb70752e5d0437dbf866966d6d0b30 | obliviateandsurrender/Course-Portal | /app/students/models.py | 614 | 3.515625 | 4 | from flask_sqlalchemy import SQLAlchemy
from app import db
class Student(db.Model):
__tablename__ = 'student'
# Define the fields here
roll = db.Column(db.String(8), primary_key = True)
name = db.Column(db.String(200))
year = db.Column(db.String(3))
#courses = db.Column(db.String(1000))
... |
9d299caef0eb2d51dc614c15c249dd4f95d5ecd4 | jamtot/CodingBatPython | /Warmup-2/string_splosion.py | 686 | 3.703125 | 4 | # Given a non-empty string like "Code" return a string like "CCoCodCode".
from test import Tester
def string_splosion(str):
result = ''
for i in range(len(str)):
result += str[:i+1]
return result
Tester(string_splosion('Code'), 'CCoCodCode')
Tester(string_splosion('abc'), 'aababc')
Tester(s... |
9748b25ae387900619ea3fee3407ea7ff2de8909 | smahmud5949/All-code | /24.py | 124 | 4.1875 | 4 | num=int(input("Enter a number: "))
n=1
while num>0:
n=n*num
num=num-1
print ("Factorial of the given number is ",n)
|
5cc699392432d3c3539c860ed6c499f31b0a068b | alexeynico/les | /program.py | 160 | 3.65625 | 4 | phones = ["iPhone Xs", "Samsung Galaxy S10", "Xiaomi Mi8"]
phones.append("iPhone Xs")
print(phones)
ln = len(phones)
print(ln)
print(phones.count("iPhone Xs"))
|
5a4388ee81d7dd3c43bca2717699c5d161575847 | ejmoyer/python-projects | /ex17.py | 591 | 3.640625 | 4 | # ex 17
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses.")
print(f"You have {boxes_of_crackers} boxes of crackers.")
print("That's enough for a party!")
#we can give it numbers directly
cheese_and_crackers(20, 30)
# or we can use variables
amount_of_chees... |
c082f303bcc3c5e6c1f131182fc162cb1503711f | patiregina89/Exercicios-Logistica_Algoritimos | /Exercicio2_Ordemdesc.py | 1,016 | 4.3125 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício 2 - Números inteiros decrescente")
print(("*"*42))
#2. Faça um Programa que leia um vetor d... |
65c6feb79bbeecc0c5f1444506982280123a7c1d | jlmasson/Ayudant-asFundamentos2017-I | /Funciones-Arreglos/TicTac.py | 2,495 | 3.578125 | 4 | def dibujar_linea(width, edge, filling):
print(filling.join([edge] * (width + 1)))
def mostrar_ganador(player):
if player == 0:
print("Tie")
else:
print("Player " + str(player) + " wins!")
def revisar_ganador_fila(row):
"""
Return the player number that wins for that row.
If there is no winner, return 0.
... |
62e96c00c8872087cf20eec1e93bfbbb1559c555 | TolentinoDev/Computer-science-130 | /Computer Science 130 copy/RyanTolentinoxassignment0.py | 2,261 | 4.3125 | 4 | #Ryan Tolentino
#8-18-2016
#Assignment 0
print('assignment: Assignment 0')
print('programmer: Ryan Tolentino')
print('date: 8/16/2016')
print('Correct Answers')
print('Problem 1')
print('Check if the first character of my first name "Denny" is the same as')
print('the first character of your name "Ryan"')
firstNam... |
fb64f1f221b017bfd2dd95b6425a7d89330ac21f | Fischerlopes/EstudosPython | /cursoEmVideoMundo2/ex045.py | 1,494 | 3.96875 | 4 | import time
import random
print(' === JOGO JOKENPO === ')
print(''' ESCOLHA SUA OPCÃO
[ 1 ] - PEDRA
[ 2 ] - PAPEL
[ 3 ] - TESOURA''')
jogador = int(input('Qual é a sua jogada ? '))
print('Vamos ao jogo!!')
time.sleep(1)
print('Jo')
time.sleep(1)
print('Ken')
time.sleep(1)
print('Po')
list = ['Pedra','Papel','Tesour... |
fd0401194f81aa364d99b1631c4399fef7760700 | monkeyking/getIOU | /get_iou.py | 1,942 | 3.59375 | 4 | def xywh(bboxA, bboxB):
"""
This function computes the intersection over union between two
2-d boxes (usually bounding boxes in an image.
Attributes:
bboxA (list): defined by 4 values: [xmin, ymin, width, height].
bboxB (list): defined by 4 values: [xmin, ymin, width, height].
(... |
f5a5a8c755529ff9a01512da1ae50cfab187184e | thor4/Computational-Neuroscience | /models/supervised/mlp.py | 4,412 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 09:31:24 2018
@author: bryan
"""
import numpy
# sigmoid function from scipy.special
import scipy.special
# define a neural network class that can be initialized, trained and queried
class neuralNetwork:
# initialize the network
def __init__(self, input_nodes... |
35e570f2627249951580740343ed7fe5b6acfa8f | Jfprado11/holbertonschool-higher_level_programming | /0x0A-python-inheritance/11-square.py | 718 | 4.1875 | 4 | #!/usr/bin/python3
"""A method that holds a class
witch it inherates from the class
rectangle
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""a class witch holds
an inheratence of rectangle
"""
def __init__(self, size):
""" initiation of the class
con... |
c872635443a38a5e30a464cd28237f06cc02b126 | vikramraghav90/Python | /van/van_fizzuzz_2.py | 761 | 4.40625 | 4 | """ 2. Write a function called fizz_buzz that takes a number.
- If the number is divisible by 3, it should return “Fizz”.
- If it is divisible by 5, it should return “Buzz”.
- If it is divisible by both 3 and 5, it should return “FizzBuzz”.
- Otherwise, it should return the same number.
"""
def fizz_buzz (a):
if a... |
93a6775e32a1a12637a2102ab3fa3e958871eeb7 | Adam-Petersen/secret-santa | /graph.py | 4,381 | 3.5625 | 4 | import random
from random import randint
from random import shuffle
class Graph:
def __init__(self, people):
self.people = people
self.targeted = {} # Specifies whether a person is currently being targeted
self.old_edges_collection = {} # Used in assigning algorithm for restoring destroyed edges
self... |
bff4eba7d2e064c44b32d162be96a09087c141ae | codicevitae/learningtocode | /1_Assignment_Statements/problem_1.py | 510 | 4.375 | 4 | # We have to convert the input to a number. Here we use an int, but we could use a float()
# so the user could enter things like 21.4
fahrenheit = int(input("Enter your Fahrenheit temperature: "))
# Notice that because there is division in this formula, that even if every other number in it
# is an integer, the answer... |
811e92443e4ac330a149e84649bc0e1328470b49 | dummy3k/Project-Euler | /problem039/solve.py | 1,009 | 3.515625 | 4 | import doctest
import math
from euler_tools.misc import StopWatch
max_perimeter = 1001
def cnt_solutions(perimeter):
"""
>>> cnt_solutions(120)
3
"""
retval = 0
for a in range(1, perimeter / 2):
for b in range(a + 1, perimeter / 2):
c = perimeter - a -b
... |
7c5ff79a909e7cb1ea13aada45c1ace861aa2872 | AaronAS2016/Sudoku_Solver_EDD | /reader.py | 1,971 | 4.21875 | 4 | # TODO:
# [] Leer archivo
# [X] Leer csv
# [X] Excepciones
# [] Completar docs
import os
import csv
class Reader():
"""
A class to read Files
Attributes
----------
filepath : str
the path of the file that want to read
Methods
----------
setFile(filepath)
change the... |
4f2be28714a913de52b5ca9abda25912b0e04096 | yask123/PracticeHR | /selectionsort.py | 412 | 3.578125 | 4 | def select_sort(alist):
for i in range(len(alist)):
max_num = alist[0]
for j in range(len(alist) - i):
if alist[j] >= max_num:
max_num = alist[j]
max_num_index = j
alist[max_num_index], alist[len(alist) - i - 1] = alist[len(alist) - i - 1], alist[m... |
931d483c759128ad29b634224705673f9f1f2a53 | DebojyotiRoy15/LeetCode | /75. Sort Colors.py | 619 | 3.546875 | 4 | #https://leetcode.com/problems/sort-colors/
if len(nums) == 1:
return nums
elif len(nums) == 2:
if nums[0] > nums[1]:
nums[0], nums[1] = nums[1], nums[0]
return nums
else:
hash = {0: 0, 1: 0, 2: 0}
for... |
5d3629827da18118869f958892a5f836b9615d45 | amouhk/redfish_utils | /utils.py | 480 | 3.625 | 4 | # Foncutions utile sur les string
# Extraction d'une chaine de caractere entre 2 chaines
def find_between(s, first, last):
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return ""
def find_between_r(s, first, last):... |
82ffc32e1c8d100450b4b9c75501b578804651be | NunationFL/FPRO | /raise_exception.py | 192 | 3.640625 | 4 | def raise_exception(alist, value):
out=[]
for elem in alist:
if elem <= value:
out.append(ValueError("{} is not greater than {}".format(elem,value)))
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.