blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
747f91c1df9f422dd403be1866534deb285128ec | dlee533/comp1510-programming-methods | /Assignments/A1/colour_mixer.py | 1,445 | 4.375 | 4 | def colour_mixer():
"""
print the result of two mixed colour
:postcondition: prompt user to input colour_one, a primary colour
:postcondition: prompt user to input colour_two, a different primary colour
:postcondition: if two colours are identical, print error message
:postcondition: print mi... |
6867a98ba807d7315ef85497d0e22b1e24fb49f7 | dlee533/comp1510-programming-methods | /Labs/Lab10/question_2.py | 697 | 3.828125 | 4 | import doctest
def gcd(a: int, b: int) -> int:
"""Divide until remainder is zero
:param a: an integer
:param b: an integer
:precondition: a must be an integer
:precondition: b must be an integer
:postcondition: if b/remainder from previous division is zero, return a
:postcondition: calcul... |
e3b47def425ebcacc2e150a99014c874a4d3ef9e | Sahha2001000/4LabForParadigmsProgramming | /Lab4Task1__Vasyliev/Rational.py | 2,289 | 4 | 4 | class Rational(object):
def __init__(self, numerator=1, denominator=1):
self.__numerator = numerator
self.__denominator = denominator
def meetUser(self):
print(
"\nThis program help you calculute (*,/,-,+) and output fraction standart and decimal from your 2 numbers\n")
... |
c2513970bb475c20a1ce61312bc3091de925ac47 | RonakAggarwal/Python | /PlusMinus.py | 279 | 3.546875 | 4 | #Plus Minus
n=int(input())
inp=input()
arr=inp.split(' ')
sum1,sum2,sum3=0,0,0
for i in arr:
if int(i)>0:
sum1+=1
elif int(i)<0:
sum2+=1
else:
sum3+=1
sum4=int(sum1+sum2+sum3)
print(sum1/sum4)
print(sum2/sum4)
print(sum3/sum4)
|
4ef850b402c97dd5a0f63bc0f13d3ccf27d8856c | simonzs/applet | /backend/algorithm/arithmetic_analysis/bisection.py | 1,142 | 3.859375 | 4 | # -*- encoding: utf-8 -*-
'''
@File : bisection.py
@Time : 2019/12/06 11:04:53
@Author : Simon
@Version : 1.0
@Desc : 二等分
'''
# here put the import lib
import math
def bisection(
function, a, b
): # find where the function become 0 in [a, b] using bisection
start = a
end = b
... |
ef971f1f1d413aab9b252302314560b875eb35ba | simonzs/applet | /backend/tests/test.py | 1,096 | 3.703125 | 4 | from typing import List
def threeSum(nums: List[int]) -> List[List[int]]:
# one_list = list()
two_list = list()
three_list = nums
result = list()
for r_ind, three in enumerate(three_list):
one_list = list()
for w_ind, two in enumerate(two_list):
... |
4aced51cc95533af43ebee0369b75ef2296c154d | JackKoLing/python_study_notes | /Other-Python-Notes/L18.py | 2,490 | 4.0625 | 4 | # coding : utf-8
""" 小测试:验证用户密码 """
password = '147258'
count = 3
while count :
count -= 1 # 用减法更好,因为可以直接打印剩余次数。并且如果是减法,循环直接while true
p = input("请输入密码:")
if p == password:
print("密码输入成功")
break
elif count == 0:
print('密码错误,不允许进入')
else:
print('密码错误,你还有', cou... |
e8dde36d4cf044ae12e6ed23833783eead85807f | flyinacres/PyT | /AndS2.py | 915 | 3.59375 | 4 | __author__ = 'rfischer'
def allStringsStartingWith(c):
string_set = set()
i = 0
while i > -1:
i = _s.find(c, i)
if i > -1:
for j in range(i, len(_s)):
string_set.add(_s[i:j+1])
# iff an occurrence was found, skip it next time
i += 1
re... |
7149b87f5fc1b3754861348657725ad6b7da794e | akshaysmin/Web-Of-Science-Scraper | /dateVsTermInTitle.py | 866 | 3.59375 | 4 | from pprint import pprint
import sys
'''
uses : 'resultsxl.txt'
goal : create a dictionary with keys as year and values as no. of titles with given term published in respective years
design: a counter for "term in title" while looping through each data row for each "year"
'''
filename='resultsxl.txt'
term='solution'
i... |
2991eedef4d0e7771dc8967ffb9d671314f39327 | danny-hunt/Problems | /increasing_subsequence/longest_increasing_subsequence.py | 1,753 | 4.15625 | 4 | """
Given an array of numbers,
find the length of the longest increasing subsequence in the array.
subsequence does not necessarily have to be contiguous.
For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15],
the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, 15.
"""
... |
457711a60b6f3f5dab2cd6dd61a12cf5156551e2 | danny-hunt/Problems | /step_words/step_words.py | 2,012 | 4.34375 | 4 | """
A step word is formed by taking a given word, adding a letter, and anagramming the result.
For example, starting with the word "APPLE", you can add an "A" and anagram to get "APPEAL".
Given a dictionary of words and an input word, create a function that returns all valid step words.
"""
import json
from string imp... |
e0e4cc16eb19a1d354891bff86c27f233184b592 | danny-hunt/Problems | /common_subsequence/common_subsequence.py | 2,445 | 4.125 | 4 | """
Write a program that computes the length of the longest common subsequence of three given strings.
For example, given "epidemiologist", "refrigeration", and "supercalifragilisticexpialodocious",
it should return 5, since the longest common subsequence is "eieio".
"""
# refzzzzz rezzzzzzzzz rez
# abcd cdef efab
# a... |
66953975dec128b6f55115cc91858a7ba98bd8e7 | danny-hunt/Problems | /binary_heap.py | 1,293 | 3.640625 | 4 | from random import randint
from __future__ import annotations
from typing import List
class BinaryHeap:
def __init__(self, value):
self.value = value
self.children = [None, None]
def __str__(self):
return_string = ""
return_string += str(self.value)
for child in self.... |
396e63dad4ac02a5c1b5607e9d0ed4dff0fe7b24 | danny-hunt/Problems | /fibonacci_sums.py | 645 | 3.640625 | 4 | class AlicesBirthday:
def generate_fibs(self, k):
fibs = [1, 1]
n = 2
while n < k:
fibs.append(fibs[n - 2] + fibs[n - 1])
n += 1
return fibs
def partition(self, k):
if k % 3 == 1:
return [-1]
if k % 3 == 0:
fibonac... |
8607760a3716624011118807729f12e52b23894e | danny-hunt/Problems | /partition_multiset/partition_multiset.py | 933 | 4.25 | 4 | """
Given a multiset of integers,
return whether it can be partitioned into two subsets whose sums are the same.
For example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true,
since we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55.
Given the multiset {15, 5, 20, 10... |
751937b495a2d8e88363d8147a0b36badaefa20f | herzenuni/sem3-rot13-311017-AnnGoga | /rot13.py | 923 | 3.546875 | 4 | def rot_13(text):
def rot(englishlang):
i='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.find(englishlang)
if i!=-1:
return 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'[i]
else:
return englishlang
return "".join(map(rot, text))
print(rot_13('noenpnqnoen')) #результат: abracadabr... |
dc9de2e8c97e7022f5852dcbdd8d969c56a8aed5 | konigin144/Project_PT | /SQLQuery/print.py | 1,097 | 3.9375 | 4 | import sqlite3
#Connecting to sqlite
conn = sqlite3.connect('AppDB.db')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
cursor.execute('PRAGMA encoding="UTF-8";')
#Doping EMPLOYEE table if already exists.
#cursor.execute("DROP TABLE IF EXISTS Devices")
#Creating table as per requirement
sq... |
40e0eb5d4fb4eae2d4afb570cb7352ce2bf013eb | nikuzuki/I111_Python_samples | /4/10.py | 632 | 3.84375 | 4 | # 2分探索法
def find(x, s):
print("find {}".format(x))
left = 0
right = len(s) - 1
while True:
mid = (left + right) // 2
print(mid)
print("[{}, {}] mid = {}".format(left, right, mid))
if x == s[mid]: # 見つかった
return mid
if x < s[mid]: # 左側にあるかも
... |
37032c4328c612b92ae9180a5742ee229877fa51 | nikuzuki/I111_Python_samples | /3/17.py | 479 | 3.703125 | 4 | # 配列に昇順に要素を入れた場合の探索(改良版)
s = [3, 9, 12, 25, 29, 33, 37, 65, 87]
x = int(input())
print("min : ", s[0])
print("max : ", s[len(s)-1])
sum = 0
for i in s:
sum += i
print("average : ", sum/len(s))
center = int((len(s)-1)/2)
print("center : ", s[center])
s.append(x+1) # x+1をsの末尾に追加
i = 0
while(s[i] < x):
i += 1 ... |
45804befa6247ce0706c80591718cf9154a7a281 | nikuzuki/I111_Python_samples | /1/20.py | 193 | 3.8125 | 4 | # 閏年判定例
year = int(input())
if year%400==0 or (year%100!=0 and year%4==0):
print(str(year)+"年は閏年です.")
else:
print(str(year)+"年は閏年ではありません.")
|
16de5aad233066ae56120f21517c74261a9785bc | nikuzuki/I111_Python_samples | /6/list_stack_sample.py | 805 | 4.125 | 4 | # p8 連結リストを使ったstackの実装
class Node:
def __init__(self, i, n):
self.data = i
self.next = n
class StackLL:
def __init__(self):
self.top = None
def push(self, x):
n = Node(x, self.top)
self.top = n
def pop(self):
if self.top != None:
topvalu... |
feed8fd9b44b22e65f595b681c5bab688d7ed8e3 | skyying/euler | /020/20.py | 241 | 3.828125 | 4 |
def factorial(n):
m = 1
for i in range(1, n+1):
m *= i
return str(m)
def sum_of_factorial_digits(n):
m = factorial(n)
return sum([int(x) for x in m])
print(sum_of_factorial_digits(100))
|
23ceac17a3cb255727d5ca5aee5fff13cc361e5d | skyying/euler | /010/10.2.py | 948 | 3.921875 | 4 | import math
# using sieve of eratosthenes
# this is much faster, the execution time is about 0.482s.
# the concept of this algorithm can be found in this video
# https://www.youtube.com/watch?v=eKp56OLhoQs
# find sum of prime below n
def sum_of_primes(n):
primes = [1 for i in range(0, n + 1)]
# mark 0 and 1 ... |
db2979a43362adec4d8e1a89bf49cede4c1ca240 | muojie/python_sample | /nsfg/test.py | 971 | 3.5625 | 4 | import survey
table = survey.Pregnancies()
table.ReadRecords()
print ('Number of pregnancies', len(table.records))
def life(data_dir):
preg = survey.Pregnancies()
preg.ReadRecords(data_dir)
pregfirst = survey.Pregnancies()
pregothers = survey.Pregnancies()
prglenfirst = 0
prglenothers = 0
... |
73d7bcd07d00a861b875a0db295f14433e088e23 | scaryswe/Chatbot | /Chatbot.py | 1,213 | 3.703125 | 4 | #chatbot Ashraj Grewal cs1.0
import random
def get_bot_response(user_response):
bot_response_happy = ["Great! That's how you belong", "Keep the good times going!", "Good, life is too short to be anything else"]
bot_response_angry = ["Sorry to hear that, take some time to think", "Have a cup of tea!", "Go liste... |
a8b45f0f1aad107de27ab5c841dccb78b143a9cd | 1Blademaster/PiWars-2019_20 | /gpio_waldo_better.py | 525 | 3.5 | 4 | import RPi.GPIO as GPIO
from time import sleep
#front axle 1 is left, 2 is right
GPIO.setmode(GPIO.BCM)
Motor1f = 2 # Input Pin yellow
Motor1b = 3 # Input Pin white
Motor1e = 4 # Enable Pin bl
GPIO.setup(Motor1f,GPIO.OUT)
GPIO.setup(Motor1b,GPIO.OUT)
GPIO.setup(Motor1e,GPIO.OUT)
print("... |
d97c283f254ba62df402ca98f38eb1a518e03c37 | notlesz/IGTI-Python | /2 - Analise de Dados/Aula 5.py | 1,492 | 3.578125 | 4 | #Outras operacoes com NUMPY
import numpy as np
x = np.array([[1,3,7],
[4,11,21],
[42,8,9]])
print("X:\n",x)
print(20*"=")
print("Transformacao de um array:\n",x.reshape(1,9)) #Refaz o array nessa condicao (9 linhas e 1 coluna)
print(20*"=")
#Transposicao de matriz(linha em coluna e coluna em... |
71d5292b1a15bb5407fd89023219de42ebf41a4f | notlesz/IGTI-Python | /2 - Analise de Dados/Aula 6.py | 1,069 | 3.84375 | 4 | #Regressão linear numpy
#Visualização de dados
from matplotlib import pyplot as plt
#dados
x = [1, 2 ,3 ,4 , 5, 6]
y = [10, 50 , 100, 150, 200, 250]
#plot dos dados
plt.figure(figsize=(10,5))
plt.plot(x,y,'o',label = 'Dados originais')
plt.legend()
plt.xlabel("x")
plt.ylabel("Y")
plt.grid()
plt.show()
'''
Iremos es... |
a8da3fac2412f97251d162babd4e4edf292547d4 | notlesz/IGTI-Python | /1 - Fundamentos Python/Aula13.py | 184 | 4.03125 | 4 | #Loop While
#Contando a quantidade de linhas de um arquivo com while
nome_do_arquivo= input("Digite o nome do arquivo: ")
arquivo = open(nome_do_arquivo)
nlinhas = 0
while arquivo !=
|
eecfbfdec4ccc9ac91345c8d61fdfaba2e80b671 | notlesz/IGTI-Python | /1 - Fundamentos Python/Aula18.py | 1,112 | 4.4375 | 4 | # Argumentos em python
'''
def concatena_nome_mensagem(nome,mensagem): #A função possui dois parametros
print("Olá,"+nome+"! "+mensagem)
a = input("Digite seu nome: ")
b = input("Digite seu nome: ")
concatena_nome_mensagem(a,"Bom dia")
concatena_nome_mensagem(b, "BOM DIA")
=========================================... |
cb86f947a90c0f38edffd53a90f66ed3be195c1d | notlesz/IGTI-Python | /1 - Fundamentos Python/Aula 6.py | 1,755 | 4.09375 | 4 | # if condicional or
#altura = int(input("Digite sua altura em centimetros: "))
#if (altura < 150) or (altura > 180):
# print('Voce nao pode brincar')
#else:
# print("Voce pode brincar!")
#Adivinhando resultado da divisao
#numerador = float(input("Digite o valor do numerador: "))
#denominador = float(input("Digit... |
fc22e0644a92e59bd862f8f72d0eb5b2246cb933 | ishwarc404/BreastCancerDetection_MachineLearning_fromScratch | /ANN/test_ann.py | 2,350 | 3.59375 | 4 | import numpy as np
import pandas as pd
# sigmoid function to normalize inputs
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# sigmoid derivatives to adjust synaptic weights
def sigmoid_derivative(x):
return x * (1 - x)
# # input dataset
# training_inputs = np.array([[0,0,1],
# [1,1,1... |
15b75f0ef7ffcd0d35927c4718ac32fa0baf8bd1 | AkshayaK04/7-Day-Coding-Challenge | /Program9.py | 217 | 4 | 4 | choice=int(input('Enter the choice: 1 for feet to centimetre and 2 for inches to centimetre'))
n=float(input('Enter the distance'))
if choice==1:
print(n/30.48)
elif choice==2:
print(n*2.54)
else:
print('Invalid') |
22e3d95f2aa0ee4177722f42f9bbbad9f7c88bbe | AkshayaK04/7-Day-Coding-Challenge | /Program58.py | 426 | 3.59375 | 4 | import sys
n=int(input('Enter the no. of elements in the list'))
A= []
for x in range(0,n):
i=int(input('Enter the element'))
A.append(i)
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_i... |
73b4f39abafdbcce0bee4fae6ba8b24b4872b143 | AkshayaK04/7-Day-Coding-Challenge | /Program43.py | 376 | 3.828125 | 4 | s=input('Enter the string')
print(len(s))
s1=input('Enter the string')
c=0
for x in s1:
c+=1
print(c)
s2=input('Enter the string')
counter = 0
while s2[counter:]:
counter+=1
print(counter)
str=input('Enter the string')
if not str:
print(0)
else:
some_random_str = 'py'
print((some_ra... |
74ce5d37e9976ebcf154cd8b2bcb5508c0212cba | AkshayaK04/7-Day-Coding-Challenge | /Program27.py | 56 | 3.5 | 4 | a=list(input('Enter the list'))
a=a[::-1]
print(a) |
1368a7a93eceb926e5bf65bd6507983e615f5bbe | AkshayaK04/7-Day-Coding-Challenge | /Program54.py | 469 | 4.15625 | 4 | def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
n=int(input('Enter the no. of elements in the list'))
arr = []
for x in range(0... |
61dba91b3b5bdb7c76e3b6366f0ad305b2c8713c | AkshayaK04/7-Day-Coding-Challenge | /Program46.py | 181 | 3.828125 | 4 | import re
a= input('Enter the string')
b= input('Enter the string')
c = 0
for i in a:
if re.search(i,b):
c=c+1
print("No. of matching characters are ", c) |
3d22c4f3d34b6f24c886a9f6bf8f9d7bd717374c | AkshayaK04/7-Day-Coding-Challenge | /Program41.py | 108 | 3.609375 | 4 | s=input('Enter the string')
i=int(input('Enter the value of i'))
s1=s[0:i]
s2=s[i+1:len(s)]
print(s1+s2) |
ae1683dbe910899cf2ecd33a29d1f0dbb8823de6 | AkshayaK04/7-Day-Coding-Challenge | /Program63.py | 105 | 3.671875 | 4 | l=list(input('Enter the list'))
sum=0
for x in range(0,len(l)):
sum+=int(l[x])
print(sum)
|
ce7e9f1dc032fd20b596836ba6f75c0150f214c9 | utep-cs-systems-courses/video-player-johnmdelgado | /my_video_player/functions/custom_queue.py | 1,185 | 3.53125 | 4 | #!/usr/bin/env python3
"""
FileName: custom_queue.py
Author: John Delgado
Created Date: 5/4/2021
Version: 1.0 Initial Development
This is our custom queue using semaphores!!
Also, May the 4th be with you.
"""
from threading import *
class CustomQueue:
def __init__(self):
self.buff = list()
#... |
6ceb6edd18102950855e6929e271f00f201acf39 | fedcalderon/MathFacts | /src/application/models/question.py | 2,092 | 3.890625 | 4 | """A class that stores a single question and the user's response."""
# Andrew
class Question:
"""Pass either a dictionary or the individual variables, not both."""
def __init__(self, question_dict=None, question_type=None, first_num=None, second_num=None, symbol=None,
correct_ans=None, studen... |
73129597d62bc69c965339e72a2f2eb6d56b0d86 | ccsourcecode/Blockchain_Survival_Guide | /XOR.py | 1,450 | 3.625 | 4 | import random
def string_to_bytes(input):
input = bytearray(input, 'utf-8')
result = ""
for byte in input:
for i in range(7, -1, -1):
result += str((byte >> i) & 1)
return result
def bytes_to_string(input):
result = ""
for idx in range(0, int(len(input)/8)):
binary ... |
2fdc296fa9ef05e76ce60ac9ffb25289579eac58 | prajwaltelkar/GPIO_interfacing_RPi | /gpio with infinte loop.py | 1,123 | 3.875 | 4 | import RPi.GPIO as GPIO # importing GPIO library
import time # importing time library for delay
GPIO.setmode(GPIO.BOARD) # enable BOARD pin numberings
GPIO.setup(11,GPIO.OUT) # Set pin 11 as output
while True:
GPIO.output(11,1) # Send Output 5V to pin 11
time.sleep(1)... |
604851feaf9d25494e2f6567b9e7fe9db6b6682e | Abhijeet-ni/DS-Algo-practice | /QuickSort_Impl/quick_sort_impl.py | 322 | 3.625 | 4 | #quick sort using hoare partition
def swap(a,b,arr):
if a!=b:
temp = arr[b]
arr[b]=arr[a]
arr[a]=temp
def partision(element):
privot = element[0]
def quick_sort(element):
pi = partision(element)
if __name__=='__main__':
elements = [11,9,29,7,2,15,28]
quick_sort(element... |
8ce589f15832df26f4aab265616ed8c3b2992a5f | jorgetoledo23/PythonSeccionP12C1 | /ejercicio1eva3.py | 426 | 3.96875 | 4 | #Dados dos números enteros, devuelva su producto. Si el producto es mayor que 1000, devuelva su suma
num1 = int(input("Ingrese Numero 1: "))
num2 = int(input("Ingrese Numero 2: "))
producto = num1 * num2
if producto > 1000:
print(num1 + num2)
else:
print(producto)
def multipicacion_o_suma(num1, num2):
pr... |
7087181f3085ce803844ba369b67144996539c4b | jorgetoledo23/PythonSeccionP12C1 | /ejercicio6eva3.py | 330 | 3.65625 | 4 | #Calcule el impuesto sobre la renta para los ingresos dados siguiendo las siguientes reglas
renta = int(input("Ingrese Renta para calular: "))
impuesto = 0
if renta <= 500000:
impuesto = 0
elif renta >= 500000 and renta <= 1000000:
impuesto = renta * 0.05
elif renta > 1000000:
impuesto = renta * 0.07
print... |
329c181bcaace158b202afa6546a77883029c062 | jorgetoledo23/PythonSeccionP12C1 | /ejercicio1.py | 492 | 3.8125 | 4 | #Determinar si un alumno aprueba a reprueba un curso,
# sabiendo que aprobara si su promedio de tres calificaciones es mayor o igual a 4.0;
# reprueba en caso contrario.
contador = 1
nota = 0
suma = 0
while contador <=3:
print("Ingrese Nota N", contador)
nota = float(input())
suma = suma + nota
conta... |
778de4bfdf16194a8bb0006b2d1433c293a4fdfa | MahmoudSelmy/DepthEstimationVGG | /HelperAPI.py | 4,048 | 3.875 | 4 | import tensorflow as tf
# TODO : add layer and parameters name parameter
def weights_init(shape,layer_name,trainable = True):
'''
This function is used when weights are initialized.
Input: shape - list of int numbers which are representing dimensions of our weights.
'''
return tf.Variable(tf.trunca... |
fc7b5ef0c9d122f5816958362fc69f72d790c17e | meny87/PythonBegginerCourse | /Ex19_Conditionals.py | 905 | 4.59375 | 5 | # Create a program to calculate the BMI (Body mass index) of a person.
# Ask the user for his height in meters and his weight in kg.
# Print BMI in the classification:
# - Underweight: Less or equal to 18.5
# - Normal Weight: Greater than 18.5 or less than or equal to 24.9
# - Overweight: Greater than 24.9 ... |
66df343a0aa001358a8dd8a365e3346ed16042e6 | mayak19-meet/YL1-201718 | /Lab5/Lab5.py | 854 | 3.8125 | 4 | from turtle import Turtle,colormode
import random
class Square(Turtle):
def __init__(self, size):
Turtle.__init__(self)
self.size = size
self.shape=shape
def random_color(self):
r=self.random.randint(0,256)
g=self.random.randint(0,256)
b=self.random.randint(0,256)
self.color(r,g,b)
Square1=Square(30... |
daf9209f73ba9105d06aa14461cb176adb05bd24 | skatenerd/tic_tac_toe | /player.py | 342 | 3.5 | 4 | import playerinput
class Player(object):
PLAYERS_DICT = {'x':'o','o':'x'}
def __init__(self,token,input_method=playerinput.PlayerInput()):
self.token = token
self.opponent_token = (self.PLAYERS_DICT[token])
self.input_method = input_method
def next_move(self):
return self... |
8c39c3f408fe50fa37e0fbb78bfe18895d569556 | yaoyc/learning-python | /lianxi_1X2X3X...N.py | 151 | 3.546875 | 4 | def func(n):
sum = 1
for x in range(1,n+1):
sum = sum * x
return sum
########## 求 n! 也就是 1*2 * 3 * 4.. *n 这个式子的值##########
|
5be13705e85d1413919160806e26392ece82f46b | IvanBrasilico/prova_turing | /1_logica/q2b.py | 1,320 | 3.578125 | 4 | from collections import deque
class EstacionamentoQB:
def __init__(self, k=0, n=0):
if k < 1 or k > 10_000:
raise ValueError('Tamanho deve ser entre 1 e 10.000')
if n < 1 or n > 10_000:
raise ValueError('Número de carros deve ser entre 1 e 10.000')
self.tamanho_rua ... |
40205bfd6888e595f23822b2ea21c95d90778b5f | johebuck/Algorithms-Analysis | /Algorithms & Analysis/sort/Program1/insertion/insertion_sort_ordered.py | 511 | 4.1875 | 4 | #NAME: John Buckley
#DATE: 9/17/17
#PROGRAM: Programming assignment 1: ordered input
#PURPOSE: Uses insertion sort to take a list of integers and sort them in increasing order
def insertionSort(alist):
for i in range(1,len(alist)):
k = alist[i]
j = i
while j>0 and alist[j-1]>k:
... |
536621ec50f062b62a99f1afe27f51b32ff15fd2 | EruDev/Python-Practice | /菜鸟教程100例/68.py | 256 | 3.859375 | 4 | # 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
li = [1, 2, 3, 4, 5, 6] # 测试列表
m = 3 # 设置向后移动3位
for _ in range(m):
li.insert(0, li.pop())
print(li) |
62e29f566412e40020fbe444fb2ab6723e57195c | EruDev/Python-Practice | /菜鸟教程Python3实例/20.py | 262 | 3.625 | 4 | # Python 十进制转二进制、八进制、十六进制
num = int(input('请输入一个数字:'))
print('十进制数为:', num)
print('转换为二进制为:', bin(num))
print('转换为八进制为:', oct(num))
print('转换为十六进制为:', hex(num)) |
3c050860ba0295d12ba25281e8f4ba1f6792891e | EruDev/Python-Practice | /菜鸟教程100例/01.py | 401 | 3.578125 | 4 | # 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
# 一开始没看清题目的意思,其实只要打印出所有的三位数,然后去掉个位、十位、百位上有重复的数,就好了
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if (i != j) and (i != k) and (j != k):
print(i, j ,k) |
43ff7778d22509b8e680be6ac266d2b66b52b710 | EruDev/Python-Practice | /第1章/1-2.py | 361 | 3.546875 | 4 | # 如何为元组中的每个元素命名,提高可读性一
# ('Zhangsan', 15, 'male', 'zhangsan@qq.com')
# ('Lisi', 18, 'male', 'lisi@gmail.com')
# ('Wangwu', 12, 'female', 'wangwu@163.com')
NAME, AGE, SEX, EMAIL = range(4)
student = ('Zhangsan', 15, 'male', 'zhangsan@qq.com')
# name
print(student[NAME])
# age
if student[AGE] > 10:
pass
# sex
if stu... |
9a9602e345ae68e11f18ec4bcf1650c8d05d26c2 | EruDev/Python-Practice | /第2章/2-5.py | 1,994 | 4 | 4 |
# 如何在一个for语句中迭代多个可迭代对象?
"""
案例子:
1. 某班学生期末考试成绩,语文,数学,英语分别存储在3个列表中,
同时迭代三个列表,计算每个学生的总分(并行)
2. 某年级有4个班,某次考试没办英语成绩分别存储在4个列表中,
依次迭代每个列表,统计全学年成绩高于90分人数(串行)
解决方案:
1.并行--使用内置函数zip,它能将多个可迭代对象合并,每次迭代返回一个元组
2.串行--使用标准库itertools.chain,它能将多个可迭代对象连接
"""
"""
1. 先随机生成语文、数学、英语这个三个列表。
然后利用zip函数,将每个学生的三门成绩加起来,存在一个列表中
打印列表
In [2]: ch... |
0d4fb6c1b1b789581bc8a31daea2c575b47e196d | EruDev/Python-Practice | /菜鸟教程100例/31.py | 454 | 4.125 | 4 | # 题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
weekDict = {'M':'Monday', 'T':{'u': 'Tuesday', 'h':'Thursday'}, 'W':'Wednesday', 'F':'Friday',
'S':{'a':'Saturday', 'u':'Sunday'}}
day = input('输入第一个字母:')
day = day.upper()
if day in ['T', 'S']:
day2 = input('输入第二个字母:')
print(weekDict[day][day2])
else:
print(week... |
5d720cbf5b71dec9395c0358ba719528900aa658 | EruDev/Python-Practice | /菜鸟教程100例/32.py | 118 | 3.609375 | 4 | # 题目:按相反的顺序输出列表的值。
L = [1, 2 ,3 ,4 ,5]
print(L)
print('相反顺序输出:', L[::-1]) |
719b7527d887d74e89d965307c29bfe24030bdb1 | EruDev/Python-Practice | /菜鸟教程100例/34.py | 185 | 3.53125 | 4 | # 题目:练习函数调用。
def hello_world():
print('hello world')
def three_hello_world():
for i in range(3):
hello_world()
if __name__ == '__main__':
three_hello_world() |
29d083a83c300a0e883de97757a3904e71f8df79 | EruDev/Python-Practice | /菜鸟教程100例/57.py | 227 | 3.875 | 4 | # 题目:画图,学用line画直线。
import turtle
def drawLine(n):
t = turtle.Pen()
t.color(0.3, 0.8, 0.6) # 设置颜色
t.begin_fill()
for i in range(n):
t.forward(50)
t.left(360/n)
t.end_fill()
drawLine(4) |
7c907b1a6e594695805d8969c911c6c959bfccad | EruDev/Python-Practice | /第2章/2-2.py | 904 | 4.28125 | 4 | # 如何使用生成器函数实现可迭代对象?
"""
案例:实现一个可迭代对象的类,它能迭代出给定范围内的所有素数
pn=PrimeNumbers(1,30)
for n in pn:
print(n)
输出结果:2 3 5 7 11 13 17 19 23 29
解决方法:将该类的__iter__方法实现生成器函数,每次yield返回一个素数
"""
# def f():
# print('in f() 1')
# yield 1
# print('in f() 2')
# yield 2
# print('in f() 3')
# yield 3
# g = f()
# print(next(g))
# pr... |
1b5e3d3ffbc400e9c32be679372ba6f9f27b59d1 | EruDev/Python-Practice | /第1章/1-7.py | 1,195 | 4 | 4 | # 如何根据字典中值的大小,对字典中的项排序
# 案列:某班英语成绩以字典形式存储为:{'lucy':88,'bob':66...},根据成绩高低,计算学生排名
"""
方法:使用内置的sorted()函数
1. 利用zip()将字典转换成元组
2. 传递sorted函数的key参数
"""
"""
1. 先生成一个有6个学生,分数随机的字典
2. 通过zip函数,把字典的values和keys组合成一个元组,然后通过sorted函数排序
3. 利用sorted函数中的key参数
In [1]: from random import randint
In [2]: student = {x:randint(0,100... |
37fce2b911cc3af8534e4c9e19558e45d412739d | seanps8/python-fun | /dice-rolling.py | 209 | 3.796875 | 4 | #!/usr/bin/python
from random import randint
def main():
min = 1
max = 6
num1 = randint(min, max)
num2 = randint(min, max)
print randint(num1 + num2)
if __name__ == '__main__':
main() |
2bf8e55c99f13cdcf27ac4215fb5088f79c1620c | AlexVernon/6.00.1x | /probSet1Prob3.py | 449 | 4.375 | 4 | # Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which
# the letters occur in alphabetical order. For example,
# if s = 'azcbobobegghakl', then your program should print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the fi... |
81174e640f01b55f5875df27b829933fc6aef748 | MatheusFBBueno/vetores | /1165.py | 278 | 3.5 | 4 | d = 0
c = int(input())
for o in range(0,c):
x = int(input())
if x == 1 or x == 2:
print("%d eh primo"% x)
else:
for a in range(2,x):
if x % a == 0:
d += 1
if d > 0:
print("%d nao eh primo"% x)
d = 0
else:
print("%d eh primo"%x)
d = 0 |
ecf52a0ffda4bdb2efd0f7949e0b19f8252320d0 | agalyaramesh/Python | /file2.py | 213 | 3.6875 | 4 | import random
n=random.choice(range(10))
for i in range(5):
c=int(input('guess a number:'))
if c==n:
print('win')
exit(0)
else:
print('try again')
print('lost')
|
e4f1d2331e033e857a3261af851e8d5faae99d0d | maldata/mstManager | /mstmanager/dialogs/episodeentry.py | 2,546 | 3.6875 | 4 | from collections import namedtuple
EpisodeEntryResult = namedtuple('EpisodeEntryResult',
'canceled, episode_number, title')
class EpisodeEntryController:
def __init__(self):
self.view = EpisodeEntryView()
def get_episode_info(self):
result = self.view.show()
... |
ad897d7db740b4a064eb97f7865b4e8ee84b249c | omarXzain/data-structures-and-algorithms-401 | /tests/data_structure/test_repeated_word.py | 1,457 | 4.125 | 4 | from data_structures_and_algorithms.challenges.repeated_word.repeated_word import repeat_word
def test_repeat_word1():
test = 'Once upon a time, there was a brave princess who'
actual = repeat_word(test)
expected = 'a'
assert actual == expected
def test_repeat_word2():
test = "THE WEATHER IS VERY... |
105b0f9468020a00d87767bda45a4faa86a73f81 | Min-Guo/CracklePop | /CracklePop.py | 554 | 4.25 | 4 | # Code CracklePop
# Min Guo
# May 22, 2014
# Write a program that prints out the numbers 1 to 100 (inclusive). If the number is divisible by 3, print Crackle instead of the number. If it is divisible by 5, print Pop. if it is divisible by both 3 and 5, print CracklePop.
def cracklePopOneHundred():
for num in range(1... |
1edf19012918de7f03d5f2a00536cf94502cfbaa | atharv4git/pyLearn | /ch4/02_list_slicing.py | 140 | 3.578125 | 4 | # list slicing
friends = ["kalash" , "saransh" , "vishvesh" , "alan" , 45]
print(friends)
print(friends[0:4]) # similar to string slicing |
922aaa1ffec543edb1c84ec647d0377c847165b7 | atharv4git/pyLearn | /ch5/06_pr_02.py | 354 | 3.921875 | 4 | n1 = int(input("Enter no. 1:\n"))
n2 = int(input("Enter no. 2:\n"))
n3 = int(input("Enter no. 3:\n"))
n4 = int(input("Enter no. 4:\n"))
n5 = int(input("Enter no. 5:\n"))
n6 = int(input("Enter no. 6:\n"))
n7 = int(input("Enter no. 7:\n"))
n8 = int(input("Enter no. 8:\n"))
# will display unique numbers
s = {n1... |
5a948c08aaa78e2eddf206347b216a538dad8751 | rahil1303/Queues_Using_Python | /1_Create_a_Queue.py | 249 | 3.9375 | 4 | class Queue:
### Create a Queue
def __init__(self):
self.lists = []
def __str__(self):
values = [str(x) for x in self.lists]
return " ".join(values)
# TIME COMPLEXITY = O(1)
# SPACE COMPLEXITY = O(1)
|
d04d3f1d9f659d18d28645a5b22cc2834aad9497 | soucevi1/ecdlp-babystep-giantstep | /helper_tools.py | 1,022 | 3.59375 | 4 |
# Module with other needed tools for ECDLP.
# Author: Vit Soucek
class BabyStepPoint:
"""
Helper class to store generated
babysteps in a sorted list and
keep their indexes after sorting.
"""
def __init__(self, point, index):
self.point = point
self.index = index
def __lt... |
b92cd472a02a80934cdfe6fe0c0e1dcf3a879973 | krestko/pythonTutorial | /functions.py | 221 | 3.84375 | 4 | import sys
def addNumber(fnum, lnum) :
sumNum = fnum + lnum
return sumNum
print(addNumber(1, 3))
#python version of ruby gets.chomp, saving user input
print('Hello')
user_response = input()
print(user_response) |
e5a1d205990a62509fcd89fe3ddb0f362dfd3c4e | rafaeltadeu01/devops | /cursos/cursoemvideo/Python/Aula4/desafio-015.py | 390 | 3.84375 | 4 | ## Calculadora de valor da locação de um carro
dias = int(input('Quantos dias ficou alugado?: '))
km = float(input('Quantos KM foi rodados?: '))
pago1 = dias * 60
pago2 = km * 0.15
print('O total a pagar de dias é de: R$ {:.2f}'.format(pago1))
print('O total a pagar de km é de: R$ {:.2f}'.format(pago2))
print('-' * 50)... |
93ae09aa67589a4ce6643f4adcd3ff4af25cac22 | rafaeltadeu01/devops | /cursos/cursoemvideo/Python/Aula4/desafio-002.py | 237 | 4 | 4 | ## Imprime uma data informada
dia = input('Qual foi o dia que você nasceu?')
mes = input('Qual foi o mês que você nasceu?')
ano = input('Qual foi o ano que você nasceu?')
print('Você nasceu no dia',dia, 'de',mes,'de',ano,'Correto?') |
84b04a43a507627b1c4f6a7c3f28010e2ee8e673 | rohitdha/Inference-First-Order-Logic | /inference.py | 10,731 | 3.65625 | 4 | """
Author: Rohit Dhawan
Algorithm: Backward Chaining
Domain: Artificial Intelligence
Sample Input Format:
2 // 2 Queries
H(Bob)
F(Hello)
3 // 3 Entries in the KB: Knowledge base
R(x) => H(x)
R(Tom)
F(Hi)
Sample Output Format:
TRUE
FALSE
Statement:
R(x) => H(... |
e1926601bd4bb672661d66689e829263dfab818d | bdebelle/learnpython | /ex38.py | 1,407 | 3.953125 | 4 | # Doing things to lists
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print "Wait there's not 10 things in that list, let's fix that."
# Variable equal to ten_things with list items split by a space.
# ['Apples', 'Oranges', 'Crows', 'Telephone', 'light', 'sugar']
stuff = ten_things.split(' ') # split(ten_... |
80205fea8a4639f54e1dbf25f6c21082ec668df4 | bdebelle/learnpython | /ex07.py | 863 | 3.953125 | 4 | print "Mary had a little lamb." # print string
print "its fleece was white as %s." % 'snow' # print string with string formater
print "And everywhere that Mary went." #print string
print "." * 10 # printed string consecutively 10 times
end1 = "C" # Variable
end2 = "h" # Variable
end3 = "e" # Variable
end4 = "e" # Var... |
86469438340b16f8abffc2a718031823f22c6a2b | bdebelle/learnpython | /ex34.py | 188 | 4 | 4 | letters = ['Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
for i in letters:
print i
print letters
for i in range(len(letters)):
print "Index %d in the list is %s" % (i, letters[i]) |
2c4fd552b8d8f8a3f51fe594f95e84b9a3796c5f | bdebelle/learnpython | /ex15.py | 716 | 3.953125 | 4 | # Imports the arguement variable module from system
from sys import argv
# set are argument variables
script, filename = argv
# variable txt set to open variable filename
txt = open(filename)
# print string with Repr File name
print "Here's your file %r:" % filename
#Prints the contents of TXT which is set to open vari... |
db2064ad6118f703fec71e78174b909c2521f5ab | A159951123/MIDTERN | /9.py | 132 | 3.84375 | 4 | s1 = input("輸入 s1 為:")
s2 = input("輸入 s2 為:")
if len(s2.replace(s1,""))!=len(s2):
print("YES")
else:
print("NO") |
927983ea39a2c81e1b96dbbe621f9aedefc8ae94 | A159951123/MIDTERN | /3.py | 168 | 3.578125 | 4 | animal=["rat","ox","tiger","rabbit","dragon","snake","horse","sheep","monkey","rooster","dog","pig"]
Year = int(input("請輸入年份"))
print(animal[(Year + 8) % 12]) |
6158c9b8fcec116f8f1ba37db7cccaa78458a630 | ConnorMcCon/Projects | /Rock, Paper, Sissors.py | 1,055 | 4.03125 | 4 | #Rock, Paper, Sissors
import random
gamelist = ["Rock","Paper","Sissors"]
while True:
computer = random.choice(gamelist)
user = input("Type Rock, Paper, or Sissors - ")
if user == "Rock" and computer == "Sissors":
print("You Win")
if user == "Paper" and computer == "Rock":
... |
a761a3c455b072c4d361db52e6d0e9ec775d2310 | nram19/IntrotoComputing | /HW #5.py | 1,525 | 4.03125 | 4 | #Question 1
class Clock():
def __init__(self, time):
self.time = time
def print_time(self):
time = ' 6:30'
print(self.time)
clock = Clock(' 5:30')
clock.print_time()
#Question 2
class Clock():
def __init__(self, time):
self.time = time
def print_time(self, time):
... |
52154198cb17dcf87d156d1444c75f7a3ea2d738 | yorae39/IA-COTI-Python | /pandas2.py | 756 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 9 18:39:01 2019
@author: Aluno 09
"""
import pandas as pd
import numpy as np
df = pd.DataFrame([
["PE", "Pernambuco", "Recife"],
["RJ", "Rio de Janeiro", "Rio de Janeiro"],
["PB", "Paraiba", "João Pessoa"],
... |
e98fe60843ae39bcf33604e59ac58bcbba93d499 | AZ-OO/Python_Tutorial_3rd_Edition | /4章 制御構造ツール/4.7.5.py | 394 | 3.75 | 4 | """
4.7.5 Lambda(ラムダ)式
"""
# キーワード lambdaを使うと小さな無名関数が書ける。
def make_incremenor(n):
return lambda x: x + n
f = make_incremenor(42)
print(f)
f(0)
f(1)
# 用途としては、小さな関数を引数として渡すことができる
pairs = [(1,'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair:pair[1])
print(pairs)
|
8aaefd67e2955f6bf583442eff4605252e89573f | AZ-OO/Python_Tutorial_3rd_Edition | /9章 クラス/9.6.py | 602 | 3.625 | 4 | """
9.6 プライベート変数
"""
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append((item))
__update = update # 上のupdte()メソッドのプライベートコピー
class mappingSubclass(Mapping):
... |
7a597927c4221f0b1b7350fa66cd3b57549b5138 | AZ-OO/Python_Tutorial_3rd_Edition | /4章 制御構造ツール/4.3.py | 970 | 4.375 | 4 | """
4.3 range()関数
"""
# 数字なの連なる反復をかけるときは、range()関数が便利
# 与えられた終端値は入らない
# これは、等差級数を生成する
for i in range(5):
print(i)
# range()が生成する値は、各アイテムのインデックスとなる
# 0以外の数字から始めることもできるし、増分(ステップとも呼ばれる)を指定することも可能
# ステップは負数も使える
for i in range(5,10):# 5から10まで
print(i)
for i in range(0,10,3): # 0から10までで、3ずつインクリ
print(i)
for i... |
dc0e66450becfe62197d5341654d5bba7c1f3c33 | AZ-OO/Python_Tutorial_3rd_Edition | /4章 制御構造ツール/4.4.py | 819 | 3.984375 | 4 | """
4.4 break文とontinue文、ループにおけるelse節
"""
# break文は、forまたはwhileのループを抜けるモノ
# ループ文にはelse節が加えられる
# else節はリストを使い果たしたり(for)、条件式がfalesになること(while)によって
# ループが終了したバアアイに実行され、
# break文で終了した場合には実行されない
# 素数検索ループ
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
... |
d78cb28bbc84535787e73d5d464393e3b4125c77 | AZ-OO/Python_Tutorial_3rd_Edition | /4章 制御構造ツール/4.7.2.py | 2,424 | 3.796875 | 4 | """
4.7.2 キーワード引数
"""
# 関数はキーワード引数もとれる
# 『キーワード = 値』のかたち
def parrot(voltage, state = 'a stiff', action = 'voom', type = 'Norwegian Blue'):
print("This parrot wouldn't", action, end = '')
print("if you put", voltage, "volts through it.")
print(" -- Lovery plumage, the", type)
print(" -- It's", state, "!... |
424c0ca3b3ba80cd6aab1f7cbdb68f12205d2a2f | prompt-toolkit/python-prompt-toolkit | /examples/prompts/rprompt.py | 1,524 | 3.953125 | 4 | #!/usr/bin/env python
"""
Example of a right prompt. This is an additional prompt that is displayed on
the right side of the terminal. It will be hidden automatically when the input
is long enough to cover the right side of the terminal.
This is similar to RPROMPT is Zsh.
"""
from prompt_toolkit import prompt
from pro... |
3359205be80c1d686052a9b2e53578d7d17ac495 | prompt-toolkit/python-prompt-toolkit | /examples/prompts/custom-key-binding.py | 2,255 | 4.03125 | 4 | #!/usr/bin/env python
"""
Example of adding a custom key binding to a prompt.
"""
import asyncio
from prompt_toolkit import prompt
from prompt_toolkit.application import in_terminal, run_in_terminal
from prompt_toolkit.key_binding import KeyBindings
def main():
# We start with a `KeyBindings` of default key bind... |
2c3d1b9ea8d9fb717996369b1369749a1705ff23 | prompt-toolkit/python-prompt-toolkit | /examples/print-text/html.py | 1,367 | 4.15625 | 4 | #!/usr/bin/env python
"""
Demonstration of how to print using the HTML class.
"""
from prompt_toolkit import HTML, print_formatted_text
print = print_formatted_text
def title(text):
print(HTML("\n<u><b>{}</b></u>").format(text))
def main():
title("Special formatting")
print(HTML(" <b>Bold</b>"))
... |
f42e60b3fd47d75c3ab9a7db4daf49c9beadaf49 | prompt-toolkit/python-prompt-toolkit | /examples/prompts/multiline-prompt.py | 290 | 3.71875 | 4 | #!/usr/bin/env python
"""
Demonstration of how the input can be indented.
"""
from prompt_toolkit import prompt
if __name__ == "__main__":
answer = prompt(
"Give me some input: (ESCAPE followed by ENTER to accept)\n > ", multiline=True
)
print("You said: %s" % answer)
|
f27b849a716f5578c32a48678078eb1b6b2a7395 | prompt-toolkit/python-prompt-toolkit | /examples/telnet/toolbar.py | 1,117 | 3.5 | 4 | #!/usr/bin/env python
"""
Example of a telnet application that displays a bottom toolbar and completions
in the prompt.
"""
import logging
from asyncio import Future, run
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.shortcuts impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.