blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d4bff52cb873af65dd4e38a6bc2c2e4a3fbf7d51 | JennyIkaMaharani/Python-Projects-Protek | /Praktikum09/operasiFile4.py | 687 | 3.640625 | 4 | #membuat function untuk mengacak string
#mengimport random
import random
def shuffleString(x,n):
#mengubah string ke list
kata = list(x)
#membuat list kosong
listHasil = []
listHasil1 = []
while True:
#mengacak huruf
random.shuffle(kata)
#menggabung huruf menjadi kata
... |
53c3dc6a595e9886799a66dd9ea8428fb423c264 | fruitynoodles/Python_Examples | /dara2019/primes.py | 1,093 | 4.21875 | 4 | # Write a program to calculate the first N prime numbers-
# numbers which have only themselves and one as factors.
# Write a function to test if a number is a prime or not.
# If it is a prime, return True. If not, return False
# Use the sieve of Erastosthenes (or more a sophisticated method)
# check remainder of num d... |
a47a73ee4e53bc2b81b94e918ce75bbb7e0a9095 | nurack/eric-pcc-solutions | /PCC8_8.py | 513 | 3.9375 | 4 | def make_album(artist_name, title_name):
album = {'artist': artist_name, 'title': title_name}
return album
while True:
print("\nEnter artist name and title of the album:")
print("\nEnter q to quit")
artist_n = input("Enter artist name:")
if artist_n == 'q':
break
album... |
5482e1aa37f45f5cafafb3379cbd5374e6bdf618 | lakshmi-sahithi/Coffee-Machine | /Coffee_Machine.py | 3,717 | 3.890625 | 4 | class CoffeeMachine:
def __init__(self, water=400, milk=540, coffee_beans=120, disposable_cups=9, money=550):
self.water = water
self.milk = milk
self.coffee_beans = coffee_beans
self.disposable_cups = disposable_cups
self.money = money
def update_stock... |
6603f3412ef6864069751467fa4c420194a23fd2 | ronakice/Connect4EasyAI | /Connect-4-Easy.py | 4,884 | 3.75 | 4 | import sys
import random
from time import sleep
def checkcolumn(c):
#checkcolumn(c) checks if the top cth column has atleast one empty spot
if board[0][c-1] == '.':
return True
return False
def checkwin(ab):
#checkwin(ab) prints which player wins if any and returns True if a player has won o... |
76aa4844fcd92801199bb335bd897fc883dadffa | mofty8/BioInformartics | /K-mers.py | 329 | 3.515625 | 4 | import string as st
text = "CGCCTAAATAGCCTCGCGGAGCCTTATGTCATACTCGTCCT"
k = 3
count = 0
freq = {}
for i in range (len(text) - k + 1):
count = 0
str = text[i:i+k]
for j in range(len(text) - k + 1):
if (text [j : j+k] == str):
count = count + 1
freq[str]=count
print (freq)
print (ma... |
bef7290dbcaa194ede9ff36d90958486d0c1f798 | Venkataraman-Nagarajan/DAA- | /EX3/maxsum_nlogn.py | 947 | 3.53125 | 4 | def MaxCrossingSum(a,l,r,m):
Sum=0
left_sum=0
for i in range(m,l-1,-1):
Sum+=a[i]
if(left_sum < Sum):
left_sum=Sum
Sum=0
right_sum=0
for i in range(m+1,r+1):
Sum+=a[i]
if(right_sum < Sum):
right_sum=Sum
return left_sum+right_sum
def MaxSumSide(a,l,r):
if(l==r):
return a[l]
m=(l+r)//2
r... |
3affdcbb8f295871bae61a29d5729e0481469230 | gabrielmuller/calcnum | /newton.py | 284 | 3.578125 | 4 |
import math
def f(x):
return math.pow(math.e, x) - x - 1
def df(x):
return math.pow(math.e, x) - 1
a = 0
b = 1
xm = 0.5
c = 0
while(abs(f(xm)) > 0.000001):
c += 1
xm = xm - (f(xm) / df(xm))
print(xm)
print("f(" + str(xm) + ") = " + str(f(xm)))
print(str(c) + " iters")
|
376654f66b22240c766a9c957a7e90e4d7d5b3ab | scottsilverlabs/raspberrystem | /rstem/projects/breakout/breakout_3.py | 5,522 | 3.6875 | 4 | #In this project the user adds the Ball class, which handles
#most of the game physics, and adds the win and lose functions.
#Imports
from rstem import led_matrix
from rstem import accel
import sys
import time
#Initialize hardware
led_matrix.init_grid(2, 2)
accel.init(1)
#Initialize game data
bricks = []
score = 0
s... |
3936082d69cab8acb21edc78bf5035a5b3d1886e | FerhatYilmaz1986/calculator | /Statistics/Mean.py | 314 | 4 | 4 | def mean(a, b, c, length):
try:
a = int(a)
b = int(b)
c = int(c)
length = int(length)
result = (a + b + c) / length
return result
except ZeroDivisionError:
print("Error: Invalid input")
except ValueError:
print ("Error: Please enter a number")
|
e9ad3dcd783eafb3ae38a5a5b4066b2e67a598e2 | wyy18813148814/wyymultprocessstudy | /第五章节/多线程/同步/线程之间共享数据2.py | 618 | 3.828125 | 4 | #coding:utf-8
#主线程中的全局变量,作为所有子线程的共享数据
from threading import Thread
import time,os
#定义一个全局变量
g_num=0
def run1():
global g_num
time.sleep(1)
for i in range(10):
g_num+=1
print('线程1,执行之后的结果为:%d'%g_num)
def run2():
global g_num
print('线程2,执行之后的结果为:%d'%g_num)
if __name__ == '__main__':
... |
3c5590cac624c3e42dc2957ee92f88d826775bb9 | sanathkuppa/ProjectEuler | /Problem_34.py | 505 | 3.53125 | 4 | ## 7*(fact(9)) is 2540160. So, if the number has 8 digits,
## the sum cant ever be 8 digits
def Factorial(n):
if n == 0:
return(1)
if n == 1:
return(1)
return(n*Factorial(n-1))
Facts = []
for i in range(20):
Facts.append(Factorial(i))
Upper = 2540160
Ans = 0
for i in range(1,Uppe... |
59df9055bca9b4bf80497f697d43da95af4258d4 | Hvbyte/cursoemvideo-PYTHON | /Exercicios/ex015_Alugel_de_carros.py | 179 | 3.578125 | 4 | dias = int(input('Quantidade de dias com o veículo:'))
KM = float(input('Quantos Km rodados:'))
preço = dias * 60 + KM * 0.15
print('O valor do alugel é: R${}'.format(preço))
|
7d5a9563c564232b1895ab877aacf2bf3c470a86 | karalienes/Python | /For_2.py | 254 | 3.515625 | 4 | #Fig. 3.23:fig03_23.
#calculating compound interest(bırlesık faız hesaplama)
principal=20000
rate=.05
print"Year %21s" % "Amount on deposit"
for year in range(1,61):
amount =principal *( 1.0 + rate)** year
print"%4d%21.2f" % (year , amount)
|
2c8bbac71b1d442d7c71ddfef8f167d778d91d4a | pranavmswamy/leetcode | /mathworks/verticalOrderTraversal.py | 767 | 4.0625 | 4 | def verticalOrderTraversal(root):
# keep track of dist wrt 0 for root node.
# if you go left, do level-1
# if you go right, do level+1
# collect all nodes of the same level in the dict
# print them.
# keep track of min and max level so that it helps you to print later.
vertical = dict()
max_left = 0
max_right... |
465dfa9065719a5e152c4f6cd1524ac82c4448e9 | reddycloudengineer/ctci | /amazonPractice/medium.py | 2,041 | 3.6875 | 4 | class TreeNode(object):
def __init__(self,data,left=None,right=None):
self.data=data
self.left=left
self.right=right
def makeTreeNodes(l):
if not l:
return None
mid=int(len(l)/2)
head=TreeNode(l[mid])
head.left=makeTreeNodes(l[0:mid])
head.right=makeTreeNodes(l[... |
e3e472eac28a7b1e1d3022150ad367d376692e08 | 02021997/Competitive-programming-in-Python | /Mathematics/Number-theory/Euclidean-algorithms.py | 800 | 3.9375 | 4 | '''
Euclidean algorithms.
'''
#########################################################################
def egcd(a, b):
''' Extended Euclidian algorithm. '''
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
# x * a + y * b = g
return (g, x - (b // a) * y, y)
... |
ec02954f7547d94889bd4c5117aa48680446b908 | gear/learn | /udacity_softwaredev/poker.py | 2,832 | 3.84375 | 4 | def poker(hands):
"""
Return a list of winning hands.
"""
return allmax(hands, key=hand_rank)
def allmax(iterable, key=None):
"""
Return a list of all items equal to
the max of the iterable.
"""
key = key or (lambda x: x)
max_instance = max(iterable, key=key)
return [i for i... |
6d40ab282ca832fc8a064c879cc1502b87435a63 | caiosuzuki/exercicios-python | /ex058.py | 422 | 3.90625 | 4 | from random import randint
n_palpites = 1
num_escolhido_pelo_computador = randint(0, 11)
num_jogador = int(input('Tente um número de 1 a 10: '))
while num_jogador != num_escolhido_pelo_computador:
num_jogador = int(input('Tente adivinhar de novo: '))
n_palpites += 1
print('Parabéns, vc adivinhou depois de {} ... |
befaad8163781971d24481be96206a915b76391c | isears/SpamFilter | /spamAgent.py | 7,503 | 3.53125 | 4 | """
The spam classification agent:
Build a naive bayes model of messages using invididual words as features and spam/ham as classes.
To properly use the spam agent, call the functions in the following order:
1. __init__(spam_training_files, ham_training_files, k, m)
2. computeFeatures()
3. train()
4. c... |
5fe63eebfe496ba748c8df4eac1a73c29a332ac2 | dmitarint/algo_and_structures_python | /Lesson_3/1.py | 427 | 3.5 | 4 | # 1. В диапазоне натуральных чисел от 2 до 99 определить,
# сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
# a=[]
a=[0 for _ in range(10)]
for i in range(2, 10):
m=0
for j in range(2,100):
if j%i==0:
m+=1
a[i]=m
for _ in range (2,10):
print(f'На {_} делится {a[_]} чис... |
edae462b5f7ab851d11f72731d8608046529ef1b | rohit20001221/leetcode | /stacks_que/bfs_template.py | 330 | 3.65625 | 4 | from collections import deque
def BFS(root, goal):
Q = deque([root])
visited = [root]
while !(Q.empty()):
v = Q.popleft()
if v is goal:
return v
for v_ in v.neighbours():
if v_ not in visited:
visited.append(v_)
q.app... |
f9dbf898e031e9af9d6142b0842154842831c751 | Isaias301/IFPI-ads2018.1 | /Atividade E/fabio01_q24.py | 375 | 3.96875 | 4 | """ Questão: Lista E 24
Descrição: Leia um valor em m, calcule e escreva o equivalente em cm.
"""
def main():
# entrada
valor_metros = float(input("Digite um valor em metros: "))
# calculos, operacoes, processamento
valor_centimetros = valor_metros * 100
# saida
print('Valor em centimetros: %.2f cm' % valo... |
ab401de9fdf6e70a0add12d44d41a3e9c8acd089 | codebubb/python_course | /Semester 1/Project submissions/Andreas Georgiou/Semester 1 - Introduction to Programming/Semester 1 - Introduction to Programming/Week 3/Practice/Printing an index from a list test.py | 143 | 3.625 | 4 | subjects = ["Science", "Maths", "English", "IT"] # a list called subjects
print subjects[1] # prints index 1 from the list. index starts at 0
|
cbed05109f0dfdbe5e8fbece7e424bbf5ca57526 | eliomb/NERV | /8).py | 1,132 | 3.84375 | 4 | listanumeros = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
def romanos():
"""
esta funcion anda gracias a una list que contiene la tabla de conversion entre numeros
decimales a numeros rom... |
c380dd027b0dc660ff19f7d1fd02d46a63bf4f87 | gguillamon/PYTHON-BASICOS | /python_ejercicios basicos_III/if/ejericicio15.py | 960 | 3.953125 | 4 | #El director de una escuela está organizando un viaje de estudios,
#y requiere determinar cuánto debe cobrar a cada alumno y cuánto debe pagar
#a la compañía de viajes por el servicio. La forma de cobrar es la siguiente:
#si son 100 alumnos o más, el costo por cada alumno es de 65 euros; de 50 a 99 alumnos,
#el costo... |
779e4cfc3a605242d665a29f23795200b753be68 | itsmedeepak/pong-Game | /paddle.py | 409 | 3.71875 | 4 | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, x_cor):
super().__init__()
self.shape("square")
self.color("#6f03fc")
self.shapesize(stretch_wid=5, stretch_len=1)
self.penup()
self.goto(x_cor, 0)
'''paddle = Turtle("square")
paddle.color("#6f03f... |
33d384b717ba4bd50c06ff4e4495d92258c31a8b | guilhermegouw/codewars | /count_characters_in_your_string/test_count_characters_in_your_string.py | 380 | 3.734375 | 4 | """
test.assert_equals(count('aba'), {'a': 2, 'b': 1})
test.assert_equals(count(''), {})
"""
from .count_characters_in_your_string import count
def test_count_no_repetitive_letter():
assert count("abc") == {"a": 1, "b": 1, "c": 1}
def test_count_one_repetitive_letter():
assert count("aba") == {"a": 2, "b": ... |
10867367a266be9aaa778fe241a4f5181afb3a82 | daniel-gonzalez-cedre/school | /fsu/applied-machine-learning/EM-clustering/EM-clustering.py | 4,742 | 3.515625 | 4 | # Daniel Gonzalez, FSU Mathematics PhD
# Colton Piper, FSU Mathematics PhD
# Applied Machine Learning Assignment 10
from __future__ import print_function
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
#PARAMETERS FOR THE SCIKITLEARN GAUSSIAN MIXTURE MODEL
... |
9a2e1d00f0fb44ddc6b696747a87a22c6617985f | sjhawkes/EQ_risk | /.ipynb_checkpoints/eq_risk-checkpoint.py | 6,069 | 3.6875 | 4 | # This script reads in historical earthquake data from the Los Angeles region
# and prompts the user to enter the lat-long coordinates of a house for which
# to determine the historical earthquake risk
import pandas
import numpy as np
import matplotlib.pyplot as plt
import math
#load earthquake data from 1950-2020
lo... |
a1f21e56d751c1994bdd85e717956c5d725ba414 | ag5300cm/RetailProjectMid | /sqlDatabaseForRetail.py | 4,303 | 4.46875 | 4 |
import sqlite3
from sqlite3 import Error
# this should only run once, when you start up the program
def create_database_and_table():
sqlite_file = "myDatabase.db" # change database here
table_name = "potatoTable" # change table name here
conn = sqlite3.connect(sqlite_file) # making a connection
... |
7ccc1167c6b9d230908ca0acf6bba84afd999605 | avijoshi4u/Python | /generator.py | 270 | 3.6875 | 4 | '''geneartor are function that return a sequence of value back a geneartor function is just like any other
function but it uses a yield statement'''
def customegen(x,y):
while x<y:
yield x
x+=1
result =customegen(20,30)
for i in result:print(i)
|
059ec8021c83a911c614b261a16890d6baee596a | elsandkls/SNHU_IT140_itty_bitties | /regex_search_challenge_student.py | 1,630 | 5 | 5 | import re
#The string to search for the regular expression occurrence (This is provided to the student)
search_string='''This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression'''
print(search_string)
#1. Write a regular expression... |
ef824921c1c614516bca1709d2c2fad1e4fd5294 | noozip2241993/dictionary-python | /task15.py | 519 | 3.84375 | 4 | """Write a Python program to get the maximum and minimum value in a dictionary"""
def maximum_value(d):
maximum1 = -100000000000
for i in d.values():
if i > maximum1:
maximum1 = i
return maximum1
dic1 = {numbers:numbers*10 for numbers in range(1,6)}
print(maximum_value(dic1))
print(dic1)... |
8332b0e39a7d1a71dc41291853ae86e4db40eb3b | Nur99/yandex_lyceum | /2nd_year/WEB1. Знакомство с API/Class/04_zip_code.py | 640 | 3.65625 | 4 | from Samples.geocoder import geocode
def get_address_postal_code(address):
# Ищем переданный адрес, ответ получаем в формате json.
toponym = geocode(address)
# Извлекаем почтовый индекс.
postal_code = toponym["metaDataProperty"]["GeocoderMetaData"]["Address"]["postal_code"]
return postal_code
de... |
7b2ef5765a0723a3cd2e59416c6af1436a8aad50 | joseph-mutu/Codes-of-Algorithms-and-Data-Structure | /Leetcode/列表翻转.py | 745 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-02 21:15:19
# @Author : mutudeh (josephmathone@gmail.com)
# @Link : ${link}
# @Version : $Id$
import os
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution():
def ... |
fb90791848bb3d7f3fd54fa7b612ae3fc3d7bb9e | f4tihsahin/Python-Algoritma--Ornekleri | /Örnek_34/örnek_34.py | 444 | 3.625 | 4 | """
Girilen 10 sayidan pozitiflerin ve negatiflerin sayisini gösteren program
"""
pozitifSayisi = 0
negatifSayisi = 0
for i in range(0,10):
girilenSayi = int(input("{}. sayiyi giriniz : ".format(i+1)))
if girilenSayi > 0:
pozitifSayisi += 1
elif girilenSayi < 0:
negatifSayi... |
06020b4ec9cdb5f94159d1786fe2c1bc6d5afda6 | DaveFres/Python_Projects | /coursera/week_3/file_reader.py | 403 | 3.546875 | 4 | #!/usr/bin/env python3
class FileReader:
"""Класс FileReader помогает читать из файла"""
def __init__(self, path):
self.path = path
def read(self):
try:
with open(self.path, 'r') as f:
result = f.read()
return result... |
3aa20b249a574ee9fb785eb956c910244cc83922 | LeonildoMuniz/Logica_de_programacao_Python | /Atividades diversas/L_Cond_2_A.py | 469 | 3.78125 | 4 | A=0
B=0
C=0
A=int(input('Digite o valor de A: '))
B=int(input('Digite o valor de B: '))
C=int(input('Digite o valor de C: '))
if C>B:
if B>A:
print(A)
print(B)
print(C)
if B>C:
if C>A:
print(A)
print(C)
print(B)
if C>A:
if A>B:
print(B)
print(A)
print(C)
if A>C:
if C>B:
... |
e9149ea4b970fb4bfbd1eb2117ce5597a32a7ac9 | nullx5/Learning-the-Syntax-python | /ejemplo_ficheros_2.py | 1,105 | 3.6875 | 4 |
f= open(r"C:\Users\flop\Desktop\Ficheros_Python\ejemplo_ficheros_2.txt", "w")
num_car = f.write("Ana : 28\nJavier : 32\nEva : 45\nCarlos : 29")
print("-----------------------------------------------------------------")
print("Fichero escrito correctamente. Número de caracteres escritos: ",num_car,"\n")
f.close()
f =... |
91d75310a2804910586cb02ba89901be8c907d82 | IPCamp/mltraining | /multivar_linreg_gradient_descent/multivar_linreg_gradient_descent.py | 3,591 | 3.625 | 4 | ##################################################
## Author: Marton Szabo
##################################################
import numpy as np
if __name__ == '__main__':
# turn off scientific notation for printing numbers
np.set_printoptions(suppress=True)
# parameters of dragons
#
# t1: numbe... |
8a428157a55c4219805700091812c61724106d65 | dmcg89/CS-2.1-Trees-Sorting | /Code/sorting_recursive.py | 4,910 | 4.3125 | 4 | #!python
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
Running time: O(n) - iterates through all items of in inputs
Memory usage: O(n) - creates a new list the size of both inputs"""
... |
e62a4b0cf3e16dfb684e6bb5152fd5462ac8b8fb | PrashikshyaRegmi/stringfunction | /task.py | 289 | 4.125 | 4 | def word(string):
inputWords=string.split(" ") ##spliting the words
inputWords=inputWords[::-1] ##reversing the list word
output=' '.join(inputWords) ##join words
return output
if __name__=="__main__":
string = 'I type the string here'
print (word(string))
|
da40890f734f6f4f2c7e65777a258030004b5312 | Velraj55/Test1 | /expo.py | 280 | 4 | 4 | def raiseToPower(base_num,pow_num):
result = 1
#final = 1
for letter in range(pow_num):
result = base_num * result
print(result)
base_num = int(input("Enter base num:"))
pow_num = int(input("Enter pow num:"))
raiseToPower(base_num,pow_num) |
6b19c930409f373c62d7b40e59f934d57e4a3fad | Xinmudotmoe/pyglet | /tools/genmap.py | 3,330 | 3.59375 | 4 | """Usage: %s <arguments>
-h h draw hexes with given height in a rectangular grid
-x h draw hexes with given height in a hex grid
-r w[,h] draw a rect grid
-s w,h map size in cells (default=5,5)
-f render flat (default)
-o render orthographic projection
-... |
823d1d2bb4dda37d985583956f0f822458c3c30d | martin-bn/Prosjekt0 | /Oppgave4.py | 599 | 3.78125 | 4 |
def factorial(number):
if number < 0:
raise ValueError("Only positive numbers, please")
elif number == 0:
raise ValueError("Factorial of zero is 1")
else:
fac = 1
for i in range(1, number + 1):
fac = fac * i
return fac
def sin(x, N):
value = int(0)
... |
8de849e2c0bfa2e266ff52244dadd7e1cca535a8 | lsb530/Algorithm-Python | /파이썬챌린지/5.for루프/44.파티초대.py | 226 | 4.03125 | 4 | num = int(input("How many people do you want to invite party?: "))
if num < 10:
for i in range(num):
name = input("What's your name?: ")
print(f"{name} has been invited")
else:
print("Too many people")
|
137645afff17452e3243f2d1de4d0741c22128f8 | mv-debug/sdc11073 | /sdc11073/sdcdevice/intervaltimer.py | 1,255 | 3.578125 | 4 | from time import monotonic, sleep
class IntervalTimer(object):
''' this is a timer that does not drift (but is has jitter). '''
VERBOSE = 0
def __init__(self, periodInSeconds, activeWaitLimit=0.0):
self._period = periodInSeconds
self._activeWaitLimit = activeWaitLimit
... |
0a0bef3220b29c9e04442eab0f39a984a82a4a74 | frtug/Euler_Project | /euler2.py | 236 | 3.828125 | 4 | def factor():
x = int(input("enter the number"))
max =0
for i in range(2,x):
if x%i == 0:
print(i)
if i >max:
max = i
x = x/i
print('max',str(max))
|
563841dfc875e6bda2e490a8de47326a080ba11c | mivalov/HackerRank-py | /src/basic_certification_exam/sample_test_fizzbuzz.py | 583 | 3.9375 | 4 | #!/bin/python3
# import math
# import os
# import random
# import re
# import sys
# Complete the 'fizzBuzz' function below.
#
# The function accepts INTEGER n as parameter.
#
def fizz_buzz(n):
# Write your code here
for i in range(n+1):
if i == 0:
continue
elif i % 3 == 0 and i %... |
1b41de1ef00fd7946067f6b11cdf66eb8cb9bc8a | alvinwang922/Data-Structures-and-Algorithms | /LinkedList/LinkedList-Cycle.py | 1,076 | 4.0625 | 4 | # Given a linked list, determine if it has a cycle in it.
# To represent a cycle in the given linked list, we use
# an integer pos which represents the position (0-indexed)
# in the linked list where tail connects to. If pos is -1,
# then there is no cycle in the linked list.
# Definition for singly-linked list.
clas... |
0c8728c33007d7d7f48e0156a1000fd0a774ea98 | jbofill10/COSC450-Lab1 | /program1.py | 784 | 4.1875 | 4 | import random
'''
Author: Juan Bofill
Description: Takes input of an array or generates a random array and does quicksort on it
'''
def run_quicksort(arr):
if len(arr) <= 1: return arr
return run_quicksort([l for l in arr[1:] if l < arr[0]]) + arr[0:1] + run_quicksort([h for h in arr[1:] if h >= arr[0]])
if __... |
1029113f302144e79300cb57768a7f56c651f310 | BradenRowlands/CP1404Practicals | /Prac08/TaxiFair.py | 1,656 | 3.9375 | 4 | from Prac08.taxiCode import Taxi, SilverServiceTaxi
def main():
menu = "Q)quit, C)Choose taxi, D)drive"
user_input = ""
total_bill = 0
taxis = [Taxi("Prius", 100),
SilverServiceTaxi("Limo", 100, 2),
SilverServiceTaxi("Hummer", 200, 4)]
cab_decision = choose(taxis)... |
a3d4ed591a4dc5efdba72bd735dab9d0cff22c32 | pcleddy/codeex | /004_palindrome.py | 354 | 3.6875 | 4 | #!/usr/bin/python
m_palidromes = []
def isPalindrome(m_num, m_palidromes):
if ( str(m_num) == str(m_num)[::-1] ):
m_palidromes.append(m_num)
return m_palidromes
for m_left in xrange(999, 100, -1):
for m_right in xrange(999, 100, -1):
m_palidromes = isPalindrome(m_left * m_right, m_palidromes)
m_palidr... |
46dca896993bae7a7fbd17bbfba69b4ea302e779 | ihomya/LearnPython | /basic/str_format.py | 699 | 3.84375 | 4 | # 格式化字符串
# 占位符 %s 替换内容 字符串
print('Hello,%s'% 'world')
# 占位符 %d 替换内容 整数
print('your age is %d'% 18)
# 占位符 %f 替换内容 浮点数
print('PI is %f'% 3.1415)
# 占位符 %x 替换内容 十六进制整数
print('16的十六进制是 %x'% 16)
# 如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串
print('Age: %s. Gender: %s' % (25, True))
# 用%%来表示一个%
print('growth rate: %d %%'... |
61289a51debd79b06c07de14456ab6977465ab50 | blarkin13/python_projects | /text_game_wizard.py | 12,147 | 3.765625 | 4 | import random
var_health = 10
var_dammage = 1
var_st_dammage = 3
var_heal = 3
var_potion = 1
var_response = ''
while 1:
var_un = input('Enter Nickname:')
if var_un != "":
break
input('It is a cold stormy night...')
input('In the forest lives monsters. The monsters are prepairing to storm the ca... |
0e6b8ba222f19997899dc76b341db8b9b4d53400 | rlarkdtks312/cording_test_practice | /비밀지도.py | 744 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 12:07:37 2021
@author: kim
"""
def solution(n, arr1, arr2):
answer = []
binary_arr1 = []
binary_arr2 = []
for q in range(0, n, 1):
answer.append('')
for i in range(0, n, 1):
binary_arr1.append(bin(arr1[i])[2:].zfill(n)... |
150f19235a7ee075826eb752dedeeddaa923ee5d | S2606/Project_Euler | /exp1.py | 208 | 4.25 | 4 |
'''
Sum of number which are multiples of 3 or 5
'''
import math
if __name__ == "__main__":
count=0
for i in range(1,1000):
if(i%3==0 or i%5==0):
count=count+i
print(count)
|
337f58aa47fac3db7832c9c8ed0bd0ea3364eb34 | christophercalm/Processor-Scheduling-Algorithms | /fcfs_sjn.py | 2,329 | 4.0625 | 4 | #This program simulates the FCFS algorithm and the Shortest Job Next Algorithm
#The SJN program sorts the jobs by size before processing.
#Function to find waiting time of each job being processes
def findWaitingTime(job_list, wt):
# waiting time for first job is 0
wt[0] = 0
# calcu... |
d8d10d7481c4f6f01e5700f5e7de33e56bfe1fb6 | ManishShah120/Python_Basics_4_Data_Science | /Data Structure/Lists/Chapter 8(Lists)(Building a List from Scratch).py | 350 | 4.03125 | 4 | stuff = list() #Constructor form
stuff.append('Book')
stuff.append(99)
print(stuff)
stuff.append('Cookie')
print(stuff)
#Is something in a List?
some = [1, 9, 21, 10, 16]
print(9 in some)
print(15 in some)
print(20 not in some)
#Lists are in Order
friends = ['Joseph', 'Glen', 'Sally']
print(friends)
... |
2102b729f89599fdf929315c7c1d1826b10a76f9 | jwaldrep/game-of-sticks | /game_of_sticks.py | 8,637 | 3.578125 | 4 | import random
class SticksGame:
def __init__(self, p1, p2, sticks=100, silent=False):
self.current_player = p1
self.player_a = p1
self.player_b = p2
self.max_draw = 3
self.player_a.initial = '1'
self.player_b.initial = '2'
self.set_sticks(sticks)
sel... |
9c91faf72af67c5286f6949629a70967aacb0ab2 | shell-escape/EMAP_python_April2021_homeworks | /homework_2/task_1.py | 4,434 | 4.25 | 4 | """
Given a file containing text. Complete using only default collections:
1) Find 10 longest words consisting from largest amount
of unique symbols
2) Find rarest symbol for document
3) Count every punctuation char
4) Count every non ascii char
5) Find most common non ascii char for document
""... |
6282ac04e91dcdfbbf448ffa59064e97cc3721b2 | osbaldoisaias/B1-Programacion-Con-Python-2020 | /Sesion-01/Reto-01/reto_variables.py | 172 | 3.765625 | 4 | print("inserta número")
a = input()
print("inserta otro número")
b = input()
num1 = int(a)
num2 = int(b)
concatena = a+b
suma = num1+num2
print(concatena)
print(suma) |
ae51833076f7d657708a2b420b7dc76f3fce7abe | andersonpereiragithub/CursoEmVideoPython | /exerc112/utilidadescev/moeda/__init__.py | 1,357 | 3.859375 | 4 | def aumentar(preco=0 , taxa=0, formato=False):
"""
--> Calcula o aumento de um determinado preço,
retornando o resultado com ou sem formatação.
:param preco: o preço que se quer reajustar.
:param taxa: qual é a porcentagem de aumento.
:param formato: quer a saída formatada ou não?
:return:o ... |
62a17b38cf32740da3004f2fdee4e2007f100a51 | birtnieva/PythonCodesRepository | /MapReduceSample/Mapper.py | 517 | 3.90625 | 4 | # Mapper.py
# Run on Python3
import sys
import re
count = 1
# Loops through input lines of text
for input in sys.stdin:
# Strip off spaces in beggining and end of input line
input = input.strip()
# Remove characters (.,!?) and convert text to lower case
input = re.sub('[^a-zA-Z\-]+', ' ', i... |
f48c3372be248e0652140b25de0e22d79be91a72 | luoyanhan/Algorithm-and-data-structure | /Leetcode/medium/142.py | 863 | 3.78125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head):
node = head
visited = set()
while node:
if node in visited:
return node
visited.... |
648813b119d6b6f0b6b91f8b20ba1bb519f27fb6 | simeon-petrov-5/Hack-Bulgaria-Python-101 | /week03/panda-test.py | 921 | 3.609375 | 4 | class Panda():
def __init__(self, name, age, weight):
self._name = name
self._age = age
self._weight = weight
def eat(self, amount):
self._weight += amount
def sleep(self):
self._age += 1
def get_age(self):
return self._age
def get_weight(self):
#Method za doobrabotvane | Ako se importva classa ... |
7dbcb985b1c6b93ef455a92a8a9222b6bc638b79 | ntk148v/til | /protocolbuffers/python/reading_message.py | 1,145 | 3.53125 | 4 | import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them
def list_people(address_book):
for person in address_book.people:
print("Person ID: ", person.id)
print("* Name: ", person.name)
if person.HasField("email"):
print("* Ema... |
a93579a84ffe7132188eca714c30088a93432d14 | Nitesh221194/Python | /pattern_A-Z/M.py | 274 | 4.09375 | 4 | i=4
for row in range(7):
for col in range(5):
if (col==0 )or (row==col<3):
print('*',end=" ")
elif (col==4)or(col==i and row<2):
print('*',end=" ")
i-=1
else:
print(end=" ")
print() |
d49bb0c631c5f243d4facb6a54c8f710e7bc84b0 | taylorbcool/Graphs | /projects/graph/graph.py | 7,297 | 4.15625 | 4 | """
Simple graph implementation
"""
from util import Stack, Queue # These may come in handy
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
"""
Add a vertex to the gr... |
b6930c2724387898dd53a217915b44aeb2efbbda | F4Francisco/Python_Tut | /PythonTut5.py | 4,001 | 3.890625 | 4 | #Functions
'''
def add_numbers(num1, num2):
return num1 + num2
print("5 + 4 = ", add_numbers(5,4))
#local variables cant be used
def assign_name():
name = "Doug"
assign_name()
print(name)
#Error:Name not defined
def change_name(name):
name = "Mark"
name = "Tom"
change_name(name)
print(name)
# Will prin... |
fe02e22cacdc13cf9401b6fa892af4109b16d447 | flysaint/Sword_Offer | /chapter/2_3_3_从尾到头打印单链表.py | 1,589 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 14:44:52 2019
@author: DELL
面试题5 从尾到头打印单链表
从尾到头打印单链表
思路1:使用栈
思路2:递归
"""
import numpy as np
class Node:
def __init__(self,x):
self.val = x
self.next = None
class Link:
@staticmethod
def link(values):
head = Node(0)
move = ... |
cadafc837b4a8adfbb567aeff66cbbd8ce83784d | celsopa/IFAL-ESTD114_Estrutura_de_dados | /Lista03 - Recursão/l3q9.py | 653 | 4 | 4 | # 9. O MDC de dois números inteiros é o maior número inteiro que divide ambos sem deixar resto.
# O MDC pode ser calculado através do algoritmo de Euclides. Abaixo uma função iterativa que calcula o MDC.
# Reescreva a função abaixo de forma recursiva.
# def MDC(a, b):
# while (b != 0):
# r = a % b
# a = b
# b = r
# ret... |
82e24168e218730673fb6448f00565443aa574d4 | Technoguy01/hacktoberfest-is-ending | /rock_paper_scissors.py | 1,091 | 3.90625 | 4 | import random
from time import sleep
symbols = ['🪨','🧻','✂️']
print('You are bout to start a rock-paper-scissors game. Make your choice.')
for i in range(3):
print(i, symbols[i])
usr_play = int(input('Enter your choice'))
cpu_play = random.randint(0,2)
if usr_play == cpu_play:
print(symbols[usr_play], "I... |
49b675bb7c8635e8284c473cbb9ae44803ebf988 | gorgonun/projects-cs50 | /similarities/less/helpers.py | 1,048 | 3.578125 | 4 | from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
listLines = []
a = set(a.split("\n"))
b = set(b.split("\n"))
for line in a:
if line in b and line not in listLines:
listLines.append(str(line))
return listLines
def sentences(a, b... |
edb94c76d8b9a0d0dec3dd66b5cc442aca0b2d1b | MasatakeShirai/Python | /chap12/12-3.py | 700 | 4.46875 | 4 | #関数オブジェクト
# Pythonでは関数を制限のないオブジェクトとして利用できる
def square(x):
return x**2
print(square)
# ()をつけることで関数を実行できる
print(square(3))
# オブジェクトなので,引数としても利用できる
def distance(x,y,func):
print(func)
return func(x-y)
print(distance(2,1,square))
# 関数の中で関数を定義することも可能
def func():
def inner_func():
pass
print... |
8862ac2d23999d4a481d5889cbd51c04471283dd | Inna99/homework | /homework7/task1.py | 749 | 4.15625 | 4 | """
Given a dictionary (tree), that can contains multiple nested structures.
Write a function, that takes element and finds the number of occurrences
of this element in the tree.
Tree can only contains basic structures like:
str, list, tuple, dict, set, int, bool
"""
from typing import Any
def find_occurrences(tr... |
1c8f9d401264564626af7439ae078e4e67a6eda7 | shubhamjain700/Basic_code | /Palindrome.py | 139 | 3.765625 | 4 | # a=input()
#
# if a==a[::-1]:
# print("Palindrome" )
# else:
# print("Not Palindrome")
#
#
a="Shubham jain"
b=a.split(' ')
print(b[0])
|
c6f94e4e6485830658f991abc26c42c938966e4e | sindhu-thanikonda/Assignment--1_Python- | /1.py | 315 | 4 | 4 | """
WAP find the average of given list of elements representing a grade of student.
grades = [84, 84, 93, 78, 86, 73]
"""
Grades = [84, 84, 93, 78, 86,73]
count = 0
num = 0
for i in Grades:
num = num + i
count = count +1
Average = num/count
print "Average of the List: ", Average
|
53e3b8b1ee172684d18bbebf143ad997fe0fafa4 | antohneo/pythonProgramming3rdEdition | /PPCh5PE9.py | 493 | 4.125 | 4 | # aaa
# Python Programming: An Introduction to Computer Science
# python3
# Chapter 5
# Programming Excercise 9
def main():
# intro
print("This program counts the nuber of words in a sentence.")
# prompt for phrase
sentence = str(input("Enter a sentence: "))
# split phrase and count words
word... |
20aa7faa3c5e7fb6c687dbe9086b799317e5282c | ErisonSandro/Exercicios-Python | /exercicios/ex016-Quebrando um numero.py | 161 | 4 | 4 | import math
valor = float(input('Digite um valor: '))
pi = math.trunc(valor)
print('O valor digitado foi {} e a sua porção inteira é {}'.format(valor, pi))
|
9e14759bcc60237e2027ac05d5e011d7981ca1b6 | dan-kiss-dev-this/python-coursework-certification | /functions3.py | 3,084 | 4.25 | 4 | def greet_person(name = 'Rock'):
'''
the 3 quotes give info
:param name: string
:return: string
'''
print('some info')
print('Hello there, ' + str(name))
return 'hello there ' + str(name)
z = greet_person(11) # passing in the name is optional
print(z)
def remainder(num1, num2):
r... |
1a39e7de6615e57ee8f4b518c8413463f32830f6 | vchandrakiran/Summer-Workshop-django | /Day-2/inherit.py | 293 | 3.59375 | 4 | class Person:
def __init__(self,age,mailid):
self.age=age
self.mailid=mailid
def getage(self):
return self.age
def getmailid(self):
return self.mailid
class Emp(Person):
def data():
obj=Person(25,"vijay@gmail.com")
print(obj.getage())
print(obj.getmailid())
obj=Emp
obj.data()
|
d1e8e334877f1396c6b4129601896dce4d8f15a6 | rdaniela00/proyectos | /python/calculos/calculos_generales.py | 344 | 3.625 | 4 | def suma(op1, op2):
print("la suma del total es ", op1+op2)
def resta(op1, op2):
print("la resta del total es ", op1-op2)
def multiplicar(op1, op2):
print("el resultado del total es ", op1*op2)
def potencia(base, exponente):
print("el resultado es", base**exponente)
def redondear(numero):
print("el resultad... |
925d29a6428c30f8d60ef470fdf457897b469a99 | petesndrs/progspeed | /python/goldbach_conjecture/gold.py | 4,092 | 4 | 4 |
NUMBER_PRIMES=300
class node:
def __init__(self):
self.value = None
self.smaller = None
self.larger = None
def largest_pow2(number):
power = 0
while (number != 1):
number >>= 1
power+=1
return 1<<power
def create_tree(primes, current, last, nodes):
distance = current - last... |
cbe00c83d2fae5720c6a0145c88303b34e962e6c | se2313se/basics-of-programming-on-Python | /1/nxtprv.py | 177 | 4.03125 | 4 | X = int(input())
print('The next number for the number', X, 'is', X+1, sep=' ', end='.')
print()
print('The previous number for the number', X, 'is', X-1, sep=' ', end='.')
|
db08c56dd5d5e2e26b3eea6b6e0c54badf2a7d9b | potato179/pythonProjectwlswodnd | /문제 300/문제 111~120.py | 1,679 | 3.71875 | 4 | # 반복문
# 111.
문자열 = input("문자열을 입력하세요 : ")
print(문자열*2)
# 112.
숫자 = int(input("숫자을 입력하세요 : "))
print(숫자+10)
# 113.
숫자 = int(input("숫자을 입력하세요 : "))
if 숫자%2 == 0 :
print("짝수입니다")
else:
print("홀수입니다")
# 114.
숫자 = int(input("숫자을 입력하세요 : "))
if 숫자+20 >= 255 :
print(255)
else:
print(숫자+20)
# 115.
숫자 = int... |
f592ba078f90f5f628da16571b4437477be5a6b1 | gyassine/Machine-Learning | /Partie 6 - Reinforcement Learning/2-Thompson Sampling/thompson_sampling.py | 2,271 | 3.546875 | 4 | # Copyright (c) 2019 SunnyShark - All Rights Reserved
# thompson_sampling.py is part of the project Introduction au Machine Learning
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Created by Yassine Gangat <yg@sunnyshark.com> on 27/09/2019 09:17.
# Las... |
daceb415266fcd7ae60098595409e758e1192307 | Ma11ock/in-class-git | /calc.py | 310 | 3.859375 | 4 | #!/usr/bin/env python
def calc(a, b):
sum = a + b
divid = a / b
mult = a * b
lesser = a - b
modulo = a % b
myList = [ sum, divid, lesser, modulo, mult ]
listSum = 0
for i in myList:
listSum += i
print(listSum)
print(myList)
calc(3, 4)
|
249c0616c8cd17821e725d43cdc3d721be038fa8 | MrBearTW/somewhere | /pythonCrawler/demo04.py | 316 | 3.5 | 4 | import os
def main():
users = [{
'name': 'john',
'age': 25
}, {
'name': 'marry',
'age': 32
}, {
'name': 'Simon',
'age': 27
}]
print(users)
usernames = [user['name'] for user in users]
print(usernames)
if __name__ == '__main__':
main() |
657815a7fcf4672063b7099abd032b7fab7f51a6 | mahesh122000/Data-Structures | /Array/Harshad number.py | 953 | 3.515625 | 4 | def checkHarshad( n ) :
sum = 0
temp = n
while temp > 0 :
sum = sum + temp % 10
temp = temp // 10
return n % sum == 0
def safe(arr,m,n,i,j):
if(i>=m or j>=n or i<0 or j<0):
return False
if(checkHarshad(arr[i][j])):
return True
return False
def check(arr,m,... |
6f7f09bdca1fb9ea9b1de1ef751cd5d111d3d035 | yumeiliu/learnpython | /19Fibonacci_recursion.py | 161 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def sequence(n):
if n==1 or n==2:
return 1
else:
return sequence(n-1) + sequence(n-2)
x = int(input())
s = sequence(x)
print(s)
|
a58dd83b76043b15f99c1b4e9487fbf0b2947a80 | ProsenjitKumar/Recursion-and-Fibonacci-sequence | /recursion.py | 505 | 4.09375 | 4 | # f(x) = f(x - 1) + 2 and where f(0) return 1
# f(3) = f(3 - 1) + 2
# = f(2) + 2
# f(2) = f(2 - 1) + 2} + 2
# = f(1) + 2} + 2
# f(1) = f(1 - 1) + 2} + 2] + 2
# = f(0) + 2} + 2] + 2
# f(0) = f(1) + 2} + 2] + 2
# = 7
def f(x):
if x == 0:
return 1
else:
return f(x - 1) + 2
print(f(int(input("En... |
91f2771182ab7e739efe3ce7df3b36a14158a5b0 | curiousTauseef/docluster | /model_template.py | 1,551 | 3.734375 | 4 | from docluster.core import Model
class YourModelName(Model):
def __init__(self, model_name='YourModelName'):
"""
<One-liner description of your model>
Credits:
--------
This was adapted from a post/code from <Name of author (which can be you)> that can be
found he... |
fc1ec6534e1a227b6519ac7385ed3fd7e91f4edc | saidaHF/InitiationToPython | /exercises/algebra1.py | 1,655 | 4.5625 | 5 | #!/usr/bin/env python
# solution by cpascual@cells.es
"""
Exercise: algebra1
-------------------
Use numpy arrays for performing algebraic manipulations of matrices and vectors
1. create the following 3x3 square matrix:
M = np.array([[1,2,0],
[0,2,0],
[0,0,3]])
... |
a2674261468aa1e12fbf585eccc4fdc89276ba17 | venkateshmorishetty/CSPP1 | /M11/p4/assignment4.py | 776 | 3.828125 | 4 | #Exercise: Assignment-4
#We are now ready to begin writing the code that interacts with the player. We'll be implementing the playHand function. This function allows the user to play out a single hand. First, though, you'll need to implement the helper calculateHandlen function, which can be done in under five lines of... |
8040ca379d94bdcd970434b46f9edfdac828a665 | STBlackHawk/HackerRankChalenges | /CoinChangeProblem.py | 390 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HackerRank: CoinChange Problem
@author: blackhawk
"""
dic = {}
def getWays(n, c):
if (n,tuple(c)) in dic:
return dic[(n,tuple(c))]
else:
if n < 0 or not c: return 0
elif n ==0 : return 1
else :
ans = getWays(n-c[0], ... |
ab6363333b45b05b2ba9ffec20db2c08d304995a | aubique/daily | /python/p3_181015_2234.py | 550 | 4.09375 | 4 | #!/usr/bin/env python3
#p3_181015_2234.py
# Capitalize each word
def handler(text):
newString = list()
string = text.split()
for word in string:
if word != string[0]: newString.append(' ')
newString.append(capitalize(word))
print(''.join(str(char) for char in newString))
def capitalize... |
f3105ce80d82a84234f2b6837dbdc55aea355377 | green-fox-academy/attilavaczy | /python-practice/21.py | 136 | 3.578125 | 4 | u = 9
#ver2 out = ()
if u >= 10 and u <= 20:
print('sweet')
#out = sweet
elif (u < 10):
print('More')
else:
print('Less')
|
3c98863b372b30fe982599391bd628d3ea2217e4 | Maurya232Abhishek/Python-repository-for-basics | /Dictionary.py | 83 | 3.609375 | 4 | d1={'ram':101,'shyam':102,'mohan':103}
print(d1)
print(d1['ram'])
d={}
while(true)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.