blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
cec6fafd666635de71fc1c2a2d188f297c8b514b | Khalid-Sultan/Section-2 | /to binary.py | 273 | 4.1875 | 4 | def main():
value=eval(input("Enter an integer:"))
print("The binary value is",decimalToBinary(value))
def decimalToBinary(value):
result=""
while value!=0:
bit=value%2
result=str(bit)+result
value=value//2
return result
main()
|
565db48c15f068ec0f1a31949066e02ca3536c36 | KrisDalmIWT/Python_Test | /ex02.py | 283 | 4.03125 | 4 | #!/usr/bin/env python
def sumNum(num):
previousNum = 0
for i in range(num):
sum = previousNum + i
print("Current Number: ", i, "Previous Number: ", previousNum, "Sum: ", sum)
previousNum = i
print("Printing current and previous number sum in a given range (10)")
sumNum(10) |
19554ee421e2f148c867c20c548f95b79aa3fa9a | Tamabcxyz/Python | /th1/oop.py | 282 | 3.640625 | 4 | class Parrot:
def __init__(self,name,age):
self.name=name
self.age=age
def sing(self,sing="o o o..."):
return "{} sing {}".format(self.name,sing)
a=Parrot("pig",23)
b=Parrot("cow",34)
print(a.name)
print(a.age)
print(a.sing('a b c'))
print(b.sing())
|
61af3f82b452f1e0402cafc2a5797e3ffbb399be | Tamabcxyz/Python | /th2/dictionariescollectioninpython.py | 371 | 4.15625 | 4 | #A dictionary is a collection unordered can changeable, index. In python dictionary are written with curly brackets
#the have keys and values
a={"name":"Tran Minh Tam", "age":22}
print(a)
for x in a.values():
print(x)
for x in a.keys():
print(x)
for x,y in a.items():
print(f"a have key {x} values is {y}")
#... |
2519cac969dbd311788610823b0e8c17794ac5b0 | Tamabcxyz/Python | /th1/testmymind.py | 178 | 3.75 | 4 | # test my mind I don't know it's true or false
a=input("nhap so")
if int(a)>1:
print(a);
a=int(a)+1
print("day la a sau if ",a)
else:
print("day la a sau if ",a)
|
dd3749579badf2d94ec3b70bc8fbca4df495a6af | Tamabcxyz/Python | /th1/use_decimal_library.py | 247 | 3.5 | 4 | #import decimal
from decimal import Decimal as d
print(d(0.1))
print(d(2.2)+d(1.1))
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(1,5))
a=fractions.Fraction(1.1)
print(type(a))
b=fractions.Fraction('1.1')
print(type(b))
|
62328df1033c5d2d6026badb893d455db226569b | fuzzygwalchmei/FuzzleFolio | /mysite/templates/DiceRollerRegex.py | 908 | 3.578125 | 4 | import re
import random
diceRegex = "[\d]d[\d]"
modRegex = r'[+-]\s?\d\b'
def getItems(diceInput):
diceInput=diceInput.lower()
diceInput=diceInput.replace(" ","")
myDice = re.findall(diceRegex,diceInput)
myMods = re.findall(modRegex,diceInput)
rolls= []
mods=[]
for eac... |
11ac72a9cc2fc69ee01cdfe3976faf90b920cfdd | ccdale/python-from-scratch | /hublogs/hublogs/ccanumbers.py | 2,072 | 4.03125 | 4 | """Number routines"""
import sys
def makeSizeStr(size, human=True):
"""
function to return the file size in either bytes
or human readable form.
set in a field width of 12 chars
"""
try:
if human:
szstr = humanReadableSize(size)
else:
szstr = str(size)
... |
89e94f7ffcaffe9acc31e262c19c9c6a8539d9e6 | ccdale/python-from-scratch | /oop/oop/hangman.py | 6,296 | 4 | 4 | """Hangman game class
This class needs to be able to:
done - ask the user for a letter
done - check that the input is a valid letter
done - test if the input is actually a phrase or a letter
done - allow the user to guess the phrase
done - convert the phrase to a hidden string composed of "_ " per ... |
9ec46ef73554eed0ee073677f952c9fea335d1ef | ccdale/python-from-scratch | /countdown/07/countdown.py | 3,146 | 4.125 | 4 | #!/usr/bin/env python3
"""Application to play the Coundown letters game."""
import random
import sys
from anagrams import testWord
from buildwordlist import onlyInWords
from buildwordlist import readWordList
from buildwordlist import sortWordsByLetter
def rndLetter(vowel=False):
letters = [chr(x) for x in range... |
d5438545ead5bb2d41c7791b6e86c72c4f93aa66 | LuannaLeonel/data-structures | /src/python/InsertionSort.py | 314 | 4.125 | 4 | def insertionSort(value):
for i in range(len(value)):
j = i
while (j > 0 and value[j] <= value[j-1]):
value[j], value[j-1] = value[j-1], value[j]
j -= 1
return value
a = [1,3,7,9,5]
b = [5,5,7,3,0,2,1,52,10,6,37]
print insertionSort(a)
print insertionSort(b)
|
b7d936616016e8403aa7a68caa195b9f04492dad | bezelie/bflitz | /study_argv.py | 334 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Learning Code : 引数の取得のしかた
#
import sys
from time import sleep
print ("argv="+str(sys.argv))
print ("argv[0]="+str(sys.argv[0]))
num = len(sys.argv)
print (num)
if num > 1:
print ("argv[1]="+str(sys.argv[1]))
if str(sys.argv[1])=="roll":
print ("rolling")
|
197fb6b7d7b4db1ccde7078e85475f80d9c604d9 | arpith143a/best-practices | /interview_easy/interview3.2.py | 204 | 4.125 | 4 | m=int(input('Enter number:'))
if m<=0:
print('Enter number greater than zero')
for i in range(1,m+1):
for k in range(i,m):
print(' ',end='')
for j in range(1,i+1):
print('*',end='')
print('')
|
b6f75a3551a01f65ed19883669c2d5898d802cd6 | Lexanus686/myVecCloned | /vec.py | 383 | 3.5625 | 4 | class Point:
def __init__(self, *args):
self.values = args
def __add__(self, other):
return self.values + other.values
def __sub__(self, other):
return (self.values - other.values)
Point c = Point(2,5)
class Vec:
def __init__(self, *args):
self.values = args
def ... |
121fe571622844666be38c63fd0cc4b8b56c9868 | MonicaHP/webAppExtra | /dataPelicula.py | 487 | 3.546875 | 4 | import json
class peliculas:
dataPeliculas = []
def readPeliculas(self):
with open('data/peliculas.json','r') as file:
dataPeliculas = json.load(file)
self.dataPeliculas = dataPeliculas['results']
def getPelicula(self):
peliculas = []
for row in... |
170311e8f5417e36f48731e59f0c72f18c40b5df | jacorse/advent_of_code_2019 | /day3.py | 1,598 | 3.53125 | 4 | # Advent of Code 2019
# Day 3 code
import numpy as np
def shortest_distance(filename):
fp = open(filename)
wires = fp.readlines()
# separate variables for both wires and split instructions
wire1_instructions = wires[0].split(",")
wire2_instructions = wires[1].split(",")
# wire1 = wire1.split(... |
2b9a519f487edca558d4307879828b811248216b | heloisethero/bicyle_technical_test | /sample/statistiques_descriptives.py | 12,965 | 3.546875 | 4 | """This script generates the different tables and figures of
the descriptive statistics part."""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def save_column_description(df, table_name, path):
"""Create the colmun summary table on slide 3"""
column_description = pd.concat([bike_df.m... |
f7250d967c81fd2550262cbb3bd4c4261e54b177 | ssmmchoi/OracleDatabase | /workspace/chap01_pandas/lecture02_handling/step01_DF_merge.py | 1,628 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
DataFrame 병합(merge)
ex) DF1(id) + DF2(id) -> DF3
"""
import pandas as pd
from pandas import Series, DataFrame
# 1. Series merge : 1 dimension
s1 = Series([1,3], index=['a', 'b'])
s2 = Series([5,6,7], index=['a', 'b', 'c'])
s3 = Series([11,13], index=['a', 'b'])
# 행단위 결합 : R의 rbingd()
s4 ... |
57022ff8f513c77ab1029cff3159449cc73d6308 | antonina111/AlgorithmsAndDataStructures | /BinarySearch.py | 830 | 3.953125 | 4 | def binary_search(arr, ele):
first = 0
last = len(arr)-1
found = False
while first <= last and not found:
mid = (first + last)//2
if arr[mid] == ele:
found = True
else:
if ele < arr [mid]:
last ... |
37679aa5f19d56a0cd004f0349fb566d902f9464 | nara-l/100pythonexcercises | /Ex66basic_translator.py | 299 | 4.125 | 4 |
def translator(word):
d = dict(weather="clima", earth="terra", rain="chuva")
try:
return d[word.lower()]
except KeyError:
return "We don't understand your choice."
word = input("Please enter a word to translate, weather, earth, rain etc. \n ")
print(translator(word))
|
cb14be47d394c9754c5626b1a18b4c040964e776 | nara-l/100pythonexcercises | /generate_list_intervals.py | 187 | 3.859375 | 4 | # using list comprehension
items = [item for item in range(10,201,10)]
my_range = range(1,21)
#print (items)
print ([10*item for item in my_range]) # mulitiply range of numbers by 10
|
9ca138f2879644a2c71a2874d0f0f30697f31fee | BenRapone/PyAlgs | /MergeSort.py | 411 | 3.734375 | 4 | def Merge(x,y):
nx = len(x)
ny = len(y)
i = 0
j = 0
bx = []
n = nx+ny
for k in range(n):
if nx - i == 0:
bx.append(y[j])
j += 1
elif ny - j ==0:
bx.append(x[i])
i += 1
elif x[i] <= y[j]:
bx.append(x[i])
i += 1
else:
bx.append(y[j])
j += 1
return bx
def MergeSort(x):
n = len(x)... |
4b2a68e7e0def4aca915ea288f1b5d2cbb667b8d | Abwas/TDD_assignment | /weather.py | 1,263 | 3.546875 | 4 |
filename = "port-harcourt-weather.txt"
def weatherReport():
with open(filename) as report: # open the problem file as report.
report.next() # skipping the first and second lines since they are not needed
report.next() # for our analysis.
dayList = []
dailyTempSpread = []
for line i... |
60b22a32db7631c1d14c1a1f457508eb79f6c922 | wuyujie1/CSC336-Numerical-Methods | /a3/a3q3.py | 10,779 | 3.84375 | 4 | #CSC 336 Summer 2020 A3Q3 starter code
#Please ask if you aren't sure what any part of the code does.
#We will do a similar example on the Week 10 worksheet.
#some general imports
import time
import datetime
import numpy as np
import scipy.linalg as LA
from scipy.optimize import fsolve
import matplotlib.pyplot as plt... |
73e7c66167779ac774c82daf18e1294b017c603e | WXLwkl/PythonRepository | /模块/Module.py | 2,164 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PythonRepository
# Created by xingl on 2017/10/31.
# Filename: Module 模块
__author__ = 'xingl'
# 使用模块
import sys
def test():
args = sys.argv
print(args)
if len(args) == 1:
print('Hello World')
elif len(args) == 2:
print('Hello %s!' %... |
7cf294c09e6baf9f098c77258362340d054915e9 | WXLwkl/PythonRepository | /函数式编程/返回函数.py | 5,417 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PythonRepository
# Created by xingl on 2017/10/31.
# Filename: 返回函数
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
# 现... |
471e5941da2a11e3331c5026b8b2ad6813033154 | yangze01/py_LeetCode | /Stack/Mystack.py | 1,106 | 3.96875 | 4 | #coding=utf8
class my_stack(object):
def __init__(self, value):
self.value = value
# 前驱
self.before = None
# 后继
self.behind = None
def __str__(self):
return str(self.value)
def top(stack):
if isinstance(stack, my_stack):
if stack.behind is not None:
... |
06d0df2988e01072be7e80ffe7036976ac7fba2a | voidnologo/Learning-Python | /constructor_critter.223.py | 298 | 3.765625 | 4 | # Constructor Critter
# demonstrates contructors
#pg 223
class Critter(object):
def __init__(self):
print('A new critter has been born.')
def talk(self):
print('\nI\'m an instance of class Critter.')
#main
crit1 = Critter()
crit2 = Critter()
crit1.talk()
crit2.talk()
|
51c143e6dcdbba01d039917f274c360ab243520d | voidnologo/Learning-Python | /gui/labeler.292.py | 225 | 3.546875 | 4 | #Labeler
# demonstrates a label
#pg 293
from tkinter import *
root = Tk()
root.title('Labeler')
root.geometry('200x50')
app = Frame(root)
app.grid()
label = Label(app, text='I am a label!')
label.grid()
root.mainloop()
|
356d9ed6e6cf379e2361819b30bc314e76956cf4 | voidnologo/Learning-Python | /playing_cards.252.py | 1,521 | 4.09375 | 4 | # Playing Cards
# Demonstrates combining objects
# pg 252
class Card(object):
RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K']
SUITS = ['c', 'd', 'h', 's']
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
return '{}{}'.... |
b8e5f07d5c112103ab864c330cb84ed5d69e8a8c | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio03_FOR/Fabio03_07_inteiro.py | 163 | 3.96875 | 4 | def main():
numero = int(input("Digite um número: "))
soma = 0
for i in range(1, numero+1):
soma += i
print(soma)
main() |
712b9351962de41d97ee6b170d71df8cfba15d05 | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio02a/Fabio02a_13_5números(maior_menor).py | 1,292 | 4 | 4 | def mair_menor():
n1 = float(input('Insira o primeiro número:'))
n2 = float(input('Insira o segundo número:'))
n3 = float(input('Insira o terceiro número:'))
n4 = float(input('Insira o quarto número:'))
n5 = float(input('Insira o quinto número:'))
if n1 > n2 and n1 > n3 and n1> n4 and n1... |
8e98946fb4e3705a5eaa89bdd9e61b5f2b98dc15 | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio03_Parte2/Fabio03_17_Sequencia1.py | 207 | 3.734375 | 4 | def main():
n = int(input("Defina n: "))
cont = 1
s = 0
while cont <= n:
print(f"1/{cont} + ", end=" ")
cont += 1
s += 1/cont
print(f"S = {s}")
main() |
4c54248a75fa6ebc582c785c968e44a4c3dc3189 | layusso/-ifpi-ads-algoritmos2020 | /Fabio_05/Fabio05_04.py | 498 | 4.09375 | 4 | def main():
a = []
b = []
n = int(input("Informe a quantidade de elemtentos em A: "))
nb = int(input("Informe a quantidade de elemtnos em B: "))
for i in range(n):
a_element = input("Digite elemento de A: ")
a.append(a_element)
for i in range(nb):
b_e... |
fc5e74b115270d6b31c71488fcab643657bc5ca8 | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio02a/Fabio02a_03_3maior_menor.py | 533 | 4 | 4 | def maior():
numero_1 = float(input('Insira o primeiro número:'))
numero_2 = float(input('Insira o terceiro número:'))
numero_3 = float(input('Insira o terceiro número:'))
if numero_1 > numero_2 and numero_3:
print('O maior é o primeiro número.')
elif numero_2 > numero_1 and numero_3... |
096f8f8da2425908550f151e4b82d7b143ee59a6 | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Turtle/bob.py | 1,005 | 3.71875 | 4 | import turtle
import math
bob = turtle.Turtle()
#Exercitando bob
def square(t, length):
for i in range(4):
t.fd(length)
t.lt(90)
turtle.mainloop()
print(t)
def polygon(t, n, lenght):
anglo = 360/n
polyline(t, n, lenght, anglo)
def circle(t, r):
arc(t, r, 360)
... |
ab22c03ed10e84e6572503a93f711ce3026986d6 | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio02b/Fabio02b_15_fruteira.py | 820 | 3.84375 | 4 | def main():
morango, maca = map(float, input('Quantidade em kg de maçã e morango que deseja:').split(' '))
strawberry = valor_morango(morango)
apple = valor_maca(maca)
total = strawberry + apple
kg_totais = morango + maca
if kg_totais > 8 or total > 25:
total_descontado = total-... |
2b124a0003535fc96ff8bf27f5e813fba7bea11a | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio02a/Fabio02a_24_coeficients(A,B,C).py | 488 | 3.6875 | 4 | def raizes():
a = float(input('Digite o valor de a:'))
b = float(input('Digite o vaor de b:'))
c = float(input('Digitie o valor de c:'))
delta = b**2 - 4*a*c
x1 = ((-b) + delta**(1/2)) / (2*a)
x2 = ((-b) - delta**(1/2)) / (2*a)
if a == 0 :
print('O valor de a precisa ser dife... |
02ac853780cfd85fdcaa1d2e80f8965480710b9b | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio03_FOR/Fabio03_16_Fibonacci.py | 318 | 3.671875 | 4 | def main():
qtd = int(input("Informe a quantidade de números: "))
anterior = 0
atual = 1
print(anterior, atual, end=" ")
for i in range(2, qtd+1):
novo_atual = anterior + atual
print(novo_atual, end=" ")
anterior = atual
atual = novo_atual
main() |
27c32b7d3cf5dd513b9974280e984ccfd635d23f | layusso/-ifpi-ads-algoritmos2020 | /Atividade_Fabio02a/Fabio02a_16_notas(aprovado_reprovado).py | 471 | 3.75 | 4 | def nota():
nota_1 = float(input('Insira a primeira nota:'))
nota_2 = float(input('Insira a segunda nota:'))
media = (nota_1 + nota_2) / 2
if media >= 7.0:
print('Aprovado!')
elif media < 7.0:
nota_final = float(input('Insira a nota do exame final:'))
media_final = ... |
606051d02841c7593bd564f2e9b1655eba1d7ada | kxhsing/data-structures-algorithms | /lists/dll_class_node.py | 2,927 | 3.859375 | 4 | class Node(object):
def __init__(self, data, next=None, previous=None):
self.data = data
self.next = next
self.previous = previous
def __repr__(self):
return "<Node {}>".format(self.data)
class DoublyLinkedList(object):
def __init__(self, head=None):
self.head = he... |
b16791277b3f04ad3f66f5dc49df33888c35360d | kxhsing/data-structures-algorithms | /lists/merge_sorted_ll.py | 525 | 4.09375 | 4 | def merge_sorted_ll(l1, l2):
"""Given two sorted linked lists, merge"""
# create dummy node with data of 0 to start
new_dummy_head = current = Node(0)
while l1 and l2:
if l1.data < l2.data:
current.next = l1
l1 = l1.next
else:
current.next = l2
... |
f2996c41e49dbcfe7f1fe95e5d8391fa6a0c408d | kxhsing/data-structures-algorithms | /sorting/bubble_sort.py | 510 | 3.984375 | 4 | def bubble_sort(lst):
"""For optimal, check if made any swaps, can also keep counter of how many
swaps were made"""
swaps_made = 0
for i in range(len(lst)):
made_swap = False
for j in range(len(lst)-1-i):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], ls... |
32c7644493b4cffcd342c71e394ba2564221f249 | b-junkoo/Sudoku | /Sudoku_GUI.py | 7,354 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 14:25:57 2020
pyggame GUI for Sudoku
@author: Jun
"""
import pygame, sys
from pygame.locals import *
from Sudoku_Generator import maker, format
pygame.font.init()
puzzle, solu = maker()
font = pygame.font.SysFont('comicsans', 60)
# Window Size - Wi... |
43dd5fb872255883905ff1748a99867cd3c7079a | Plaifa/python | /test2.py | 610 | 4.125 | 4 | from datetime import datetime , timedelta
current = datetime.now()
print('Today is '+ str(current))
oneday = timedelta(days=1)
ytd = current - oneday
print ('Yesterday is '+ str(ytd))
oneweek = timedelta(weeks=1)
lastw = current - oneweek
print ('last week is '+ str(lastw))
print('-------------------------')
print... |
3a41669c59c17ea5eef7ca92900eb39fca554bca | 841509254/test | /LeetCode/test.py | 1,777 | 3.59375 | 4 | # def trap(height):
# _sum = 0
# if len(height)<3 :
# return 0
# for i in range(1,len(height)-1):
# left_max = 0
# right_max = 0
# for j in range(i+1):
# left_max = max(left_max,height[j])
# for k in range(i,len(height)):
# right_max = max(righ... |
6dad14c85c4ed0b23faf410beeae7172b0bd9ead | x14130114/SmartDoorbell | /cv2_video.py | 1,680 | 3.5625 | 4 | """
**************************************
* OpenCV Video class *
**************************************
Initialize face recognizer and Frontal face cascade
Functions:
Check if trainer configuration file exists
Load trainer configuration file
Start capturing video from ... |
b881b7660a8bdc3f691d9a1860bc3970d4d43ea0 | zippety/total_beginner_RL | /policy_copy_1.py | 6,702 | 3.578125 | 4 | import numpy as np
import pprint
import sys
from lib.envs.gridworld import GridworldEnv
pp = pprint.PrettyPrinter(indent=2)
env = GridworldEnv()
#policy evaluation function from Denny Britz.
def policy_eval(policy, env, discount_factor=1.0, theta=.00001):
"""
Evaluate a policy in an environment given a full d... |
1d46392c4e020bb2ebe21eecd40cb40dee685885 | Shivam-Gangwar/Information-Security-Assignment | /4,5.py | 954 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[25]:
import operator
Text = 'ETAOINSHRDLCUMWFGYPBVKJXQZ'
def get_key(iteration: int, ch: str) -> int:
return ord(ch) - ord(Text[iteration])
def decryption(message, key):
decode = ""
for ch in message:
if ch.isspace():
decode += " "
... |
3ae6ec8a80969f18a38899b615c74a9b49196aed | Shahzeb98/Blackjack-game | /BJ_PROGRAM.py | 4,055 | 3.859375 | 4 | # Online Python compiler (interpreter) to run Python online.
# Write Python 3 code in this online editor and run it.
# Programming Blackjack
#import chain
from itertools import chain
# decks_in_shoe = int(input("Enter the number of decks in shoe."))
decks_in_shoe = 6
# Cheatsheet provide as basic strategy ... |
4339002271790f8dd264e75b31c11534f364f918 | muhammadsubair/54l35t0ck-455355m3nt | /number_1_solution_1.py | 1,702 | 4.0625 | 4 | '''
Env: python 2.7.6
Purpose:
Solve question number 1;
You are given a textfile that contains the age (Integer) of each people in Jakarta, let's assume Jakarta 10 Million people. The format of the file is very simple, each line is an integer representing age of one people.
Example age.txt:
==========... |
de4968d56cddaefced632fe100895fe7d44a38ca | ftx-java/Python-Test | /test/test6.py | 1,859 | 3.640625 | 4 | ##第九课
# 测试题 5. 目测以下程序会打印什么?
while True:
while True:
break
print(1)
print(2)
break
print(3)
# 动动手 0. 设计一个验证用户密码程序,用户只有三次机会输入错误,不过如果用户输入的内容中包含"*"则不计算在内。
mykey = input("请输入密码:")
realkey = '666qwer'
i = 3
while i:
if mykey == realkey:
print("密码正确")
break
... |
4093720d3f9de7cbe347d733de32f7f833205c1e | ftx-java/Python-Test | /test/test8.py | 3,920 | 3.78125 | 4 | ##第17课
# 测试4. 请问这个函数有多少个参数?
list0 = [1, 2, 3, 4, 5]
def Myfuc(x):
for i in x:
print(i)
Myfuc(list0)
# 动动手 0. 编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值。
def power(x, y):
return x ** y
print(power(2, 4))
# 2. 编写一个将十进制转换为二进制的函数,要求采用“除2取余”(脑补链接)的方式,结果与调用bin()一样返回字符串形式... |
5f3219d42cda504a6a31ecb2e28959b16f97647e | filippo82/microbit | /mpl_seis_animation_simple.py | 859 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 21:26:04 2018
@author: filippo
"""
"""
=====
microseisms
=====
This example showcases a real-time animation of a microbit accerleromter.
"""
import serial, time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as a... |
70e770c27e0f073f088f06ec56703d656cfdfd16 | Senate5000/advent_of_code | /2020/day4.py | 3,304 | 3.640625 | 4 | def construct_passport(line, passport):
print(line)
split_entries = line.split(" ")
for key_val in split_entries:
split_key_val = key_val.split(":")
print(f"split_key_val: {split_key_val}")
passport_key = split_key_val[0]
print(f"passport_key: {passport_key}")
passpor... |
22a8418383cb88997bd72f66b98e82302b50d7b3 | abbeyperini/DC_HTML_CSS | /Day5/python problems/factorial_trailing_zeros.py | 772 | 4.0625 | 4 | '''
Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Input: 3
Output: 0
Output explanation: 3! = 6, no trailing zero.
Input: 5
Output: 1
Output explanation: 5! = 120, one trailing zero.
'''
# Finish below function
d... |
320456ce3328c0eb226c38811e1e9db300624af7 | ayonar/NNetArchitecture-EmsembleModels | /generatePolygons.py | 3,159 | 3.796875 | 4 | # Generate Polygon datasets
# Python 2.7
import math, random
from PIL import Image, ImageDraw
import numpy as np
from random import randint
# Polygon generating function
def generatePolygon( ctrX, ctrY, aveRadius, irregularity, spikeyness, numVerts ) :
'''Start with the centre of the polygon at ctrX, ctrY,
t... |
a02d32dd73178bbef0fe04fc3663e026f2ae2d5c | ozkanparlakkilic/PythonExercises | /TemelVeriYapilariVeObjeler/ikiSayininYeriniDegistirme.py | 193 | 3.625 | 4 | birinciSayi = int(input("Birinci sayiyi giriniz : "))
ikinciSayi = int(input("Birinci sayiyi giriniz : "))
birinciSayi,ikinciSayi = ikinciSayi,birinciSayi
print(birinciSayi)
print(ikinciSayi) |
5af5e753380b0c68e14a8313a643732bc4a1d4aa | ozkanparlakkilic/PythonExercises | /Fonksiyonlar/ikiSayininEkokunuBulma.py | 699 | 3.75 | 4 |
def ekokBulma():
sayi1 = int(input("İlk sayiyi giriniz : "))
sayi2 = int(input("İkinci sayiyi giriniz : "))
temp1 = sayi1
temp2 = sayi2
enKucukOrtakKat = 0
if sayi1 == sayi2:
enKucukOrtakKat = sayi1
elif temp1 < temp2:
while temp1 != temp2:
if temp1 < temp2:
... |
21638338c9bc72f9a94877c3fb90b83696383630 | ozkanparlakkilic/PythonExercises | /GomuluFonksiyonlar/Filter()-Example/FilterFunctionExample.py | 993 | 3.703125 | 4 |
# Filter fonksiyonu ile listedeki çift sayilari ekrana basma
print(list(filter(lambda x : x % 2 == 0,[1,2,3,4,5,6,7,8,9,10])))
# Filter fonksiyonu ile listedeki asal sayiları ekrana basma
def asalSayi(x):
if x == 1:
return False
count = 0
for i in range(2,x+1):
if x % i == 0:
... |
bd1cb7acc0b4f6eaa1964631e2182e76a4f2baff | TRONjj/Text-repeater | /hhAa.py | 120 | 3.65625 | 4 | a = "lol"
while True:
b = input("Введи слово: ")
if b == a:
print("pozitive")
else:
print("negative") |
61cee6ead9619c86ae2c37105e0bbb950077bfe0 | JPDZ67/alien | /alien/datetime_cleanup.py | 951 | 3.65625 | 4 | import pandas as pd
from datetime import datetime
MIN_DATE = '1999-12-31 23:59:59'
def datetime_cleanup(df, main_df=None):
"""Fixes the datetime column by replacing 24: with 0: and converting to datetime object"""
df['datetime'] = df['datetime'].apply(lambda x: x.replace('24:', '0:'))
df['datetime'] = pd... |
7d614f93d73dae587402e28e85e31062bafbdfa6 | matthewosborne71/MastersHeadstartPython | /Programs/Exercise1.py | 411 | 4.125 | 4 | # Write a program that generates a random integer between 1 and 100
# and then has the user guess the number until they get it correct.
import random
Number = random.randint(1,100)
Guess = -99
print "I thought of a number, want to guess? "
while Guess != Number:
Guess = int(raw_input())
if Guess != Number:
... |
535edd9f2864930e3b46820eca2bd199380d3e6d | cloudhz/rpsls | /rpsls.py | 3,383 | 3.578125 | 4 | import sys
import random
from bisect import bisect
VALID_CHOICES = set(['rock', 'paper', 'scissors', 'lizard', 'spock'])
WINNER_LOOKUPS = {
'rock': {
'win' : ['scissors', 'lizard'],
'lose' : ['paper', 'spock']
},
'paper' : {
'win' : ['rock', 'spock'],
'lose': ['scissors', 'l... |
dc00635c650d5356d1ec18c129dff21d36fb34a8 | arslanblcn/Py-OOP | /generate.py | 1,590 | 3.546875 | 4 | import argparse
import random
import string
parser = argparse.ArgumentParser()
parser.add_argument("-uc", "--upper-chars", help="Upper Characters", action='store_true')
parser.add_argument("-lc", "--lower-chars", help="Lower Characters", action='store_true')
parser.add_argument("-n", "--numbers", help="Numbers", act... |
793c4040dce6c5cb02950fc40520be1df6a7c2fa | Pyk017/Mini_Projects | /Automation/Messy_Folder/main.py | 2,105 | 4.09375 | 4 | import os # Interacting with Operating-System
import re # Regular Expression
import shutil # High-level operations of file and collections of files
input_dir = input("Enter Directory which you want to organize :- ") # Please enter directory... in which you want to sort files according to extensions
os.chdir(i... |
b68ed99d0e68860f0ccdff2b272babe8ab836381 | InFamousGeek/PythonBasics | /ProgramToFindTheLngthOfAString1.py | 276 | 4.375 | 4 | # Python Program to find the length of a String (2nd way)
# using for loop
# Returns length of string
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = str(input("Enther the string : "))
print(findLen(str))
|
27d9f2774ea80040d76d6009bc1b003fc8033ae7 | NYUHackDays/Python | /7.py | 223 | 3.71875 | 4 | # Lets work on an idea
# {take idea from the crowd}
# Lets take an input from the user
userInput = raw_input('How can I help you sir\n')
# BTW \n means create a new line after this sentence
print "You entered " + userInput |
c184d98ce768e7dad7efb312d6d1cebbec7a7546 | Constantinepapp/Harvard-CS50x- | /Readability/readability.py | 704 | 3.78125 | 4 |
book = input("Text:")
n=len(book)
sumwords=0
sumsentence=0
sumletters=0
for i in range(0,n):
if book[i]=='.' or book[i]=='!':
sumsentence += 1;
elif book[i]=='?':
sumsentence += 1
if book[i]==' ':
sumwords += 1
if book[i] >= 'A' and book[i] <= 'Z':
sumletters... |
c08bb267e6bd632a0e99fe019d1f56989c9c02b6 | vl-flask/movie-sys | /movie.py | 581 | 3.53125 | 4 | class Movie:
def __init__(self, name, genre, watched):
self.name = name
self.genre = genre
# self.director = "Wachowski"
self.watched = watched
def __repr__(self):
return f"<Movie {self.name}>"
def json(self):
return {
'name': self.name,
... |
1cbfb38d0c5521b5c5df24c46a864d719e1d99ed | jonathan-murmu/ds | /data_structure/leetcode/easy/350 - Intersection of Two Arrays II/intersect.py | 1,406 | 3.9375 | 4 | """
https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/674/
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: n... |
cf0fcc053e157beaa2b6eee2a78fa788d7cb2b8c | jonathan-murmu/ds | /data_structure/leetcode/easy/344 - Reverse String/reverse_string.py | 991 | 4.3125 | 4 | '''
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a... |
f0be5dacbab78cfc6d3def405474f2917d5ab5eb | jonathan-murmu/ds | /data_structure/leetcode/easy/136 - Single Number/single_number.py | 744 | 3.734375 | 4 | """
https://leetcode.com/problems/single-number/
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Inpu... |
7b7a500c8401c771406bc617b3f646383c6685b4 | jonathan-murmu/ds | /data_structure/leetcode/medium/77 - Combinations/combinations.py | 1,356 | 3.84375 | 4 | """
https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total co... |
d800cb69ddc2d4b6bd5e77c4eaf9379e18122436 | jonathan-murmu/ds | /data_structure/tree/Set1Problem1/set1problem1/relations/uncle.py | 861 | 3.796875 | 4 | from ..constants import MALE
class Uncle(object):
"""Get uncle."""
def get_uncle(self, person_name, relation, family, gender):
# the mother is the main member, only then he has maternal uncle
if family.parent.main_member.gender == gender:
uncle_aunt_families = family.parent.parent.c... |
9b4ece90080e6dc411dbf090cf3e8d4874225777 | jonathan-murmu/ds | /data_structure/tree/Set1Problem1/set1problem1/relations/aunt.py | 860 | 3.796875 | 4 | from ..constants import FEMALE
class Aunt(object):
"""Get Aunt."""
def get_aunt(self, person_name, relation, family, gender):
# the mother is the main member, only then she has maternal aunt
if family.parent.main_member.gender == gender:
uncle_aunt_families = family.parent.parent.ch... |
f841b9850f10679be5757d0c9590cb6a64b6dfde | jonathan-murmu/ds | /data_structure/arrays/digit_freq.py | 296 | 4.09375 | 4 | '''Digit frequency
Given a single digit k find out how many times it appears in the given number n.
'''
def digit_freq(n, k):
count = 0
while n > 0:
if ((n % 10) == k):
count += 1
n = n//10
return count
count = digit_freq(99823739, 3)
print(count)
|
6a0a6ef7159346dc56f4acb570eb9c4f2020d009 | ankur-gupta/dframe | /dframe/missing/element_operations.py | 2,274 | 3.6875 | 4 | def __not__(x):
if x is None:
return None
else:
return not x
def __neg__(x):
if x is None:
return None
else:
return x.__neg__()
def __pos__(x):
if x is None:
return None
else:
return x.__pos__()
def __abs__(x):
if x is None:
retur... |
7fbafdf71b123b250ec8c2683aaec0c3fa799711 | 582911658/learn_python | /第09章/9.1.py | 774 | 3.609375 | 4 | class Restaurant():
"""
餐馆类
"""
def __init__(self, restaurant_name, cuisine_type):
"""
类的初始化
"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""
餐厅描述
"""
print(self.re... |
40be321dc698aeb21dda5671ebbcd33ef8ec432f | 582911658/learn_python | /第05章/5-8.py | 278 | 3.671875 | 4 | from typing import NoReturn
users = [ ]
users.append(input('请输入用户名'))
for user in users :
if user =='admin':
print('Hello admin,would you like to see a status report? ')
elif user !='admin':
print(f'Hello {user} thank you for login again!') |
a229a7d501084e4e9401ae295df02ee25d0ab5f1 | 582911658/learn_python | /第08章/8-3.py | 192 | 3.703125 | 4 | def make_shirt(size, word):
"""
打印衣服的尺码
"""
print(size.title()+'\n'+word.title())
make_shirt('63', 'I love python')
make_shirt(size='63', word='I love python')
|
68b72ee3bf295131c59603140447dbb4ed89e74d | 582911658/learn_python | /date/scatter_squares.py | 480 | 3.734375 | 4 | import matplotlib.pyplot as plt
x_values = list(range(1, 10001))
y_values = [x**2 for x in x_values]
plt.scatter(x_values, y_values, s=15)
# 设置图表标题,并给坐标轴加上标签
plt.title("Square Number", fontsize=14)
plt.xlabel("Value", fontsize=10)
plt.ylabel("Square of Value", fontsize=10)
# 设置刻度标记的大小
plt.tick_params(axis="both", wh... |
c4824cb53f4ab3f2e3abc9e6e05a9e3e8c655d97 | 582911658/learn_python | /第03章/motorcycle.py | 586 | 3.671875 | 4 | # 列表元素修改
# motorcycles = ['honda','yamaha','suzuki']
# print(motorcycles)
# motorcycles[0] = 'ducati'
# print(motorcycles)
#列表元素新增
# motorcycles = ['honda','yamaha','suzuki']
# print(motorcycles)
# motorcycles.append('ducati')
# print(motorcycles)
# motorcycles = [ ]
# motorcycles.append('honda')
# motorcycles.ap... |
0e79c9b9fb84d4fc0a8da0654a13b87872228532 | naman-32/Python_Snippets | /BASIC/v2.py | 961 | 3.5625 | 4 | message = 'bobby\'s world'
message1 = "bobby's world"
message2 = 'bobby"s world'
message3 = """bobbnjnjs
njnjkdnkdknklmdksamkdmskmdkmksd
ndskmnkldsmckldmscklds"""
print(message)
print(message1)
print(message2)
print(message3)
msg = 'Hello World'
print(msg[6])
print(msg[:5])
print(msg[6:])
print(msg[... |
3fb235ced0711f77d36d1d8a59c62bd1fdf7d564 | naman-32/Python_Snippets | /BASIC/v6.py | 1,107 | 4.28125 | 4 |
if True:#False not ok
print("alright")
else :
print("not ok")
#nkgnkgnkgbnkbgl#lkvjbljgkglbvjlbjbklbkbvlkbvljlbvjj
#"""jigbjljgfjgfljgfjlfgjbgfbjgfjlfjdrnamanjgoenka is very
language = 'jav'
if language == 'python':
print("la is python")
elif language == 'java':
print("la is java")
else:
pri... |
ac80a3e13f56d6757251aedeb5dd33741e4b62b5 | lohithabhethalam/OlympicHistory-Mapreduce | /sumOfAthletesCountries/reducer.py | 1,078 | 3.53125 | 4 | # read the contents of mapperOutput.txt for input
s = open("mapperOutput.txt","r")
# write output into reducerOutput.txt
r = open("reducerOutput.txt", "w")
# create a dictionary with empty key-value pairs
thisKey = ""
oldKey = ""
value = 0
# read each line in input file
sortedData = s.readlines()
sortedData.sort()
r.w... |
e83d6e7d131c65a29c4b60ec96c9376297382953 | mmadanguit/motor-control | /calibration-data/calibration-data.py | 971 | 3.71875 | 4 | """outputs sensor readings into graph"""
import serial
import matplotlib.pyplot as plt
# set the name of the serial port. Determine the name as follows:
arduinoComPort = "/dev/cu.usbmodem14201"
# set the baud rate so that it is the same as the sending program
baudRate = 9600
# open the serial port
seri... |
4030369f903225566c1389e396fb5ddaf6d2a4b3 | gugainfo/ALGO_REDES__2016_1_LISTA1 | /exercício3.py | 413 | 3.671875 | 4 | f = 200
g = 250
h = 8
i = 7
j = 800
k = 10
l = 2
a = f + g
b = f / h
c = f * i
d = j - k
e = l **10
print()
print("Vamos Mostrar os Resultados das questões do EX3")
print()
print("%d É o resultado da letra A" %a)
print()
print("%d É o resultado da letra B" %b)
print()
print("%d É o resultado da letra C" %c)
print()
p... |
5dcf11790445711e32ecae717c099868307c9a44 | Alkagdy/day11 | /metody_klas.py | 1,403 | 3.578125 | 4 | class Pracownik(object):
roczna_podwyzka = 5
ilosc_pracownikow = 0
def __init__(self, imie, stanowisko):
self.imie = imie
self.stanowisko = stanowisko
self.wynagrodzenie = None
Pracownik.ilosc_pracownikow += 1
def ustaw_pensje(self, kwota):
if kwota > 10000:
... |
e30217de50f48f38c25c9c5183749db67142b459 | chinalvanbliss/BudgetApp.Task | /BudgetApp.py | 3,410 | 4 | 4 | # BUDGET APP TASK
# This task will be decomposed into five steps/stages for better handling as follows:
# STEP ONE
# Create a Budget class that can instantiate objects based on different budget categories like: Food,
# Clothing and Entertainment.
class Budget:
def __init__(self, category):
self.category =... |
8e3793e8bec678cff8c2594f9a1333ac0c392fe4 | Palhares17/Python_Exercicios_UFV | /Lista2/ex012.py | 148 | 3.6875 | 4 | import math
A = int(input())
if(A > 0 or A == 0):
print(f'A raiz quadrada de {math.sqrt(A):.2f}')
else:
print(f'O quadrado é {A**2}') |
c65cdf8c7b6c3bdcf4743cd6b4d6fd519c5dc31d | Palhares17/Python_Exercicios_UFV | /Lista1/ex010.py | 139 | 3.5 | 4 | l = int(input('O valor dos lados: '))
area = l * 2
pmetro = l * 4
print(f'A área e o perímetro são de {area}, {pmetro} repectivamente.') |
6f537744ac5eba1240d4023d586a0a5731dd7939 | Palhares17/Python_Exercicios_UFV | /Lista2/ex011.py | 150 | 3.953125 | 4 | A = int(input())
B = int(input())
if(A > B):
print('A é maior que B')
elif(A < B):
print('A é menor que B')
else:
print('São iguais') |
aa3738eb5a290e251c9aaf093ad1162b3d39c305 | matteuan/lega_automate | /get_teams.py | 1,292 | 3.5625 | 4 | """ get_players retrieve all teams and fill the teams table.
It is a one time script. Typical link is http://195.56.77.208/team/"""
from bs4 import BeautifulSoup
import requests
import sys
import sqlite3
def parse_teams(link):
team_to_id = dict()
team_to_id[""] = 0
r = requests.get(link)
soup = Beaut... |
d49fc41036398468f691da9300ab49fd2a3c0f9b | ranoaritsiky/Udemy_tsiky | /udemy.py | 732 | 4.125 | 4 | # liste = ["Java", "Python", "C++"]
# liste.insert(3, liste[1])
# liste.remove("Python")
# print (liste)
# liste = ["Maxime", "Martine", "Christopher", "Carlos", "Michael", "Eric"]
# print (liste[0:3])
# liste = [1, 2, 3, 4, 5]
# liste.append(6)
# if 6 in liste:
# print ("Le nombre 6 a bien été ajouté à la liste."... |
82313ad8db88c1256b59617b7a9348dd3d7b9f8a | sksumanta/python3Basic | /tryNexcept.py | 2,462 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 1 00:48:13 2018
@author: Sumanta
"""
# unless user enter the correct the numeric till that time it will ask user input
# and find the input is present in the tuple or not.
theTuple = (20,21,23,24,26,27)
infiVal = True
while infiVal:
inVal = input(... |
36c5004ee19a8bc9d73b9f57f8936064c505a1d2 | sksumanta/python3Basic | /whileLoop.py | 1,266 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 10:56:18 2018
@author: Sumanta
"""
# what is while loop and what is the difference between for and while loop
# why while loop
"""
when the range of the iteration is not fixed then we can use while loop
when the range of the iteration is fixed then w... |
250693ad6bea3efc8e537cdbf1fbdadbd0d1bce4 | sksumanta/python3Basic | /listComprehension.py | 926 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 10:31:48 2018
@author: Sumanta
"""
# The range function in the loop
for i in range(5):
print(i)
##################### List Comprenhension ############################
lis=[]
for x in range(7):
lis.append(2**x)
print(lis) # -------- ... |
5a1bf387f76f5256d55718e109ddcf2137ea2cb9 | fangedscorpion/CS4341_CWJG | /Assignment1/astar.py | 2,482 | 3.5625 | 4 | import sys
from World import World
from AStar2Fun import AStar2
# this function tests if a given path of Nodes has a start Node
# INPUT -> (list of Nodes) path
# OUTPUT -> (boolean)
def pathHasStart(path):
for node in path:
if node.getCell().getIsStart():
return True
return False
# this ... |
02784d371bc5f88e8e2248f453d78ed368aa38b8 | fangedscorpion/CS4341_CWJG | /Assignment1/Cell.py | 3,064 | 3.84375 | 4 | from Coord import Coord
class Cell:
"""Representation for world locations"""
def __init__(self, coord, complexity):
self.coord = coord
self.vertDist = -1
self.horizDist = -1
self.isValid = False
self.heur = -1
if(str(complexity).lower() == 'g'):
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.