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 |
|---|---|---|---|---|---|---|
f730d0117e713937c0b7ec55bf76563f083fdbcb | danluu/dump | /dasgupta/rosalind/3sum.py | 1,072 | 3.671875 | 4 | import collections
# Create a set of inverse of all numbers in xs.
# For every pair of numbers, check to see if the pair sums to inverse of any number.
def solve(xs):
candidates = collections.defaultdict(list)
for i in range(len(xs)):
candidates[-xs[i]].append(i)
for i in range(len(xs)):
f... |
7810702f1445f2920b22ff168d9d71d065a502ab | mir-pucrs/norm-detect | /rlist.py | 350 | 3.78125 | 4 | class rlist(list):
""" A resizeable list that allows elements to be inserted in arbitrary positions"""
def __init__(self, default):
self._default = default
def __setitem__(self, key, value):
if key >= len(self):
self += [self._default] * (key - len(self) + 1)
super(rlist,... |
dc3b73dbd6de39c321d992355879bcfdeeafec45 | wilsonify/euler | /src/euler_python_package/euler_python/easiest/p006.py | 854 | 3.625 | 4 | def problem006():
"""
s = N(N + 1) / 2.
s2 = N(N + 1)(2N + 1) / 6.
Hence s^2 - s2 = (N^4 / 4) + (N^3 / 6) - (N^2 / 4) - (N / 6).
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural nu... |
324e624d99ea53e99b055289a46ae586553fc439 | mik-79-ekb/Python_start | /Lesson_2/HW_2.5.py | 201 | 3.6875 | 4 | """
Task 2.5
"""
list = [7, 5, 3, 3, 2]
rating = int(input("Введите новый рейтинг: "))
ind= 0
for x in list:
if rating <= x:
ind += 1
list.insert(ind, rating)
print(list) |
67a38e0e53c833a52b2fc1f20914813e8edc6e0d | joalcava/College-projects | /8 Puzzle/Solver.py | 2,042 | 3.71875 | 4 | ## Important note:
## I have taken inspiration from this code:
## https://gist.github.com/thiagopnts/8015876
from Queue import PriorityQueue
class State(object):
def __init__(board, weight, level, back_state):
self.board = board
self.weight = weight
self.level = level
self.back_st... |
c9c81e4a9898ff667056c695b5e5ded93b966277 | TaiPham25/PhamPhuTai---Fundamentals---C4E16 | /Session02/Homework/number.py | 110 | 4 | 4 | from math import factorial
n = int(input("Enter number:"))
n = factorial(n)
print('Factorial of number: ' ,n)
|
e4e2c4dfa5e75c5e03ac462e570c95c5de6d94ed | ismailraju/capcha-crack | /pythonlearning.py | 349 | 3.53125 | 4 | p = [29, 58, 66, 71, 87]
print p[0::2]
print "raju "*10
name="ismail hossain raju"
print 'k' in name
print 'n' in name
print [20]*10
family=["dad","mom","sis"]
print 'sis' in family
print 'bro' in family
print len(family)
print max(p)
print list('ismail hossain raju')
p[2]=44444
print p
del p[2]
print p
p[1:1]... |
6308c6d14708d3b58e376692fdbdd935b35a0254 | 1YaoDaDa/OCEAN | /让繁琐工作简单化/GongBaLei.py | 924 | 4.28125 | 4 | # this program says hello and ask for my name
print('Hello world')
print('What is your name?') # ask for their name
myname = input()
# the return from input is 'str'.
print('It is good to meet you,' + myname)
print('The length of your name is:')
print(len(myname)) # the return from len() is int.
print('What is your ag... |
d49bc7397194aaf8b264e08c532e4863ffea4404 | ChandraSiva11/sony-presamplecode | /tasks/final_tasks/recursion/12.power_of_no.py | 283 | 4.28125 | 4 | # Python Program to Find the Power of a Number Using Recursion
def power(base, expo):
if expo == 0:
return 1
else:
return base * power(base, expo - 1)
def main():
base_no = 5
exp_no = 2
res = power(base_no, exp_no)
print("Result", res)
if __name__ == '__main__':
main() |
b5e5f1bf89e333886bd029f4d41eca806520cfd1 | Ryan-Swanson/py_sorts | /main.py | 1,692 | 4.28125 | 4 | # This file contains selection, insert, bubble, merge, and
# quick sorts, and a function to generate a random list of
# size quantity with numbers ranging from 0 to quantity
from random import seed
from random import randint
# Random list generator, with arg quantity
def random_list(quantity: int) -> int:
seed()
... |
ef0a54a287c7bf79a385a42a3c741f8edc3cde85 | f1uk3r/Daily-Programmer | /Problem-5/dp5-password-protection.py | 716 | 3.59375 | 4 | def locked():
found = 0
username = input("Enter your username: ")
user = open('username.txt', 'r')
userlist = user.read().split("\n")
user.close()
for line in userlist:
if username in line:
found = 1;
num = userlist.index(line)
break
if found == 0:
print("You are not what we are looking for.")
loc... |
bd990afe03d68f88360af872ce0505c7c4d4da0d | PhillipDHK/Recommender | /RecommenderEngine.py | 3,114 | 3.734375 | 4 | '''
@author: Phillip Kang
'''
def averages(items, ratings):
'''
This function calculates the average ratings for items.
A two-tuple is returned, where the first element is a string and the second element is a float.
'''
lst1 = [0 for x in range(len(items))]
lst2 = [0 for x in range(l... |
37156bcd0902c19e217ab17bf06ded3e6c44c9f6 | poojagmahajan/Data_Analysis | /Data Analytics/Statistics/Probability_ mass_function.py | 599 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import binom
from PIL import Image
# Number of experiments
n = 10
# Probability of success
p = 0.5
# Array of probable outcomes of number of heads
x = range(0,11)
# Get probabilities
prob = binom.pmf(x, n, p)
# Set properties ... |
59f293e2097b25927d32027dcbdea7213df2ee88 | cfowles27293/leetcode | /venv/remove_duplicates.py | 1,300 | 3.5 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) > 1:
nums = self.mark(nums)
i = 0
while(i < len(nums)-1):
if not nums[i] == None:
i += 1
... |
aa739b8bc9a5dad8702f297282bab26a4dab5bd3 | guancongyi/LeetCode_py | /75-SortColors.py | 548 | 3.71875 | 4 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
begin, i, end = 0, 0, len(nums)-1
while i <= end:
if nums[i] == 0:
nums[begin], nums[i] = nums[i], nums[begin]
... |
10e9ca52f911c5c2e2756e6c92809c4f5a4c9aef | Deepakat43/luminartechnolab | /fuctinaprgrmming/filtering.py | 799 | 3.59375 | 4 | st=[7,8,10,4,3,2]
print(list(filter(lambda num:num%2==0,st)))
print(list(filter(lambda num:num>5,st)))
empyees=[
{"eid":1000,"name":"ajay","salary":25000,"designation":"developer"},
{"eid":1001,"name":"vijay","salary":22000,"designation":"developer"},
{"eid":1002,"name":"arun","salary":26000,"designa... |
8695641c9006fda911e301c4b9e9f2e102db3b74 | jarzab3/smart_city_mdx | /test/boards/asip_writer.py | 840 | 3.78125 | 4 | __author__ = 'Gianluca Barbon'
# this library allows to make this class an abstract class
# from abc import ABCMeta, abstractmethod
# notice that in java this is an interface, but python as no interfaces!
# python 2.7 version
# class AsipWriter(object):
# __metaclass__=ABCMeta
#
# @abstractmethod
# def ... |
cf1172cb46306713289f5bbd80ccc5442ee601c9 | young-geng/leet_code | /problems/264_ugly-number-ii/main.py | 767 | 3.609375 | 4 | # https://leetcode.com/problems/ugly-number-ii/
import heapq
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
def addToHeap(heap, dictionary, key):
if key in dictionary:
dictionary[key] += 1
else:
... |
e691ff915526366092201cae24ea76e3e86ec3f5 | simtb/coding-puzzles | /daily_coding_challenges/challenges/stack.py | 1,608 | 4.21875 | 4 | """
This problem was asked by Amazon.
Implement a stack that has the following methods:
push(val), which pushes an element onto the stack
pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
max(), which returns the ma... |
781f0f5cd62ea98d3969845747aec35e02304b72 | Punchyou/DS_from_Scratch | /probability.py | 4,494 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 2 20:47:42 2019
@author: maria_p
"""
"""Conditionl Probabilities."""
"""A family with two unknown children."""
from random import choice, seed, random
from math import sqrt, exp, pi, erf
from matplotlib import pyplot as plt
from collections import Counter
def random_ki... |
d2533a610909fda15c97d699e042c1decff76852 | dongxiexiyin/leetcode | /191-number-of-1-bits/number-of-1-bits.py | 3,336 | 4.03125 | 4 | # -*- coding:utf-8 -*-
# Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
#
# Example 1:
#
#
# Input: 11
# Output: 3
# Explanation: Integer 11 has binary representation 00000000000000000000000000001011
#
#
# Example 2:
#
#
# Input: 12... |
6c1d9eb2de2831820fe6d39d4ef8b1c353ed62d0 | Kavinchandar/Programming-Data-Structures-and-Algorithms-using-Python-NPTEL-2021 | /everthing python/best_gcd.py | 136 | 3.59375 | 4 | n, m = map(int, input().split())
def gcd(n, m):
if m == 0:
return n
return gcd(m, n % m)
print(gcd(n, m))
|
0abbd7ac43014d8715f55fc340eeb17f45f8ba03 | Matheus-HX-Alves/Python | /PrimeirosExercicios/pontos.py | 330 | 4 | 4 | import math
x1 = float(input("Digite um número para x1: "))
y1 = float(input("Digite um número para y1: "))
x2 = float(input("Digite um número para x2: "))
y2 = float(input("Digite um número para y2: "))
DistanciaAB = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
if DistanciaAB >= 10:
print ("longe")
else:
print("p... |
afd705a045fbc69534f8e58bf950385975e95ca0 | nicopenaredondo/python-adventure | /if_else_with_looping.py | 381 | 3.9375 | 4 | number = 23
flag = True
while flag:
guess = int(raw_input('Enter an Integer : '))
if guess == number:
print 'Your guess is right'
flag = False
elif guess < number:
print 'A lil bit higher'
else:
print 'wtf'
else:
... |
89e01ef76d51bad24795cdd994233725a8f8ea01 | mpettersson/PythonReview | /questions/list_and_recursion/has_two_sum.py | 3,546 | 3.84375 | 4 | """
HAS TWO SUM
Write a function that accepts a (unsorted) list l and an integer total t, then returns True if there exists two
elements in the list with the sum t, False otherwise.
Example:
Input = [11, 2, -2, 7, 4, 1], 6
Output = True
"""
import copy
# Questions you should ask the i... |
519bd77377c6c62dab12e447d530827c3375595a | sa-i/20200414py3interm | /type_hints.py | 561 | 3.703125 | 4 | #!/usr/bin/env python
import typing as T
Numeric = T.Union[int, float]
# T.Any T.Iterable T.List[type] T.Tuple[Type]
# def name(...) -> return_type:
def c2f(celsius: Numeric) -> float:
fahrenheit = ((9 * celsius) / 5) + 32
return fahrenheit
f = c2f(37.1)
print(f)
f = c2f(37)
print(f)
# type hinting vs... |
1f4b6f39aeeab66c37f1a6639452fcb92847bcd2 | ahddredlover/python_book | /codes/chapter-04/eg_4-04.py | 247 | 3.71875 | 4 | def copy(seq):
return [copy(o) if type(o) is list else o for o in seq]
if __name__ == "__main__":
lst = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10, 11]]]]]
lst_new = copy(lst)
lst_new[2][2][2][2][2] = 0
print(lst)
print(lst_new)
|
f87dcb6aafd839dbd8076475d3e3b28e66c7ae1a | HermanLin/CSUY1134 | /homework/hw06/hl3213_hw6_q1.py | 739 | 3.828125 | 4 | from DoublyLinkedList import DoublyLinkedList
class LinkedQueue:
def __init__(self):
self.data = DoublyLinkedList()
self.num_elem = 0
def __len__(self):
return self.num_elem
def is_empty(self):
return self.num_elem == 0
def enqueue(self, e):
self.data.add... |
5a36885f6d7dbea39a376e7e212b65539dd9bbc2 | Piotrek1697/Python2020 | /Sprawdzian1/Piotr_Janus_236677_S1_zad1.py | 1,244 | 4.03125 | 4 | import sys
def main(args):
input_nums = args
if len(input_nums) == 1: # When input is like: 3,4,5
input_nums = args[0].split(",")
if len(input_nums) != 3:
sys.exit("Input must have 3 elements. Input numbers must be like: a0 q n, or a0,q,n\n"
"First number (a0) - First num... |
90e22effbef119cca902eee27011ed8825ac2ea6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2951/60768/316571.py | 1,851 | 3.546875 | 4 | str1 = input()
str2 = input()
int2 = int(str2, 3)
tempInt2 = 0
ZERO_ONE = [0, 1]
ONE_TWO = [1, 2]
ZERO_TWO = [0, 2]
for i in range(0, len(str2)):
tempStr2 = str2
if str2[i] == '0':
for j in ONE_TWO:
tempStr2 = str2[0:i] + str(j) + str2[i + 1:len(str2)]
tempInt2 = int(tempStr2, 3)... |
6f65cf51f534a095ce834ef1925ff219090121c9 | r3dback/cisco-bb | /bblevel1_hands_on_exercise.py | 1,323 | 4.5 | 4 | # Python 3.6.5
# By: Francisco Rojo, 30/7/2018
# Cisco BB Level 1 _assignment
#
# How to run on Python3
# > python3 hands_on_exercise.py
import math
import random
# Expected Output
#pi is a with a value of 3.141592653589793
#i is greater than 50
#The fruit is orange
#12 x 96 = 1152
#48 x 17 = 816
#196523 x 87323 =... |
15b3b3e68c0e13ccabfa5cc43bc4ee862061b023 | MitCandy/PythonNotes | /Basics/strings.py | 807 | 4.15625 | 4 | # SimpleString
print("Get Good")
# Backslash for using quotation inside quotation
print("Get\"Good")
# Can be assigned on variable and execute
name = "Roy"
print(name)
# Concenateable w/without variable
name1 = "Burnett"
print("Your name is " + name1)
# String w function
word = "klen"
print(word.upper()) # Capitali... |
d1ef410e33f6a459899f37748e2bde3216aa0178 | Guillaume-Maille/Python-Challenges | /Booksort/Task 4.py | 446 | 3.515625 | 4 | def add_info():
column = input("Add new info:")
with open('Books.txt') as c:
c1 = c.readlines()
with open('NewBooks.txt', "w+") as f:
lines = f.read().splitlines()
for line in f:
if line == lines[1]:
f.write(c1[1] + column)
else:
... |
3eeec65fe9160c25e1e0c1a41a200a4af2ec8ab8 | aifulislam/Python_Demo_Forth_Part | /lesson6.py | 2,258 | 3.96875 | 4 | # 24/12/2020-------
# Tamim Shahriar Subeen-------
# String()----------------
s = "hello"
print(len(s))
print(s)
l = len(s)
print(l)
s = ''
print(s)
print(len(s))
s = "Dimik's"
print(s)
s = "Dimik\s"
print(s)
country = "Bangladesh"
print(country[4])
for c in country:
print(c)
c = ... |
d9332223290be1827ddf975b480a460289c58671 | col-a-guo/tftRolldownCost | /tftGoldCost.py | 3,048 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 06:59:58 2020
@author: r2d2go
"""
import random
import math
import matplotlib.pyplot as plt
def run(winrate, startstreak, startgold):
gold = startgold
lostGold = 0
winstreak = startstreak
for i in range (10):
winvar = random.u... |
32a2f0ca4e0cad5fdf551fea957321884b93192d | Ace-0/MovieAnalysis | /data/cleanup_metadata.py | 1,847 | 3.84375 | 4 | import pandas as pd
def isValidRow(row):
if ((row['adult'] != 'TRUE' and row['adult'] != 'FALSE')
or (not str(row['budget']).isdigit())
or (not str(row['id']).isdigit())
or (not isFloat(str(row['popularity'])))
or (not str(row['revenue']).isdigit())
or ... |
090bec83f4f7e7b78c520e5fe201141e329e3a3a | karolinaWu/leetcode-lintcode | /leetcode/Python3/28.ImplementstrStr().py | 293 | 3.578125 | 4 | #https://leetcode.com/problems/implement-strstr/
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
l1 = len(haystack)
l2 = len(needle)
for i in range(l1-l2+1):
if haystack[i:i+l2] == needle:
return i
return -1
|
117cd8ab9eb27b8421af8fe1c42d008ce2128835 | BlutigerHammer/calculating-area-from-given-data | /areaModule.py | 1,053 | 4 | 4 | # -*- coding: utf-8-*-
'''
Functions for calculating the training ground area:
- use the Gauss formula
- the input is a list of lists like: [[x, y], [x, y], ...]
- x and y - are coordinates of the polygon corners in 2D
- there are 2 functions:
- area () - based on python language lists
- araenp () - uses numpy array... |
f987cf49aed143934468f83a559a96548dcd46eb | borjas93/mi_primer_programa | /contar_palabras.py | 1,097 | 4.1875 | 4 | """
Este ejercicio trata sobre contar las palabras que aparecen en una cadena.
Para este cometido, vamos a definir una funcion muy basica que detecte las palabras de cualquier texto.
"""
def detectar_palabras(cadena):
lista_palabras = []
palabra = ''
for item in cadena:
if item != ' ' and item != ... |
a961c2a190ce46bfd04b2bece113b8a3acdad180 | concpetosfundamentalesprogramacionaa19/ejercicios-clases5-020519-SantiagoDGarcia | /miproyecto/run4.py | 1,374 | 3.90625 | 4 | """"
file: run3.py
autor: @SantiagoDGarcia
Deseamos obtener el costo de una carrera universitaria.
El valor Promedio de cada ciclo es de 1200$
El valor Promedio del seguro educativo es 100$ c/u ciclo,
si la edad es menor igual a 20, caso contrariario sera de 150$
Si el estudiante tiene una modalidad a dista... |
1b948b6559b736b5aaf9e06217bd65d0ac2b70a8 | saharma/PythonExercises | /Exercises/mathProgram.py | 499 | 4.1875 | 4 | num1 = float(input('Enter the first number: '))
num2 = float(input('Enter the second number: '))
print('{} plus {} equals {}'.format(num1, num2, num1 + num2))
print('{} minus {} equals {}'.format(num1, num2, num1 - num2))
print('{} multiplied by {} equals {}'.format(num1, num2, num1 * num2))
print('{} divided by {} eq... |
5d253ceaa59174917050cb5845acb99ba444c199 | jacqueline-homan/python2.7_tutorials | /py2.7tutorial.py | 1,002 | 4.28125 | 4 | # This Python tutorial uses Python 2.7
#printing out the Fibonacci sequence vertically
a, b = 0, 1
while b < 10:
print b
a, b = b, a+b
# printing out the Fibonacci sequence horizontally
a, b = 0, 1
while b < 10:
print b,
a, b = b, a+b
#printing out from user input, dialogue w/ user
myName = raw_input("What is y... |
b529e8cf1d25bd63d76af4c00113f4ae5411c4dc | kimdaebeom/Machine_Learning_spartacodingclub | /linear_regression/kaggle_linear_regression_ex2.py | 1,079 | 3.5 | 4 | #여러 X값을 이용하여 매출 예측하기
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam, SGD
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
df =... |
a5406120605cdc850d0d97d2ac3ccb4202dd14c0 | zHigor33/ListasDeExerciciosPython202 | /Estrutura de Decisão/L2E28.py | 1,418 | 3.921875 | 4 | print(" Até 5 Kg Acima de 5 Kg")
print("File Duplo R$ 4,90 por Kg R$ 5,80 por Kg")
print("Alcatra R$ 5,90 por Kg R$ 6,80 por Kg")
print("Picanha R$ 6,90 por Kg R$ 7,80 por Kg")
typeOfMeat = str(input("Informe o tipo de carne (file/alcatra/picanha): "))
quantityInKilos... |
aae24dd1e494d3f828a4c8ece342bea95e02978e | samdejong86/AboutMe | /SamFacts.py | 1,864 | 3.765625 | 4 | #import some libraries
import sys
from random import randint
#open the file containing my qualifications
with open("Sam_deJong.dat") as f:
Facts = f.readlines()
#clear whitespace and remove empty entries
Facts = [x.strip() for x in Facts]
Facts = [s for s in Facts if len(s) != 0]
print "I am the highly qu... |
7a1d69d6a7b8d9b665ff82ee962905188513f9fd | nishantkakar/ctci-6th-ed | /Chapter 8/8.4 Power Set.py | 246 | 3.78125 | 4 | def power_set(arr):
"""
:type arr: list
:rtype: list
"""
subsets = [[]]
for i in arr:
for j in range(len(subsets)):
subsets.append(subsets[j] + [i])
return subsets
x = [1, 2, 3]
print power_set(x)
|
ddabf0201c2e282a1ed422d4de95c8303fc00ad2 | extragornax/AdventOfCode | /2020/Day 04/code.py | 3,248 | 3.5 | 4 | import re
def checkHex(s):
for ch in s:
if ((ch < '0' or ch > '9') and
(ch < 'a' or ch > 'f')):
return False
return True
def two():
file = open("input.txt")
data = []
tmpVal = {}
for i in file:
i = i.rstrip()
if len(i) == 0:
... |
f0b239c9cf52128330b3a7e5a0fc1f22754b7e61 | dtingg/Fall2018-PY210A | /students/student_framllat/session04/dict_set_solution_rft.py | 3,796 | 4.65625 | 5 | #!/usr/bin/env python
"""
dict/set lab solutions: MODIFIED Chris' version.
"""
# Create a dictionary containing "name", "city", and "cake" for
# "Santa" from "NorthPole" who likes "Lemon".
gen_d = {"name": "Santa",
"city": "NorthPole",
"cake": "Lemon"}
# Display the dictionary.
print("\nGeneric printing... |
ab0daa62bc5438d654933e181091bce661304b63 | nhichan/hachaubaonhi-fundamental-c4e16 | /session2/bài học/conditional_statement.py | 252 | 4.0625 | 4 | yob = int(input('what is your birthyear: '))
age =2018-yob
print('your age: ',age)
if age<10:
print('baby')
elif age<=18:
print('teenager')
elif age==24:
print('adult')
else: #else k bao h co dieu kien
print('not baby')
print ('bye')
|
00588c4434b526f928bbbfa4b7df4523d09be184 | CorbinMayes/Artificial_Intelligence_19W | /Mazeworld/astar_search.py | 3,624 | 3.578125 | 4 | #Corbin Mayes 1/17/19
#Talked with Hunter Gallant
from SearchSolution import SearchSolution
from heapq import heappush, heappop
class AstarNode:
# each search node except the root has a parent node
# and all search nodes wrap a state object
def __init__(self, state, heuristic, parent=None, transition_cos... |
8b6fe886b0f4c468548d64d2cd0a83177908f1fb | GafasAV/SomeTestTasks | /fizzBuzz.py | 314 | 4 | 4 | def fizzBuzz(n):
if n % 3 == 0 and n % 5 == 0:
return "FizzBuzz"
elif n % 3 == 0:
return "Fizz"
elif n % 5 == 0:
return "Buzz"
else:
return str(n)
if __name__ == "__main__":
count = int(input("Input numbers count :"))
result = ""
print(result.join(fizzBuzz(n) for n in range(1, count+1)))
|
9b91921e15327d7620c920f81f4e41f845138fcb | atasoya/MultipleChoiceExamMaker | /main.py | 754 | 3.625 | 4 | Questions = []
Options = []
abc = "abcdefgh"
QuestionNumber = input("Enter The Question Number : ")
OptionNumber = input("Enter The Option Number : ")
for i in range(int(QuestionNumber)) :
Question = input("Enter the question : ")
Questions.append(Question)
for x in range(int(OptionNumber)... |
4d508ee34b197f6acfa24ae8a56d1debd17ab321 | Pitt-Pauly/ML-Hadoop-practice | /Unixversion.py | 2,254 | 3.5625 | 4 | ##
# Pierre Pauly
# s0836497
# level 10
#
# Further Documentation in ReadMe.txt
##
import re
class SimpleCaps:
""" Simple word capitalizing script using Naive Bayes. (Unix version) """
##
# init
#
# params: filename, path to training set (txt file).
#
##... |
ef8f091c8ca2b9037789604defc264cb4d792199 | padfoot18/AISearchStrategies | /uninformed_search.py | 1,605 | 3.515625 | 4 | """
dfs ids for map exploration
"""
import ids_search
import dfs_search
import generate_state_space_tree
class Node:
def __init__(self, city_name, parent, id, level):
self.city_name = city_name
self.level = level
self.parent = parent
self.child = []
self.id = id
# i... |
f52ce286f5b780344c17d6b6a7c31aa8f9fcdc72 | geofreym21/Analyze_game_Pandas_Lib_Jupyter | /Heroes_of_Pymoli_Assign4.py | 4,569 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Depedencies and Setup
import pandas as pd
import numpy as np
# In[2]:
# File to Load
file_to_load = "..\Assignment\purchase_data.csv"
# Read Purchasing File and store into Pandas data frame
purchase_data = pd.read_csv(file_to_load)
purchase_data.head()
# In[3]:
... |
a9a03c032d2d69f2b444a683c75965955bb7cd37 | hathu0610/nguyenhathu-fundamental-c4e13 | /Session02/HW/Ex3c1.py | 105 | 3.53125 | 4 | for j in range(1,10):
for i in range(1, 10):
k = j*i
print(k, end="\t")
print()
|
18cd75fabeb057eaabe94cfc47505f05cb39d76f | nyp-sit/python | /practical6/RetailPrice.py | 267 | 4.15625 | 4 |
wholesaleCost = float(input("Enter the wholesale cost of product: $"))
while wholesaleCost > 0:
retailPrice = wholesaleCost * 1.25
print("The retail price is $%.2f" % (retailPrice))
wholesaleCost = float(input("Enter the wholesale cost of product: $"))
|
56d9788891128abfa6bc54647e14e0823dc59da9 | JosepAnSabate/Python_geology | /exercisis_a.py | 686 | 3.8125 | 4 | #ex1
b = ["h","o","l","a"]
c = []
for bs in b:
c.append(bs.upper())
print(c)
#ex2
e=9
f = 1/2*(2/(e-3))+e**3
g = 1/2*(2/e-3)+e**3
print(f)
print(g)
#ex 3
diccionari={'Monday':2,'Tuessay':5,
'Wednesday':8,'Thursday':0,
'Friday': 4,'Saturday':0,
'Sunday':0}
print(dir({}... |
26ae68a0affd0b7a7ae1a8327d55c7ae1b8b5d2e | linhnvfpt/homework | /python/practice_python/exer15.py | 425 | 4.40625 | 4 | # Write a program (using functions!) that asks the user for a long string
# containing multiple words. Print back to the user the same string,
# except with the words in backwards order.
def reverseWordOrder(helptext = "Input a string: "):
string = input(helptext)
result = string.split(" ")
result.r... |
22386ecc2d932d409217d70bcf8fabff92089c65 | Erick-Paguay/perick885 | /grupotech.py | 942 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 16 19:27:04 2020
@author: Erick Paguay
"""
if __name__ == '__main__':
inicial = int()
final = int()
impresiones = int()
blanconegro = str()
costoblanconegro = float()
costocolor = float()
costoimpresion = float()
costoblanconegro = 0.06
costocolo... |
860a246796d2f09b7998653bb7e23ada4535de1e | Mercrist/CodeWars-Submissions | /4 kyu/frequentWords.py | 783 | 4.125 | 4 | from collections import Counter #supports convenient and rapid tallies
import re
def top_3_words(text):
counts = Counter(re.findall("'?[a-z][a-z']*", text.lower())) #an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values
return [w for w, words in co... |
de33d7c3058259442d127f5ff8efaca700c97a88 | amanji/quartet_phylogeny_algorithm | /phylogeny.py | 885 | 3.6875 | 4 | class Phylogeny:
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
... |
05cd00d13d8ad80ff5e4b16f6da7899b83449a3e | junyang10734/leetcode-python | /1736.py | 635 | 3.640625 | 4 | # 1736. Latest Time by Replacing Hidden Digits
# String
class Solution:
def maximumTime(self, time: str) -> str:
res = ''
for i,t in enumerate(time):
if t == '?':
if i == 0:
res += '2'
elif i == 1:
res += '3' if res... |
d1e5fa48f12e02be231ecc71bbbbd199935de902 | ramamca90/cyient_assessment | /ps_model_test.py | 4,044 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 28 09:02:51 2021
@author: gonzalez
"""
"""
Exercise:
Create a class to contol a power supply (PS) and provide a main
function that shows the usage
The PS has 4 outputs each of then can be set to a given level (range
... |
93a0ddcc04d1c582162d00f46d47ff2285bc4472 | mrgrier/AnagramExercise | /anagram.py | 461 | 3.609375 | 4 | import math
import os
import random
import re
import sys
from collections import Counter
def substringAnagrams(s):
count = 0
substrings = []
l = len(s)
i = 0
while i < l:
j = i + 1
while j <= len(s):
sub = s[i:j]
for x in substrings:
if(areAnagrams(sub, x)):
count = coun... |
995c725152123ff6cc5144c50c58cdd8fbc6ed96 | akmalmuhammed/Skools_Kool | /Chapter_08/exercise1.py | 467 | 4 | 4 | __author__ = 'matt'
"""
Write a function that takes a string as an argument and displays the letters backward, one per line.
"""
def backward(z):
"""
Take a string and display letters backwards
"""
index = 1
while index < len(z):
letter = z[-index]
print letter
index = inde... |
be2351ded3ab698e678235cbedae0a7a3ddbb2c2 | JavierPerezGithub/Python | /src/interfazGrafica/Ventana7.py | 481 | 3.640625 | 4 | '''
Created on 14/2/2018
@author: 5725
'''
from Tkinter import *
ventana1 = Tk()
ventana1.title("Posicionamiento")
etiqueta1 = Label(ventana1, text="Posicionamiento diferente 1").place(x=10, y=10)
etiqueta2 = Label(ventana1, text="Posicionamiento diferente 2").place(x=200, y=10)
etiqueta3 = Label(ventana1,... |
44747a9628824589ab9794b80abb904684b0267c | sujitkc/evaluate | /demo/submissions/rn010/Q2.py | 544 | 3.890625 | 4 |
def increment(x):
return x+1
def decrement(x):
return x-1
def add(x, y):
for i in range(x):
y = increment(y)
return y
def subtract(x, y):
for i in range(x):
y = decrement(y)
return y
def multiply(x, y):
copy = 0
for i in range(x):
copy = add(copy, y)
retu... |
46299e100af88c059c8023f65c7821071c5515fe | 924235317/leetcode | /73_set_matrix_zeroes.py | 905 | 3.734375 | 4 | def setZeroes(matrix: list) -> None:
row, col = len(matrix), len(matrix[0])
row_flag = False
col_flag = False
for i in range(row):
if matrix[i][0] == 0:
row_flag = True
break
for i in range(col):
if matrix[0][i] == 0:
col_flag = True
... |
f89535ab720b85c106695d238bd1d881b80d9586 | AntoineCanda/A2DI | /tp1-canda/exo1.py | 6,245 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 15:51:27 2017
@author: canda
"""
import numpy as np
import matplotlib.pyplot as mpl
import random
import time
from sklearn import datasets
# Question 1 : chargement des donnees
data = datasets.load_iris()
# Question 2 : Obtenir informations sur le dataset : 150 ex... |
b08f42f9e9ef5866d39d9b45a32e2a8102dd1768 | leizhi90/python | /base_python/day19_thread/work.py | 2,411 | 3.96875 | 4 | # -*- coding:utf-8 -*-
# @Author : LZ
# @Time : 2018/4/13 18:38
import threading
# 当创建一个线程时,该线程是前台线程还是后台线程?
#strat启动后变成前台程序,执行完毕销毁后变成后天程序
# 编写两个线程,对同一个全局变量增加若干次(次数多一点),会出现什么情况。
num = 0
def f_mult():
global num
for i in range(1000000):
num += 1
# t1 = threading.Thread(target=f_mult)
# t2 = threadin... |
cfd2f2cd9e4f750b3393d8d26e3ca763f8ecc1cb | ceeoinnovations/SPIKE_AI_Puppy | /Lesson_4/Lesson4Main-ReLearn_Example.py | 1,762 | 3.640625 | 4 | # Last modified: July 8th '21
# Main Code for Lesson 4: AI Fetch Examples
#(Reinforcement Learning with Linear Model Example Code)
import hub, utime
sensor = hub.port.A.device ### <----- REPLACE WITH YOUR SPIKE'S HUB PORT
number_of_examples = 3
# Setup reinforcement learning class, takes 2 ports for motor as para... |
e5f4d5e4800ecd10547974cdd330043f67b1c218 | prtk07/Programming | /Python/akumar-99_checkparallellines.py | 418 | 4.21875 | 4 | ############################
### FACTORS OF A NUMBER ###
############################
print("Line is ax+by=c")
a1 = int(input("Enter a1: "))
b1 = int(input("Enter b1: "))
c1 = int(input("Enter c1: "))
a2 = int(input("Enter a2: "))
b2 = int(input("Enter b2: "))
c2 = int(input("Enter c2: "))
if(a1/a1 == b1/b2):
pri... |
b18bc6f214f45a43de30dacf715987cdf8782c73 | luogao/python-learning | /py_slice.py | 1,071 | 3.640625 | 4 | #### Slice 切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[0:3]) # ['Michael', 'Sarah', 'Tracy']
newL = L[1:2]
print(newL) # ['Sarah']
reverseL = L[-2:]
print(reverseL) # ['Bob', 'Jack']
L1 = list(range(100))
print(L1[:10]) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(len(L1[-10:])) # 10
print()
print(L1[::... |
1ceee07f6f1818b79158ee7a05644a59755966b9 | dakbill/Lab_Python_05 | /Lab05.py | 2,319 | 3.90625 | 4 | def do(thing):
return str(thing) + str(1)
do(5)
#do(5) will have a string value of 51
##########################################################
def do(one, two=5):
return one+two
do(5)
#do(5) will have an integer value of 10
def do(a,b):
a=5
b=5
return a*b
inp = 8
do(inp,5)
print inp
#do(inp,5) wi... |
fa58ea34e18454038d020f9e97680a2671a89b56 | FreedomPeace/python | /basicKnowledge/05ForWhile.py | 581 | 3.8125 | 4 | names = ['lily', 'lucy', 'jake']
for name in names:
print(name)
# 求1+2+...+10的和 --range(10)
total = 0
for x in range(11):
total += x
# print(total)
print('1-10的和total为:' + str(total))
nums = [1, 3, 5]
totals = sum(nums)
print(totals)
totals = sum(list(range(101)))
print("100以内的和为:" + str(totals))
... |
8e86aa7b66427627a30fc69deac7ec07b1cee435 | VineetPrasadVerma/GeeksForGeeks | /SudoPlacementCourse/DistinctPalindromeSubstring.py | 404 | 3.5625 | 4 | test_cases = int(input())
for _ in range(test_cases):
arr_list = input()
size = len(arr_list)
palindrome_list = []
for i in range(size):
for j in range(i+1, size+1):
temp = arr_list[i:j]
reverse_temp = temp[::-1]
if temp == reverse_temp:
palind... |
1e062b08bf8b22908c4882d1a36debed7cd2e2d5 | aigerimzh/BFDjango | /Week1/CodingBat/count_evens .py | 135 | 3.59375 | 4 | def count_evens(nums):
cnt = 0
for x in range (len(nums)):
if nums[x]%2 == 0:
cnt = cnt+ 1
return cnt
|
8da65219f2253b8fef4879e47ca3c81db8d3e64a | avsuv/python_level_1 | /5/5.py | 277 | 3.546875 | 4 | with open('5.txt', 'w') as file:
nums = input('Введите числа через пробел: ')
file.write(nums)
numbers = []
with open('5.txt', 'r') as file:
numbers = file.read().strip().split()
summ = 0
for num in numbers:
summ += int(num)
print(summ) |
161517b7795f2291deae1d75e09b3ad3b0383a28 | 1sma3l/Practice_Python | /conversor.py | 758 | 3.75 | 4 | def conversor(tipo_peso, valor_dollar):
pesos = input("¿Cuantos pesos " + tipo_peso + " tienes?: ")
pesos = float(pesos)
dolares = pesos / valor_dollar
dolares = round(dolares, 2) #Redondeamos la cantidad a 2 decimales
dolares = str(dolares)
print("Tienes $" + dolares + " dolares")
menu = """... |
75cd40870a247b735d08bd29bdf3d9b08104f794 | cl3e8/tuple-meetup-web-scraping-workshop | /01_requests/02_requests_json_eg.py | 1,002 | 3.859375 | 4 | import requests
import pprint
""" Requests Library JSON Example:
Using the requests library, you can view contents in other formats as well.
One very popular data format for the web is JSON (JavaScript Object Notation).
With the Requests library, you can easily read in JSON data to a dictionary.
Pro tip! Many times... |
70fe9c848d3928509702fc35c16f31ddd6224b56 | chunxi-alpc/gcx_pacman | /search/search.py | 6,211 | 3.84375 | 4 | # coding=UTF-8
# search.py
"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented te... |
8d1928bd1266185c8a096f6000d631c1966ada98 | kazlik0310/python | /vsearch.py | 498 | 3.921875 | 4 | def search_for_vowels(phrase:str) -> set:
"""Возвращает булево значение в зависимости от присутствия любых гласных."""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search_for_letters(phrase:set, letters:str='aeiou') -> set:
"""Находит множество букв из 'letters', найденных в ... |
dd5694a39ecd17df831beea627b0af08a61e3c45 | figkim/TC2 | /leetcode/2020/easy/00020_valid_parentheses/valid_paren_WY.py | 635 | 3.5 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pars = {"(":")","[":"]","{":"}"}
stack = list()
for i,par in enumerate(s):
if par in pars.keys():
stack.append(par)
e... |
ad162c0963c0a3f13970dfebc690993de4998941 | charles161/python | /Factorial.py | 332 | 3.78125 | 4 | tc = input("Enter the number of test cases: ")
a=[]
for i in range(tc):
a.append(input("Enter the input of "+str(i+1)+ " test case: "))
def factorial( n ):
if n==0:
return 1
else:
return n*factorial(n-1)
for na in a:
if na<0:
print("Invalid")
else:
print(str(factorial... |
cc61fe596b967bf852083b37cc3c0521eccc672c | harsilspatel/toy-robot-simulator | /RobotSimulator.py | 2,661 | 4.03125 | 4 | from enum import Enum
class Direction(Enum):
"""Enum to representation robot direction."""
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class RobotSimulator:
def __init__(self, table_width=5, table_length=5):
assert table_width > 0, "Table width should be a positive integer"
assert table_length > 0, "Table lengt... |
d9d274f086dc030610709f4ea954694dde402ca0 | mikhail-rozov/GB_Python-main-course-1 | /Lesson 4/L4_task6.py | 1,880 | 4 | 4 | # Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание,
# что создаваемый цикл не должен быть бесконечным. Не... |
b4d70cbeb75cc6a23c9bd6be7d461be3fdb34398 | pri-nitta/firstProject | /CAP8/Funcoes.py | 900 | 4.125 | 4 | def perguntar():
return input("O que deseja realizar?\n" +
"1 - Inserir usuário\n" +
"2 - Pesquisar usuário\n" +
"3 - Excluir usuário\n" +
"4 - Listar usuário: ").upper()
# não precisa do retorno, pq é a memória
def inserir(dicionario):
dicio... |
2330266af33295d1b4cb7982871a7416de9aeb5a | alexandrepoulin/ProjectEulerInPython | /problems/problem 123.py | 350 | 3.515625 | 4 | print("Starting")
import useful
MAX = 10**6
primes = useful.primesTo(MAX)
answer = 0
for i in range(0,len(primes)):
if i%2 == 1:
continue
val = 2*(i+1)*primes[i]% primes[i]**2
if val > 10**10:
print(val)
print(primes[i])
answer = i+1
break
print(... |
e2ca225aa70ff3285d27cc80e348a0437adce91f | scottwat86/Automate_Boring_Stuff_ | /ch12_excel/PP21_Excel_to_text.py | 965 | 4.0625 | 4 | #! python3
# PP21_Excel_to_text.py
# Write a program that performs the tasks of the previous program in reverse order:
# The program should open a spreadsheet and write the cells of column A into one text file, the
# cells of column B into another text file, and so on.
# By Scott Watson
# Import modules
import sys
... |
dede04bdde1c57dfdbe02c70e174b51a35293763 | Kite-free/crop | /findfile.py | 652 | 3.859375 | 4 |
#输入要查找的文件名 查找当前文件夹下该文件的相对目录:
import os
path = os.path.abspath('.')
target_str = input('请输入要搜索的文件名关键字:')
for root, dirs, files in os.walk(path):
for file in files:
if target_str in file:
print(os.path.join(root.replace(os.getcwd(),'.'), file))
# print(os.path.join(root, file))
# os.walk
... |
c540ad3261997b1ab47a068c8fc60647560a3581 | hiepxanh/C4E4 | /MaiHuong/Session 02 - assignment 02.py | 777 | 4.09375 | 4 | from turtle import *
# Exercise 1
## Check variables type: type ()
a = 3
b = 3.05
c = "Hello"
print(type(a))
print(type(b))
print(type(c))
## 3 examples of invalid name
##3consoi = 13
##soi@ = "hello"
##max(i) = 21
# Exercise 2: calculates areas of the circle
r = 10 # r : radius
areas = r**2*3.14
print(" Areas = ",... |
76d04841a0467417cbccb1d504688cd5d01328be | patel-deepak506/Codechef | /NAV_DEEPAK P/NAVHW_049.py | 272 | 3.90625 | 4 | '''
NAVHW_049: Draw a flowchart to print the following sequence.
*
* *
* * *
* * * *
* * * * *
'''
n=int(input())
# a=1
# while a<=n:
# b=a
# while b<+n:
# print("*",end=" ")
# b+=1
# k=1
# while k
for i in range(1,n+1):
print(" "*(n-i),"*"*i) |
6af0a3f24064ee2a4e54242755746cc1217f3023 | tamyrds/Exercicios-Python | /Mundo_2_Python/estrutura_while/desafio_70.py | 680 | 3.953125 | 4 | maior = totH = totM = 0
print('=-' * 20)
print("CADASTRE UMA PESSOA")
print('=-' * 20)
while True:
idade = int(input("Idade:"))
sexo = str(input("Sexo: ")).upper()
if idade >= 18:
maior +=1
if sexo == 'M':
totH += 1
if idade < 20 and sexo == 'F':
tot... |
dbf7c9d3fad35cb132fa3bb9377f815cff5e323e | djlim98/Algorithm | /programmers/Stack&Queue/4.py | 598 | 3.59375 | 4 | #https://programmers.co.kr/learn/courses/30/lessons/42587
def solution(priorities, location):
answer = 0
count=0
while priorities:
candinate=priorities.pop(0)
location-=1
flag=True
for i in priorities:
if candinate<i:
flag=False
bre... |
d2932c43a90a05dbf2dbc75595428eba8c8eae60 | Piyush-Ranjan-Mishra/python | /Machine Learning & AI/knn.py | 2,159 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
path = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# assign column names to the dataset as follows −
headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
dataset = pd.read_csv(pat... |
1e38e9f2ac4ccce19efe1ffb1b8f1bb36b7245ad | nandadao/Python_note | /note/download_note/first_month/day09/exercise02.py | 241 | 3.71875 | 4 | """
定义函数,判断二维数字列表中是否存在某个数字
输入:二维列表、11
输出:True/False
"""
map = [
[2, 0, 2, 0],
[2, 4, 0, 2],
[0, 0, 2, 0],
[2, 4, 4, 2],
]
print(2 in map)# False X
|
97812f10c889bcd5c750604abaf26038754d514d | ggrecco/python | /basico/zumbis/velocidadeExcedida.py | 235 | 3.890625 | 4 | velocidade = int(input("Velocidade do carro: "))
if velocidade > 110:
multa = (velocidade - 110) * 5
print("Você foi mulado em R$ {}".format(multa))
else:
print("Parabéns você está dentro do limite de velocidade!")
|
81a676e978976b43ced27e7a5b839445adf0c18b | dado3212/ProjectEuler | /euler_22.py | 820 | 3.609375 | 4 | # Problem 22
# Answer: 871198282
'''
Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when th... |
f260c08d786305c4791e7b203443827a46f3bb8e | sourabbanka22/Competitive-Programming-Foundation | /Dynamic Programming/knapsackProblem.py | 839 | 3.515625 | 4 | def knapsackProblem(items, capacity):
memo = [[0 for _ in range(capacity+1)] for _ in range(len(items)+1)]
for row in range(1, len(items)+1):
for col in range(capacity+1):
currentWeight = items[row-1][1]
currentValue = items[row-1][0]
if currentWeight<=col:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.