blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bf0c9587e2b002eeaf268c0772500bbf0462f5e0 | adamsdenniskariuki/andelabootcamp | /test_loan.py | 854 | 3.8125 | 4 | import unittest
from loan_calculator import loan_calculator
#class to hold the test cases for the loan calculator
class LoanCalculator(unittest.TestCase):
#test to determine if the loan calculator works
def test_it_works(self):
self.assertEquals(loan_calculator(100000, 12, 12), 112000)
#test to ensure the user ... |
43f8b364c5f5d43067ac60d98c5169579039ec8b | 999010alex/python-and-algorithms | /december22cw.py | 1,110 | 3.90625 | 4 | '''
1
'''
balance=100
intrest=1.1
print(balance*intrest**7)
'''
2
'''
savings=100
factor=1.10
print(savings*factor**7)
result=194.8717
'''
3
'''
string="compound interest"
boolean=True
'''
4
'''
'''
5
'''
print('I started with $100, and now I have $194.87, great!')
'''
1
'''
print("Hello","World","!")
'''
2
'''
#Yo... |
f7e15b4811b82823983cd7a3b3a4b03aa12a17ae | cIvanrc/problems | /ruby_and_python/2_condition_and_loop/guess_game.py | 525 | 4.09375 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
from random import randint
def guess_game():
i = randint(1,9)
print(check_response(i))
def check_response(i):
number = int(input("D... |
cd1d4e74b81f887a3823fde206322acadf985a62 | nanli-7/algorithms | /994-rotting-oranges.py | 2,629 | 3.9375 | 4 | """ 994. Rotting Oranges - Easy
## breadth-first search
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten
oran... |
fbc641fbfe051f99816a68d61f84cd3f2d05d219 | avengerryan/daily_practice_codes | /four_sept/programiz/three.py | 219 | 4.3125 | 4 | # Finding the square root
# Pre filled number
#num=9
# Taking input from the user
num=float(input('enter a number: '))
num_sqrt=num**0.5
print('the square root of %0.3f is %0.3f'%(num, num_sqrt))
|
7fc21455fe1e9c298171688034df46be7fa00613 | AnixDrone/QuestionGenerator | /question_generator.py | 1,254 | 3.546875 | 4 | import os
while True:
try:
import docx
break
except:
os.system("pip install docx")
def newDoc(filename):
doc = docx.Document()
doc.save(filename)
return doc
def loadDoc(filename):
return docx.Document(filename)
def newQuestion(file, file... |
d64a6cdf95b62df3960dc1de508ab0c8c9b552c1 | sachasi/W3Schools-Python-Exercises | /src/05_Numbers/01_float_method.py | 271 | 4.625 | 5 | # Instructions: Insert the correct syntax to convert x into a floating point number.
x = 5
# Solution: float()
x = float(x)
print(x)
'''
The float() method can be used to transform an int to float.
Read more here: https://www.w3schools.com/python/python_numbers.asp
'''
|
048694c1b0fb6cac9751edcc4748a023f70eb7e3 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/ovdjon001/question4.py | 751 | 3.5 | 4 | """question 4
20 April 2014
by Jonathan Ovadia"""
def main():
marks = input("Enter a space-separated list of marks:\n").split(" ")
print(histogram(marks))
def histogram(l):
fail = "F |"
third = "3 |"
lower_second = "2-|"
upper_second = "2+|"
first = "1 |"
for i in range(len... |
bef10f95ceccfa83d6a6203c070a1a340e587fc2 | aumaro-nyc/leetcode | /trees/199.py | 1,160 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(s... |
bc1268e26aa7b4de94718725a09272f5a7c008b8 | Gaurav-dawadi/Python-Assignment-II | /question16.py | 1,722 | 4.1875 | 4 | """Imagine you are creating a Super Mario game. You need to define
a class to represent Mario. What would it look like? If you aren't
familiar with SuperMario, use your own favorite video or board game
to model a player."""
class fifaPlayer():
def __init__(self, name, age, position, nationality, overallRating):
... |
c358d14d4aba8db12aaddee3f837a2d5383bc811 | tiavlovskiegor24/Algorithms | /assignment2.py | 1,464 | 4.1875 | 4 | from random import randint
def median(points):
for point1 in points:
for point2 in points:
for point3 in points:
if points[point1] < points[point2] and points[point2] < points[point3]:
return point2
def swap(array,i1,i2):
swap = array[i1]
array[i1] ... |
a9ef46e598905edfd8d2f3f0454a47d74ab987e5 | Uzbec/mini_paint | /main.py | 834 | 3.609375 | 4 | from sys import argv
import os
import ft_len
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
if len(argv) == 2:
a = argv[1]
elif len(argv) > 2:
print("Error: a lot of arguments")
a = None
print()
else:
a = input()
if " " in a:
print("Error: a lot of arguments")
... |
61399623115b8bc74758aac67036ef7a8fec97e6 | thegreatcodini/mac_address_app | /mac_address.py | 938 | 4.03125 | 4 | #!/usr/bin/env python3
import sys
import requests
import re
def check_mac(mac):
"""use this function to check if a string supplied is a mac address"""
return re.match('[0-9a-f]{2}([-:.]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$', mac.lower())
def getCompany():
"""use this function to query the macaddress.io API w... |
8540f0543c8f96ab79f7b7bb8241517b4268998d | bp2070/vr_software_renderer | /Geometry.py | 5,247 | 3.984375 | 4 | """
Bryan Petzinger
Vector & Matrix based on: http://www.math.okstate.edu/~ullrich/PyPlug/
"""
import math
from numbers import Real
from operator import add, sub, mul
class Vector(object):
def __init__(self, data):
self.data = data
def Len(self):
return math.sqrt(reduce(add, map(lambda x: math.pow(x, 2), ... |
ea01738e54dd60d15c3f3e9ca51d5ddc311b2773 | karacanil/BasicProjects | /sudokusolver.py | 2,436 | 3.59375 | 4 | import time
# Starting the timer
start_time = time.time()
# Inserting the sudokus in a 9x9 form
#Example1
inp = [[0,0,0,2,0,0,0,0,9],
[0,0,0,0,9,0,0,3,6],
[0,0,0,0,0,5,1,4,0],
[0,3,0,0,4,6,8,7,0],
[1,0,0,0,2,0,0,0,3],
[0,7,2,3,5,0,0,1,0],
[0,2,5,8,0,0,0,0,0],
[9,4,0,0,... |
8a88ed616fea1b4806c741092040ec3f28ffddaa | g-hurst/Python-For-Teenagers-Learn-to-Program-Like-a-Superhero-codes | /super hero quiz.py | 866 | 3.625 | 4 | wonderBoyScore = 82
#intro text
print("aCongrats on finnishing your Super-Hero Intelligence and Reasoniong Test.")
print("or, S Q U I R T for short.")
print("lets see if you passed.")
print("A passing score means you are liscenced to be a sidekick.")
#checks to see if Wonder Boy passed or not
if wonderBoySco... |
7447000604ba079441bfd82b99a03bd2e8de26fb | douradodev/Uri | /Uri/1096_v2.py | 203 | 3.53125 | 4 | def imprime_seq(I, J, num=3):
if num:
print('I={}'.format(I), 'J={}'.format(J))
imprime_seq(I, J-1, num-1)
def seq_IJ02(I=1, J=7):
if I <= 9:
imprime_seq(I,J)
seq_IJ02(I+2, J=7)
seq_IJ02()
|
a61b1c58115a09357bd9008373a0f2567e7e4a12 | dylanawhite92/Python-Graphics | /Simple Code Blocks/graphics/turtle/ClickSpiral.py | 518 | 4.125 | 4 | import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
# List of colors available
colors = [
"red", "yellow", "blue", "green",
"orange", "purple", "white", "gray"
]
# Define function for drawing spirals of random colors and sizes on click
def spiral(x,y):
t.pencolor(ran... |
305cfb82d3e69a53a9ccc2d72940e1af30ce6879 | midhunmdrs/Python-Projects | /loops/while_loops.py | 212 | 4.03125 | 4 | i = 6
while(i >= 1):
print("Rocky Bai" , end = " ") #end is used to print in same line
i = i - 1
j = 4
while(j >= 1):
print("rocks" , end = " ")
j = j - 1
print()
|
954e6f9ab4770826ad54bc799a054515b8ea85e2 | HashtagPradeep/python_practice | /control_flow_assignment/Assignment- Control Flow_Pradeep.py | 886 | 4.46875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ---
# ---
#
# <center><h1>📍 📍 Assignment: Control Flow 📍 📍</h1></center>
#
# ---
#
# ***Take 3 inputs from the user***
#
# - **What is your Age?** (Answer will be an Intger value)
# - **Do you eat Pizza?** (Yes/No)
# - **Do you do exercise?** (Yes/No)
#
# #... |
b9e0ca60ac96ea375d02b3effe7f9e86076f62c1 | Ruotongw/The-Truth-of-Asian-Restaurants | /scraping.py | 4,888 | 3.546875 | 4 | #Eric Mok, Siddhant Singh, Ruotong Wang
#COMP 123 Lian Duan
# In this program we do web-scraping from Yelp.com to build a database
# of Chinese Restaurants in the Twin Cities
#Requires BeautifulSoup to work.
from bs4 import BeautifulSoup
import urllib.request
import urllib.error
import json
import csv
... |
0316d5567dbc85f94ea4a655a2872014b813b7de | BogomilaKatsarska/Python-Advanced-SoftUni | /Lists as Stacks and Queues - E1Q1.py | 140 | 3.515625 | 4 | input = list(input().split())
stack = []
while input:
last_el = input.pop()
stack.append(last_el)
print(f"{' '.join(stack)}") |
59e653746c5d1c8cd033d6612d0d4f0c466c4112 | chrisglencross/advent-of-code | /aoc2021/day17/day17.py | 1,044 | 3.703125 | 4 | #!/usr/bin/python3
# Advent of code 2021 day 17
# See https://adventofcode.com/2021/day/17
import re
with open("input.txt") as f:
bounds = [int(value) for value in re.match("^target area: x=([-0-9]+)..([-0-9]+), y=([-0-9]+)..([-0-9]+)$", f.readline().strip()).groups()]
def hit_target(fire_dx, fire_dy, bounds):
... |
dd10e1071576866fb2dc22692db6e1e96a998f36 | setooc/python-programacion-uade | /Progra I - PYTHON/TP1/ej_7_modif.py | 360 | 4.09375 | 4 | def concatenar_numero (num1, num2):
aux = num2
count = 0
while (aux > 1):
aux = aux /10
count = count + 1
num1 = num1 * (10**count)
num = num1 + num2
return num
num1 = int(input("ingrese un numero: "))
num2 = int(input("Ingrese otro numero: "))
num3 = concatenar_numero(num1, nu... |
bd2871786201e5d6667ff10b449a3ec536bba23a | JONGSKY/Gachon_CS50_Python_KMOOC | /code/11/finally_exception.py | 209 | 3.875 | 4 | for i in range(0, 10):
try:
result = 10 // i
print(i, "------", result)
except ZeroDivisionError:
print("Not divided by 0")
finally:
print("종료되었습니다.")
|
233802acbf9e19028a53521b75d6e780d616e814 | Vance23/Homework_Ivan_Lihuta | /hw_17.py | 550 | 3.734375 | 4 | import math
# квадратное уравнение (ax**2 + bx + c = 0)
# d - дискриминант
a = 10
b = 2
c = 0
def solve_quadratic_equation(a, b, c):
d = b ** 2 - 4 * a * c
print(d)
if d > 0:
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
return(x1, x2)
e... |
dee2235dc4dc85be61fd707782906e0dcf70e8c5 | Zhuhh0311/leetcode | /stack/backspaceCompare.py | 2,185 | 3.796875 | 4 | #844. 比较含退格的字符串
#给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。
#注意:如果对空文本输入退格字符,文本继续为空。
'''
示例 1:
输入:S = "ab#c", T = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。
'''
#自己的想法,将两个字符串都重构,然后比较是否相等,使用栈存储重构后的结果
#思路没问题,但是代码冗余
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
stack_s, stack... |
5a15d172a0595061722c6b7e079cb9ce9e918c0a | AkankshaRakeshJain/CodeChef | /FLOW006_SumOfDigits.py | 153 | 3.859375 | 4 | user = int(input())
for value in range(user):
number = input()
sum = 0
for values in number:
sum += int(values)
print(sum)
|
17a61aa20200a17de4bf1998ab524a96d24762c5 | rohanprateek/pythonprograms | /printingmatrixdiagonally.py | 594 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 19:36:10 2021
@author: Rohan Prateek
"""
class Solution:
# @param A : list of list of integers
# @return a list of list of integers
def diagonal(self, A):
n = int(2 * len(A) - 1)
res = [list() for i in range(n)]
print(res)
... |
2e36b810b128d7d5bef232a6dd9efcfadc86642c | ankit96/rejigthesystem | /src/clean.py~ | 983 | 3.75 | 4 | '''
1)cleaning every word from tweet
2)input=list of words,op: list of cleaned words
'''
__author__ = 'ankit'
from classes import stopwords
def clean(parliament):
redundant=[':',",",")",".","(",";","/","|","-",'?','=','+']
i=0
flag=0
newobj=[]
m=0
#print parliament
for a in parliament:
#print str(i)+' '+... |
ae2e919c0d420daf88f16a0356ab438c22403417 | antonyaraujo/ClassPyExercises | /Lista02/Questao13.py | 689 | 3.96875 | 4 | # Escreva um programa para calcular o salário semanal de uma pessoa, determinado pelas
# seguintes condições. Se o número de horas trabalhadas for menor ou igual a 40, a pessoa
# recebe 8 reais por hora trabalhada, se não a pessoa recebe 320 reais fixos e mais 12 reais
# para cada hora trabalhada que excede 40 horas. (... |
a617695c04656236b944a2106b764fa02e2cedeb | chenxu0602/LeetCode | /1352.product-of-the-last-k-numbers.py | 2,683 | 3.59375 | 4 | #
# @lc app=leetcode id=1352 lang=python3
#
# [1352] Product of the Last K Numbers
#
# https://leetcode.com/problems/product-of-the-last-k-numbers/description/
#
# algorithms
# Medium (42.54%)
# Likes: 397
# Dislikes: 23
# Total Accepted: 21.4K
# Total Submissions: 50.3K
# Testcase Example: '["ProductOfNumbers",... |
1a5b0b2a690cf5030d12a6cbd091c6f18aabaffa | brennon/eimutilities | /eim/tools/analysis.py | 25,466 | 3.65625 | 4 | import numpy as np
import scipy.interpolate
def bioemo_readings_to_volts(readings):
"""
Convert readings from the BioEmo sensor range to voltages.
Parameters
----------
readings : array_like
The readings to be converted
Returns
-------
out : float or :py:class:`numpy.ndarray`
... |
70b9497612178b97d69e5f675cfac26255819ed0 | maxmartinezruts/Algorithms-Data-Structures | /largest_palindromic_sequence.py | 900 | 3.96875 | 4 | """
Author: Max Martinez
Date: October 2019
Description: Given a string s, determine which is the longest palindrome hidden in s allowing to remove any character
but not sorting s
Complexity: O(n^2)
Proof:
Complexity = # guesses * time_guess = n^2 * O(1) = O(n^2)
"""
memo = {}
def L(s):
if s in memo:
re... |
47bc879c1917a2ce464d3a26087918bcc48fbcd7 | JavierEsteban/Basico | /1.- Tipos De Datos/2.- Estructura de Datos.py | 1,820 | 4.3125 | 4 | # Estructura de Datos Python
'''
###############################
######### Listas : ##########
###############################
'''
### Listas : Las listas son esructuras flexibles que puede tener varios tipos de datos... " SON MUTABLES.. "
lista_numeros = [1,2,3,4,5]
print(lista_numeros)
lista_textos = [1,'2',3,... |
a89c0073bf567dc06b4685f08f5497dd5407da69 | Aasthaengg/IBMdataset | /Python_codes/p02701/s706011545.py | 99 | 3.53125 | 4 | n = int(input())
dict = {}
for i in range(0, n) :
s = input()
dict[s] = 1
print(len(dict)) |
1d93668af1b36e741a33e55667fda9919c2c34b3 | mtlock/CodingChallenges | /CodingChallenges/Project_Euler/Euler_3.py | 537 | 4.03125 | 4 | #The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143?
#Change it to enter a number and find largest prime factor
num=raw_input("Enter an odd integer: ")
fnum=float(num)
i=3
lst=list()
while i<=fnum:
k=3
a=0
if fnum%i==0:
while k<i:
... |
747ab5c511d3a364309ea149398ded92eb23d748 | Mil0dV/AoC-2018 | /day2.py | 655 | 3.96875 | 4 | filename = "input-day2.txt"
# filename = "input-day2-test.txt"
def calculate_checksum():
file = open(filename, "r")
doubles = 0
triples = 0
for line in file:
double_letters = set()
triple_letters = set()
for char in line:
if line.count(char) == 2:
do... |
15df55056f20f311bb6a66a7ebcaf1477f69bc74 | ksheetal/MCA_NN | /hello.py | 1,471 | 3.703125 | 4 | #print("Hello! Python")
#SHEETAL KUMAR
import numpy as np
def AND(x1, x2):
x = np.array([1, x1, x2])
w = np.array([-1.5, 1, 1])
y = np.sum(w*x)
if y <= 0:
return 0
else:
return 1
def OR(x1, x2):
x = np.array([1, x1, x2])
w = np.array([-0.5, 1, 1])
y = np.sum(w*x)
... |
defb9f073b167c746a19c632369957d12ecf49c6 | bdejene19/tkinterPythonCourse | /OpenFilesandDialogueBoxes.py | 396 | 3.53125 | 4 | from tkinter import *
from tkinter import filedialog # is needed to open files anywhere on your computer
root = Tk()
root.title("Dialogue box")
# come back to this lesson --> @2:47:00
#initialdir allows us to get file from anywhere on computer --> note: still trying to figure it out
root.filename = filedialog.askopen... |
249a6eb0e26f754537a8448f748c9871ad8d2e10 | tanyastropheus/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.alt.py | 363 | 4.125 | 4 | #!/usr/bin/python3
def read_file(filename=""):
"""print out the entire content of a file to stdout using UTF8 encoding
Args:
filename (str): file to be printed
"""
try:
with open(filename, encoding='UTF8') as f:
print(f.read(), end="")
except (TypeError, IOError):
... |
35b3bae86a38a1c1dca0f11082ed454b0a9d1ed6 | yeshwanth2812/Python_Week2 | /Week2_basic/Group_member.py | 378 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Author: Yeshwanth
# @Date: 2021-01-04 18:58:12
# @Last Modified by: Yeshwanth
# @Last Modified time: 2021-01-09 12:30:53
# @Title: Group_member
def is_group_member(group_data, n):
for value in group_data:
if n == value:
return True
return False
print(is_group_memb... |
d6f8b49ae0583c3e6456075f995a2ba888c0965d | GhostOsipen/pyRep | /leetcode/LengthOfLastWord.py | 563 | 4.0625 | 4 | # Given a string s consists of some words separated by spaces,
# return the length of the last word in the string.
# If the last word does not exist, return 0.
def lengthOfLastWord(s: str) -> int:
count = 0
rs = s[::-1]
for i in rs:
if i == " ":
count += 1
else:
br... |
b5afe2d8912041d73a8a14aeee6f81954179b05c | mhsimpson24/algorithms | /two_color.py | 1,262 | 3.84375 | 4 | class Graph():
def __init__(self, V):
self.V = V
self.adj = [[0 * self.V] * self.V]
def twoColor(self, start):
if self.V == 0:
return "Trivially two colorable"
color = ["NULL"] * self.V
color[start] = "red"
queue = []
queue.append(start)
... |
13712aa9ee6581cdc87c817cb630001117e159b7 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - for examples.py | 415 | 4.15625 | 4 | #3.1.2.5 Loops in Python | for
# for range 1 parameter -> jumlah perulangan
for i in range(10) :
print("perulangan ke",i)
print()
# for range 2 parameter -> angka awal perulangan, angka akhir perulangan
a = 1
for i in range(3,10) :
print(i," = perulangan ke",a)
a+=1
print()
# for range 3 parameter ->... |
333dc9fd827d05719d19ac77e8611c72c25779e8 | jaredchin/Core-Python-Programming | /第十一章/练习/11-3.py | 305 | 3.578125 | 4 |
def max2(a,b):
if a > b:
return a
else:
return b
def my_max(alist):
if len(alist) == 0:
return 'Can not be None'
else:
res = alist[0]
for i in alist:
res = max2(res, i)
return res
alist = [1,2,3,4,5,6,7]
print(my_max(alist))
|
b8381abeac06851409641218402c718e708cbeaa | richartzCoffee/aulasUdemy | /templates2/dicCompre.py | 251 | 3.796875 | 4 |
numero = {'a': 1 ,'b':2}
print(numero)
[print(f"{a} {b}") for a,b in numero.items()]
lisa = [1,2,3,4,5,6]
quadrado = {valor:valor**2 for valor in lisa}
print(quadrado)
res = {nun : ('par' if nun%2 ==0 else 'impar') for nun in lisa}
print(res)
|
f7c2dc0e28916b8aac2c2cdaec206d2373d63c19 | dking6902/pythonhardwaybookexercises | /ex18.py | 460 | 3.703125 | 4 | # this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# ok that *args is pointless, do This
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# one argument
def print_one(arg1):
print(f"arg1: {arg1}")
#no arguments
d... |
bfacb7a3e3ef3ce2412532232268baa275270747 | MinecraftDawn/LeetCode | /Medium/230. Kth Smallest Element in a BST.py | 580 | 3.640625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.k = k
self.ans = root
self.inorder(root)
retur... |
e1c6ae3e024b8e094f501ce6c3fceeb878f586bd | AlexsanderDamaceno/x86-assembler | /Tokenizer.py | 3,112 | 3.609375 | 4 | from TokenTypes import TokenType
from Token import Token
class Tokenizer():
def __init__(self, filestream):
self.filestream = filestream
self.text_pos = 0
def advance(self):
self.text_pos += 1
def lookahead(self):
orig = self.text_pos
Token = self.nextToken()
self... |
55861d11eb9e3d52f6849c0840547c3035cbc622 | Nicholas1771/Blackjack | /Hand.py | 1,436 | 3.546875 | 4 | from Card import Card
class Hand:
def __init__(self, cards):
self.cards = cards
self.bust = False
def __str__(self):
string = ''
for card in self.cards:
if card.visible:
string += card.__str__() + ' '
else:
string += 'XX... |
f96fac4ed8aae32de2c69ac415a4f5681147cc75 | Rptiril/pythonCPA- | /chapter-3-pracise-set/Qno_4_findNreplace.py | 163 | 3.796875 | 4 | '''
Write a program to detect double spaces in a string.
'''
str = '''
Pake ped pe paka papita
pinku pakde paka papita
'''
s = str.replace(" "," ")
print(s)
|
585d2339578ac1bbf8a6b88b70cffcc006257ed4 | darrenredmond/programming_for_big_data_SROB | /calculator.py | 2,367 | 3.796875 | 4 | import math
class Calculator(object):
# addition
def add(self, x, y):
number_types = (int, long, float, complex)
if isinstance(x, number_types) and isinstance(y, number_types):
return x + y
else:
raise ValueError
# subtraction
def subtract(self, x, y)... |
27f66f2f6fd727f304d5aa4f9319bb9a0d033e15 | Nisar-1234/LeetCode-Hard | /1220-Count Vowels Permutation.py | 1,959 | 3.671875 | 4 | # https://leetcode.com/problems/count-vowels-permutation/
"""
Example 1:
Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
Example 2:
Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
Example 3:
Inpu... |
2ecc9286547fc1f7166caed9a7373035b3b6c84f | loveAlakazam/Homeworks2019 | /ProgramTraining/SW_Expert_Academy/1974/1974.py | 808 | 3.734375 | 4 | # 소요시간: 3시간 넘음.. ㅠㅠ
T= int(input())
test= sum(range(1,10))#45
for t in range(1, T+1):
sudoku=list( list(map(int, input().split())) for _ in range(9)) #2차원 배열생성
result=1 #초기화(겹치는 숫자가 없다고 가정)
# 행
for row in range(9):
if( sum(sudoku[row])!=test):
result=0
#열
for c... |
5d6d96933094c6c10ab536161a2b79da8e60a10b | selam-weldu/algorithms_data_structures | /leet_code/python/binary_trees/lca_with_parent.py | 580 | 3.59375 | 4 | # O(h) time, O(1) space
def lca(node_one, node_two):
def get_depth(node):
depth = 0
while node:
node = node.parent
depth -= 1
return depth
depth_one, depth_two = get_depth(node_one), get_depth(node_two)
if depth_two > depth_one:
node_one, node_two = ... |
6c028b45fa4d58940c2ea759163b13bd63e49d97 | Nimrod-Galor/selfpy | /911.py | 477 | 3.703125 | 4 | def are_files_equal(file1, file2):
"""
check if files content is equal
:param file1 file path
:type string
:param file2 file path
:type string
:return true if files content is the same
:rtype bool
"""
res = False
fo1 = open(file1, "r")
f1l = fo1.read()
fo2 = open(file... |
830ddf409cccd4910f33f4790c612b5e0fd6f33c | EEEEEEcho/requestDetail | /mutilProcessDemo/test7.py | 1,123 | 4.21875 | 4 | # 递归锁,为了将锁的粒度控制的更小,更精准,需要使用递归锁
# 缺点:很慢
import time
import threading
class Test:
rlock = threading.RLock()
def __init__(self):
self.number = 0
def add(self):
with Test.rlock: # 这里加了一把锁,执行execute方法,执行后释放
self.execute(1)
def down(self):
with Test.rlock:
... |
29aabedf4ac88aaef7d4c63615b72ead4c269a91 | havenshi/leetcode | /27. Remove Element.py | 911 | 3.53125 | 4 | class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
index = 0
while i < len(nums):
if nums[i] == val:
i += 1
else:
# 常规的交换是可以... |
642cad91d850493e612e64589eb89b39f69d222d | TahaKhan8899/Coding-Practice | /LeetCode/MissingNumber.py | 712 | 3.515625 | 4 |
# THIS IS STUPID.
class Solution:
def missingNumber(self, nums):
# nums.sort()
# print(nums)
# if len(nums) == 1 and nums[0] == 0:
# return 1
# if len(nums) == 1 and nums[0] == 1:
# return 0
# if len(nums) == 1:
# return nums[0]+1
... |
70392967b8a87b3501e26714b4f98f5166cc38f8 | itsafjal/python_stats | /percentile_score.py | 302 | 3.546875 | 4 | #! /usr/bin/python
def Percentile_calculater(scores, your_score):
cnt = 0
for score in scores:
if score<=your_score:
cnt += 1
result = (cnt*100)/len(scores)
return result
scores= [11,22,33,44,55,66,77]
your_score = 55
myresult = Percentile_calculater(scores, your_score)
print myresult
|
2fcffcf8343c050e8d5fbc08d528158276b3d8a3 | tjatn304905/algorithm | /SWEA/1232_사칙연산/sol1.py | 1,474 | 3.5625 | 4 | import sys
sys.stdin = open('input.txt')
# 후위 탐색
def traversal(n):
if 1 <= n <= N:
traversal(left[n])
traversal(right[n])
# 후위 연산식 스택에 쌓아주기
stack.append(values[n])
# 후위 연산
def calculate():
traversal(1)
# 숫자를 담아둘 스택
numbers = []
while stack:
elem = stack... |
5a773b56dbfb90839a1f23301ac47eab05a59879 | bpbethstar/assignment | /H180621T ass1.py | 170 | 3.8125 | 4 | n=10
a=[]
for i in range(0,n):
elem=int(input("Enter height of student: "))
a.append(elem)
avg=sum(a)/n
print("Average height of students is:",round(avg,2)) |
bcd5b7b01a3b05f40f069df0a61345a5830ea6f3 | ankitniranjan/HackerrankSolutions | /Python/Lists.py | 704 | 3.90625 | 4 | if __name__ == '__main__':
N = int(input())
list = []
for _ in range(N):
operation, *attr = input().split()
if operation == 'insert':
index = int(attr[0])
value = int(attr[1])
list.insert(index, value)
elif operation == 'remove':
value... |
63f38b13d2461f5f12ee8277daf2a7ce1c304fa7 | rad10/NIPScan | /nipscan.py | 7,210 | 3.5625 | 4 | #!/usr/bin/python3
from sys import argv, exit, stdin
import socket
import re
import argparse
# make sure library is installed
try:
import nmap
except:
print("Error: cannot find nmap library on platform.")
print("Please install nmap library from pip")
print("Please run either \"pip3 install python-nmap\... |
44d9757efc6221b7c4a9eb66eabadb81af089d5b | etikrusteva/python_acadaemy | /First/main.py | 1,390 | 4.125 | 4 | """
def main():
my_name = input("Name:")
print("Az sam", my_name)
def display(x):
print(x)
def test_condition():
var = input("Number:")
if (var == "5"):
int(var)
print("fire")
elif (var == "7"):
print("ne raboti")
else:
p... |
63bfc428714fda200a6ef906fe8e45b327aafe58 | wupei93/black-jack | /player.py | 2,576 | 3.5 | 4 | import random
import string
from abc import abstractmethod
from poker import Pile, ConsoleCard, Card, ConsoleCardBack
class BasePlayer:
def __init__(self, name, token=1000):
self.name = 'unknown'
self._cards = []
self.name = name
self.token = token
def __str__(self):
... |
6bd5725816b7e009fd4dd9112b9005cadadbfe0c | d1rtyst4r/archivetempLearningPythonGPDVWA | /Chapter07/tasks/vacation.py | 441 | 3.96875 | 4 | # Task 7-10
vacation = {}
poll_active = True
while poll_active:
name = input("Please enter your name: ")
vacation[name] = input("Please enter your next place for vacation :")
repeat = input("Do you have any person for the poll? (yes/no) ")
if repeat == 'no':
poll_active = False
print("\n--- P... |
e710b7a214d123351036d9647299ce61a222154b | MaFerToVel/Tarea-06 | /Tarea-6.py | 3,550 | 3.828125 | 4 | #encoding: UTF-8
#Autor: Maria Fernanda Torres Velazquez A01746537
#Descripcion: El siguiente programa, muestra un menu al usuario que le permite escoger 2 opciones, posteriormente
#mediante un ciclo while, se ejcutaran cuantas veces el usuario lo desee
def registrarColeccion(): #Registra el numero de insectos y muest... |
d8939b2a452aa02b921d68142bb10a93300d7e08 | acc-cosc-1336/cosc-1336-spring-2018-Carol-COSC1336 | /tests/assignments/test_assign9.py | 1,443 | 3.609375 | 4 | import unittest
from src.assignments.assignment9.invoice import Invoice
from src.assignments.assignment9.invoice_item import InvoiceItem
#from invoice import Invoice
#from invoice_item import InvoiceItem
class Test_Assign8(unittest.TestCase):
invoice_items = [] #list of Invoice Item instance objects
def tes... |
b5cc5f217274309e75b4b35be47d303bed574133 | MESragelden/leetCode | /Interval List Intersections.py | 516 | 3.578125 | 4 | def intervalIntersection(A, B):
out = []
i=0
j=0
while(i < len(A) and j < len(B)):
new = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])]
if (new[0]<=new[1]):
out.append(new)
if (A[i][1] > B[j][1]):
j += 1
elif(A[i][1] < B[j][1]):
... |
c3b95c2f73607105b6d35999ba3882bf9ad22ec3 | MarianaDrozd/Python-Martian-Manhunter-adv- | /homeworks/HW3_OOP_Practice/houses.py | 822 | 3.8125 | 4 | from abc import ABC, abstractmethod
class Home(ABC):
@abstractmethod
def apply_a_purchase_discount(self, discount):
raise NotImplementedError
class House(Home):
def __init__(self, address, area, cost):
self.address = address
self.area = area
self.cost = cost
def appl... |
9b90679ffe2b4af0babc8cea3bea3edbd704c267 | nontapanr/data-structures-and-algorithms | /Python5.Linked List/InsertSinglyLinkedList.py | 1,964 | 4 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size_ = 0
def __str__(self):
if not self.isEmpt... |
0322aa69cef5a1b2ae773f3ffab56f0fab58a639 | shobhit-nigam/strivers | /day4/adv_funcs/15.py | 205 | 3.765625 | 4 | lista = ['w', 'o', 'r', 'l', 'd', ' ', 'p', 'e', 'a', 'c', 'e']
def only_vowels(ch):
vowels = ['a', 'e', 'i', 'o', 'u']
return ch in vowels
listx = list(filter(only_vowels, lista))
print(listx)
|
cbab7ac982cdb7e6ff8b67f1338b21a95d5190c1 | rishikesh12/MachineLearningBasics | /PolynomialRegression/polynomial_regression.py | 1,227 | 3.53125 | 4 | # Bluffing Detector using Polynomial Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Fitting linear regression to the dataset... |
d84424cdf28d31f5896784c6eefe49c3159ac5d7 | Persist-GY/algorithm008-class02 | /Week_02/levelorder.py | 800 | 3.546875 | 4 | # https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
class Solution:
def levelOrder(self, root: 'Node'):
def helper(root, level):
if len(res) == level:
res.append([])
res[level].append(root.val)
for r in root.children:
help... |
4c64b289ba9cadb571ef46bea53be3aded7e0a9c | veerabhadrareddy143/python | /tkinter1.py | 748 | 4.1875 | 4 | from tkinter import *
window=Tk(); #creating new blank window
window.title("welcome"); #title presentation
txt=Entry(window,width=40)
txt.grid(column=20,row=13)
window.geometry('1000x1000') #mentioning size of window
lbl=Label(window,t... |
b1a2d291122ceab7ac964d693570c9ce81ef2b75 | fabiomeendes/nanocourses-python | /Cap5_Files/Functions.py | 651 | 3.796875 | 4 | def ask():
return input("What do you want?\n" +
"<I> - To insert a user\n" +
"<S> - To search a user\n" +
"<D> - To delete a user\n" +
"<L> - To list a user: ").upper()
def insert(dictionary):
dictionary[input("Type a login: ").upper()] = [
... |
3b936f01bfc2d51ed82210144b4174c0a47f78c1 | ebanner/cs381v_project | /img_info.py | 4,921 | 3.640625 | 4 | # Handles processing image path files (which define where the data is stored)
# and their associated labels.
class ImageInfo(object):
"""Loads image file paths from input files."""
_DEFAULT_IMG_DIMENSIONS = (256, 256, 1)
def __init__(self, num_classes, explicit_labels=False):
"""Sets up the initial data v... |
a1674fca2f4784b15f3380bb9160094ebdbd1b8d | CodeTools/hello-world | /python/Calulator.py | 1,336 | 4.1875 | 4 | # Ok this is inspired from some web site
# but atleast the coding is mine
# Menu Functions
def menu():
print("This is python calculator v1.0");
print("");
print("your options are");
print("");
print("1. Add");
print("2. Substract");
print("3. Multiply");
print("");
print("4. Divi... |
03c8c69556065fb99ab3927bee5c7821c94becac | RomaTk/The-basic-knowledge-of-programming | /laboratory work 3/solutions/code/1.py | 237 | 3.984375 | 4 | print("Введите три стороны: ");
a=float(input());
b=float(input());
c=float(input());
if ((a==b)or(a==c)or(b==c)):
print("равнобедренный")
else:
print("Не равнобедренный");
input(); |
d47d832d44b2da72776029bf738c86aa224cb0e9 | PacktPublishing/Python-Data-Analytics-and-Visualization | /Module 1/4/better.py | 278 | 3.53125 | 4 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 3, 6)
y = np.power(x, 2)
plt.axis([0, 6, 0, 10])
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Data Visualization using Pyplot from Matplotlib')
plt.savefig('better.png')
|
abe17ee6550bfa68bf780aa51b4ed31f91dbaeeb | sudhirkk/ML_Projects | /EmailSpamClassifiers/PerceptronClassifier/ImplementPerceptron.py | 1,988 | 4.1875 | 4 | def perceptron(xs,ys):
"""
function w=perceptron(xs,ys);
Implementation of a Perceptron classifier
Input:
xs : n input vectors of d dimensions (nxd)
ys : n labels (-1 or +1)
Output:
w : weight vector (1xd)
b : bias term
"""
n, d = xs.shape # so we have n input ... |
873805d8f5c277b4a977b4a3f58a0cc3ae58e6f6 | stuartwray/bric-a-brac | /correlations.py | 2,501 | 3.828125 | 4 | #!/usr/bin/python3
from math import *
import random
import time
# demonstration that when we sum four independent random variables, the
# correlation between the sum and any one of them is r = 0.5
def correl2(xs, ys):
# Simple-minded code from mathematical definition
#
# r = N * sum(x * y) - sum(x) * sum... |
8b94a2c51024b20bcd7bbd327a3b5271dc695d4b | kzth4/Tugas-PROKSI-Kuhhh | /Operasi_Temperatur_Suhu_Kuhhh.py | 1,982 | 4.03125 | 4 | # Nama : Kukuh Cokro Wibowo
# NIM : 210441100102
print("Operasi Temperature by Kuhhh\n")
print("---------------------------------")
print("\nSilahkan isi Nama kakak terlebih dahulu\n")
its_you = input("Nama Panggilan Kakak : ")
print("\nSelamat datang kak",its_you,"\n",
"----------------------------------"... |
a9621406b5800e2fe102d55c36210044b33ffe60 | biao111/learn_python | /set/sample3.py | 465 | 3.59375 | 4 | #集合间的关系操作
s1 = {1,2,3,4,5,6}
s2 = {6,5,4,3,2,1}
#==判断两个元素是否相等
print(s1 == s2)
s3 = {4,5,6,7}
s4 = {1,2,3,4,5,6,7,8}
#issubset()判断是否为子集
print(s3.issubset(s4))
#issuperset()判断是否为父集
print(s4.issuperset(s3))
s5 = {5}
s6 = {1,3,5,7,9}
#isdisjoint()函数判断两个集合是否存在重复元素
#True代表不存在重复元素,Fals代表存在重复元素
print(s5.is... |
bac5f443074118776ee6ec8ff0ff9fa79e2ef8a0 | JavierSada/MathPython | /Support/Mid Term P4.py | 559 | 3.6875 | 4 | print ("\nProblem 4 Mid Term")
import matplotlib.pyplot
from matplotlib.pyplot import *
import numpy
from numpy import *
figure()
x= arange(0,400.1,0.1)
y= arange(0,400.1,0.1)
y1 = 220 - 0.66*x
y2 = 372 - 2*x
y3 = [0]*len(x)
grid(True)
xlim(0,400)
ylim(0,400)
xlabel('X')
ylabel('Y')
plot(x, y1, 'cri... |
84cb0f4c01814ee40341dc56e809c80a9cc53c60 | dandocmando/Python-Answers-by-dandocmando | /PT15_15.1.py | 593 | 3.59375 | 4 | import time
import random
def l():
print("This program will ask you for a list of animals and then tell where the animal is in the list")
time.sleep(0.5)
print("Please type a list of animals with a space inbetween each")
arr = input()
print()
lst = list(map(str,arr.split( )))
time.slee... |
0f671c0a066a05a44d9694b618c8257532473ed5 | nicolepits/Security | /2-it21762/my-port-scanner.py | 1,683 | 3.640625 | 4 |
import sys
import socket
from datetime import datetime
# In this program we basically use Python's socket library to connect to a socket, and try to connect
# to each port with the socket's connect() function. There is a for getting all port ranging from 1 to
# 100. This program is in reality slow at rea... |
01f91f14ee71b2895c1ea0ef2be2175fae777024 | howardcameron2/PHY494 | /03_python/heaviside.py | 506 | 3.625 | 4 | # Heaviside step function
def heaviside(x):
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
theta = 1.
return theta
xvalues = []
thetavalues = []
for i in range(-16,17):
x=i/4
xvalues.append(x)
theta = heaviside(x)
thetavalues.append(theta)
... |
9805977d2a55806dcffd9f6cfd534bf574d673dd | TreySchneider95/geocoding-project | /geocoding.py | 1,728 | 3.75 | 4 | '''Geocoding Flask project
This program is a flask project that allows a user to input an address
and return to the user the latitude and longitude of that address.
The script requires that requests be installed as well as flask within
the python enviroment you are running the program in.
'''
import requests
from flas... |
a6146ec0ee02faa4b34f03bdf7ef6f7d27c31169 | macnaer/python-apps | /Lessons/03. OOP Intro/lib/Person.py | 758 | 4 | 4 | if __name__ == "__main__":
Person
class Person:
def __init__(self, name: str, surname: str, age: int):
self.__name = name
self.__surname = surname
self.__age = age
print("Constructor works")
def show_person_info(self):
print("Name: ", self.__name, "\nSurname: ",
... |
3b88d00fabdf7fbf63dc02a491a247d5d17cbe4d | shelcia/InterviewQuestionPython | /MasaiChallenge/minimumRouterRange.py | 1,086 | 3.78125 | 4 | # Minimum Router Range
# Problem
# Submissions
# Leaderboard
# Discussions
# There are N houses in a straight line i.e, on X-axis and K routers whose signal has to reach the entire road of houses All routers have some strength , which denotes the range of signal that it can cover in both the directions.
# The router's... |
11bec3515f21feb0091e265291f1e840bbab4ea7 | yangyali1015/webservice | /class_20190106/class_循环练习.py | 2,062 | 3.796875 | 4 | #
# a=('请输入您想要的配料:')
# active=True
# while active:
# message =input(a)
# if message =='quit':
# active=False
# else:
# print('我们会在披萨中添加此配料')
# a='请问你多大了?'
# age =()
# while True:
# age=int(input(a))
# if age <= 3:
# print('免费')
# elif 3< age<12:
# print('请支付10美元')
... |
4b6408e9411c2ce638e8cee21a063e2c32bed2f5 | chengcheng8632/lovely-nuts | /114 Flatten Binary Tree to Linked List.py | 1,412 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
... |
478c34ea5f652fcbd880b55ae7afd8652237dc18 | CharlyWelch/code-katas | /objects.py | 283 | 3.65625 | 4 | """ Kata: Creating a string for an array of objects from a set of words
#1 Best practices solution by **** and others:
"""
def words_to_object(s):
objects = s.split()
print(words_to_object("1 red 2 white 3 violet 4 green"))
# { _key : _value(_key) for _key in _container } |
e43068be614cf828b301419c16f703080c74d6a4 | bitterengsci/algorithm | /九章算法/基础班LintCode/3.1534. Convert Binary Search Tree to Sorted Doubly Linked List.py | 2,336 | 4.21875 | 4 | #-*-coding:utf-8-*-
'''
Description
Convert a BST to a sorted circular doubly-linked list in-place.
Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.
We want to transform this BST into a circular doubly linked list.
Each node in a doubly link... |
f2a5d812e3c43e78e3fafddd72beb7af8bb9a925 | sbhackerspace/sbhx-ai | /connect4/human_player.py | 520 | 3.53125 | 4 | from board import *
class Human:
def __init__(self):
pass
def SetPlayerNumber(self, player):
self.player = player
def GetMove(self, board):
board.Display()
available_moves = board.GetAvailableMoves()
while True:
print("Player ", self.player, " (", board.player_chars[self.player], "), please ente... |
2684274ababfeedba7a3e9a1b5fe0d00386346b0 | HieuDoan188/QAI_module1 | /code-lab-6.py | 329 | 3.5 | 4 | # 42
s = input()
print(s.upper())
# 43
s = input()
l = len(s)
if s != "a":
print(s[0:2]+s[l-2:l])
else:
print("")
# 44
s1 = input()
s2 = input()
s3 = s1[0:2] + s2[2:]
s1 = s2[0:2] + s1[2:]
s2 = s3
print(s1 + " " + s2)
#45
s = "The quick brown fox jumps over the lazy dog"
t = s.split()
m = " "
print(m.join(t... |
1d8d65a71f215e296d09c32157283cbee8d30a60 | vega2k/python_basic | /exercise/5char_count_dict.py | 251 | 3.75 | 4 | message = \
'It was a bright cold day in April, and the clocks were striking thirteen.'
print(message, type(message))
msg_dict = dict()
for msg in message:
print(msg, message.count(msg))
msg_dict[msg] = message.count(msg)
print(msg_dict) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.