blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9b3aa94ef5818da1f76aacda0d12a2e83a31e8ec
zhouf1234/untitled3
/函数编程函数19内置高阶函数map.py
1,081
4.21875
4
#定义列表 numbers = [1,2,3,4,5,6,7] #要求得到一个新列表,新列表是numbers这个列表中每个元素的3次方 #map一般用来处理列表:map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 # new_number = [] # for i in numbers: # new_number.append(i ** 3) # # print(new_number) def map_fn(ite): return ite **3 res=list(map(map_fn,numbers)) #把map的返...
false
96088e55587bcbf20b661824f0717a2e6ae9987e
zhouf1234/untitled3
/函数编程函数0自定义和返回值.py
2,024
4.21875
4
#自定义一个函数print_hello() def print_hello(): #无参 pass #Python函数先定义 再调用 #函数名(print_name)本质上就是变量名 #定义阶段 def print_name(): print('nihao') print('222') print('ddd') print('....end....') #调用阶段才会执行 print_name() print_name() print_name() print() def fn_02(): b = 1 + 1 #定义函数 def fn_01(): a = 10 * 10...
false
64a4e611797c396cbc03829c781896eb330507a3
fpavanetti/python_lista_de_exercicios
/aula21_ex104.py
893
4.40625
4
''' Desafio 104 Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente. ''' def ficha(nome='', go...
false
df3a255364d770172c8ab0b9c36a9004acd4f900
fpavanetti/python_lista_de_exercicios
/aula17_explicação.py
1,952
4.46875
4
''' AULA 17 - VARIÁVEIS COMPOSTAS (LISTAS: PARTE 1) Os índices em Python são chamados de KEY Para casos em que precisamos de listas CONSTANTES = tuplas Para casos em que precisamos manipular os dados dentro da estrutura = LISTAS lista = [1, 2, 3, 4] lista[3] = 'outra coisa' Para adicionar elementos na...
false
fad1250d600a8951bf1af8879cf5cf4043492b41
fpavanetti/python_lista_de_exercicios
/aula14_ex63.py
1,023
4.1875
4
''' DESAFIO 63 Melhore o desafio 62, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disser que quer mostrar 0 termos. ''' p1 = int(input("Digite o primeiro termo da PA: ")) r = int(input("Digite a razão da PA: ")) resp = int while resp != 0: resp = i...
false
40b0d55a22addb33668cad9ea65247cd54e20ec0
fpavanetti/python_lista_de_exercicios
/aula16_ex76.py
1,117
4.28125
4
''' DESAFIO 76 - ANÁLISE DE DADOS EM UMA TUPLA Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9 B) Em que posição foi digitado o primeiro valor 3 C) Quais foram os números pares ''' pares = 0 n1 = int(input("Digite...
false
bb896caa016179a5444c7eaaa48fe355ec17fab5
fpavanetti/python_lista_de_exercicios
/aula15_ex67.py
893
4.125
4
''' DESAFIO 67 Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (des- considerando o flag). O que deve aparecer: "A soma d...
false
1c8fcbdbb630058b69cb6f37250f3d3aefc4ba5a
fpavanetti/python_lista_de_exercicios
/aula9_ex27.py
1,277
4.5
4
''' Faça um programa que leia uma frase pelo teclado e mostre: - Quantas vezes aparece a letra 'A' - Em que posição ela aparece pela primeira vez - Em que posição ela aparece pela última vez ''' f = str(input("Digite uma frase qualquer: ")).upper().split() print(f) print("A frase possui {} espaços.".forma...
false
c8e50e78c0d07129f2b0d4ebfc6da08776aaf4ca
fpavanetti/python_lista_de_exercicios
/aula14_ex59.py
1,536
4.25
4
''' DESAFIO 59 - Jogo de Adivinhação 2.0 Melhore o jogo DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. ''' from random import randint from time import sleep ...
false
dc9bb9344cadecb222767f9bc2184d89597310d9
fpavanetti/python_lista_de_exercicios
/aula19_ex94.py
1,029
4.1875
4
''' Desafio 94 Crie um programa que gerencie o aproveitamento de um JOGADOR DE FUTEBOL. O programa vai ler o NOME DO JOGADOR e QUANTAS PARTIDAS ele jogou. Depois, vai ler a QUANTIDADE DE GOLS feitos em CADA PARTIDA. No final, tudo isso será guardado em um DICIONÁRIO, incluindo o TOTAL DE GOLS feitos durante o...
false
75de8adff9ee5574cdad8788c67c44deb46a5c5e
anarariand/cs102
/homework01/caesar.py
1,151
4.25
4
def encrypt_caesar(plaintext: str) -> str: """ >>> encrypt_caesar("PYTHON") 'SBWKRQ' >>> encrypt_caesar("python") 'sbwkrq' >>> encrypt_caesar("Python3.6") 'Sbwkrq3.6' >>> encrypt_caesar("") '' """ ciphertext = "" for char in plaintext: if not char.isa...
false
17b641ee02371d924e4dc0020f65d9ba3ce5a23c
boswellgathu/py_learn
/12_strings/count_triplets.py
338
4.1875
4
# Write a Python method countTriplets that accepts a string as an input # The method must return the number of triplets in the given string # We'll say that a "triplet" in a string is a char appearing three times in a row # The triplets may overlap # for more info on this quiz, go to this url: http://www.programmr....
true
5eab2196af7a27cfffeadcdacbc4e5f94c3d70c6
boswellgathu/py_learn
/8_flow_control/grade.py
497
4.125
4
# Write a function grader that when given a dict marks scored by a student in different subjects # prepares a report for each grade as A,B,C and FAIL and the average grade # example: given # marks = {'kisw': 34, 'eng': 50} # return # {'kisw': 'FAIL', 'eng': 'C', 'average': 'D'} # A = 100 - 70, B = 60 - 70, C = 50 - 60...
true
b86e8fdcecfd16b387546feee6fd171942b16033
ICLau/randomStuff
/test-asterisk.py
1,200
4.625
5
# # https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/ # """ what = [1,2,3,4,5] print (f'*what:', *what) print (f'what:', what) lol = [[1,4,7,11], [2,5,8,], [3,6,9,]] ziplol = zip(*lol) print (f'lol: {lol}') print (f'*lol:->', *lol) print (f'ziplol: {ziplol}') for i in ziplol: pr...
false
78f11800113f225702032ce9481c411f306d6658
rafaelribeiroo/scripts_py
/Mundo 03: Estruturas Compostas/23. Listas I/4. Inserção mais complexa.py
410
4.1875
4
# list define que será uma lista vazia até receber um append valores = list() for c in range(0, 5): valores.append(int(input('Digite um valor: '))) # Mostra apenas os elementos for elemento in valores: print(f'{elemento}...', end='') # Mostra os elementos e o índice for posição, elemento in enumer...
false
ec483614b64aa91427ce30b2c457e79141361e6c
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/102. Função para fatorial.py
874
4.15625
4
# 102. Crie uma função fatorial() que receba dois parâmetros: o primeiro que # indique o número a calcular e o outro chamado show, que será um valor # lógico (opcional) indicando se será mostrado ou não na tela o # processo de cálculo do fatorial. def fatorial(n, show=False): ''' -> Calcula o Fatorial...
false
5e61b1c087b8d4f3b7144da7e7900aee7d8b8db2
rafaelribeiroo/scripts_py
/Mundo 03: Estruturas Compostas/31. Funções II/1. Docstrings.py
588
4.15625
4
# No PY, todos os comandos fornecem uma documentação para melhor compreensão, # que pode ser acessada através de help(método). Em nossas funções, é # possível oferecer isso também através dos comentários abaixo. def contador(i, f, p): """ -> Faz uma contagem e mostra na tela. :param i: início da contagem ...
false
6307fa2237a0317e621459d2d764db4e10b8f639
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/26. Primeira e última ocorrência de uma string.py
564
4.125
4
# 26. Faça um programa que leia uma frase pelo teclado e mostre: # > Quantas vezes aparece a letra "A". # > Em que posição ela aparece a primeira vez. # > Em que posição ela aparece a última vez. frase = input('Digite uma frase: ').upper().strip() print(f"Analisando a letra 'A', ela aparece {frase.count('A')} ...
false
2fac6d1c50c76bc283fa9210f27854f62be7f0b5
rafaelribeiroo/scripts_py
/Mundo 03: Estruturas Compostas/27. Dicionários/4. Iterando dicionários.py
240
4.125
4
pessoas = {'nome': 'Rafael', 'sexo': 'M', 'idade': 25} # Como no dict não há o ENUMERATE, podemos utilizar as características vistas # anteriormente para repesentá-lo for key, value in pessoas.items(): print(f'O {key} é {value}')
false
26313125ba6626d10b33a608e93346bf56ccfb94
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/85. Listas com pares e ímpares.py
861
4.28125
4
# 85. Crie um programa onde o usuário possa digitar sete valores numéricos e # cadastre-os em uma lista única que mantenha separados os valores pares e # ímpares. No final, mostre os valores pares e ímpares em ordem crescente # Podemos declarar dessa forma também, pra não ter que sempre ficar inserindo # uma list...
false
4e2e19b88a59cf422a811ccc10f532147c66321b
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/37. Conversor de bases numéricas.py
901
4.34375
4
# 37. Escreva um programa que leia um número inteiro qualquer e peça para o # usuário escolher qual será a base de conversão: # > 1 para binário # > 2 para octal # > 3 para hexadecimal num = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para conversão: [ 1 ] converter para BINÁRIO [ ...
false
4bf760250f45132573e5bacef08da788ef893017
rafaelribeiroo/scripts_py
/+100 exercícios com enunciados/77. Contando vogais em tupla.py
521
4.125
4
# 77. Crie um programa que tenha uma tupla com várias palavras (não usar # acentos). Depois disso, você deve mostrar, para cada palavra, quais # são as suas vogais. lista = ( 'aprender', 'programar', 'linguagem', 'python', 'curso', 'grátis', 'estudar', 'praticar', 'trabalhar', 'mercado', 'programador', 'fu...
false
ebc4b93409aaa4382720eb1c7eaa5ea50ab6b31d
dfi/Learning-edX-MITx-6.00.1x
/itertools.py
608
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 14 20:10:18 2017 @author: sss """ # https://docs.python.org/3.5/library/itertools.html import operator def accumulate(iterable, func=operator.add): 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,...
true
a65f814ce9f62bc8cff8642691e206d8fa8c6b96
pabolusandeep1/python
/lab1/source code/password.py
854
4.15625
4
#validation cliteria for the passwords import re# importing the pre-defined regular expressions p = input("Input your password: ") x = True while x:# loop for checking the various cliteria if (len(p)<6 or len(p)>16):#checking for the length print('\n length out of range') break elif not re.sear...
true
6be0dd923383acba74f9820a0b4ac590b58618ed
jasonifier/tstp_challenges
/ch5/challenge4.py
732
4.28125
4
#!/usr/bin/env python3 about_me = {'height': 70, 'favorite_color': 'red', 'favorite_athlete': 'Stephen Curry', 'favorite_show': 'The Big Bang Theory'} inquiry = input("Select what you want to learn about me by typing one of four letters for the attribute: (a) - 'height', (b) - 'favorite_color', (c) - 'favorite_athlet...
false
fad58160cbcd35d9a671c8bc1217cf151560fafd
jasonifier/tstp_challenges
/ch6/challenge2.py
247
4.125
4
#!/usr/bin/env python3 response_one = input("Enter a written communication method: ") response_two = input("Enter the name of a friend: ") sentences = "Yesterday I wrote a {}. I sent it to {}!".format(response_one,response_two) print(sentences)
true
4a68ac695f956f6f9ee1326e59d21ce5554362ee
jasonifier/tstp_challenges
/ch4/challenge1.py
289
4.15625
4
#!/usr/bin/env python3 def squared(x): """ Returns x ** 2 :param x: int, float. :return: int, float square of x. """ return x ** 2 print(squared(5)) print(type(squared(5))) print(squared(16)) print(type(squared(16))) print(squared(5.0)) print(type(squared(5.0)))
true
e81f21436059dc2b3cd7f16ca43473a3f6e0f30f
destleon/Python-project
/classact.py
1,933
4.25
4
Boy_NameOfWeeks = ['Kojo','kwabena','Kwaku','Yaw','Kofi','Kwame','Kwasi'] Girl_nameOfweeks =['Adjoa','Abena','Akua','Yaa','Afia','Ama','Esi'] dayOfBirth = input("please enter your day of birth ") gender = input("are you a male or a female ") loglist = [] if (dayOfBirth == 'monday' and gender == 'female'): pri...
false
871016d4714e1d5e710bd7d3c06ab5a269040d70
Code-for-me-10/My-codes
/my_file5.py
1,158
4.1875
4
# booleans print(True) print("True") print(type(True)) # bool type print(type("True")) # string type print(5==5) print(5==6) # loops # 1. if x = 10 y = 5 if x%y == 0: print(True) else: print(False) # 2. while number = 1 while number < 10: print(number) if number == 7: ...
false
76c7b4ba9c6176b96c050884111c397d651c2cba
Epiloguer/ThinkPython
/Chapter 2/Ex_2_2_3/Ex_2_2_3.py
612
4.15625
4
# If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), # then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, # what time do I get home for breakfast? import datetime easy_pace = datetime.timedelta(minutes = 8, seconds = 15) easy_miles = 2 tempo = datetime.timedelta(minutes ...
true
8c5f65fa6ce581a28ed8d34c5a36fa0c186af33d
Epiloguer/ThinkPython
/Chapter 1/Ex_1_2_3/Ex_1_2_3.py
643
4.15625
4
# If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace # (time per mile in minutes and seconds)? What is your average speed in miles per hour? kilometers = 10 km_mi_conversion = 1.6 miles = kilometers * km_mi_conversion print(f'you ran {miles} miles') minutes = 42 minutes_to_seconds = min...
true
b62fa67f503814abbe41952067be6b9083e7b0b9
ANUMKHAN07/assignment-1
/assign3 q6.py
203
4.21875
4
d = {'A':1,'B':2,'C':3} #DUMMY INNITIALIZATION key = input("Enter key to check:") if key in d.keys(): print("Key is present and value of the key is:",d[key]) else: print("Key isn't present!")
true
1f0714e66eb4c28d8c77ec279db5c6c45f178f81
Louise0709/calculator-
/calculator.py
617
4.3125
4
income=int(input('what\'s your salary?')) salary=0 shouldPay=0 tax=0 def calculator(num): shouldPay=num-5000 if shouldPay<=0: tax=0 elif 0<shouldPay <=3000: tax=shouldPay*0.03 elif 3000 < shouldPay <=3000: tax=shouldPay*0.1-210 elif 12000< shouldPay <=25000: tax=shouldPay<=0.2-1410 elif 25000< shouldPay <...
false
5cecd539c025b0733629ff4c403d70e280f00284
PallaviGandalwad/Python_Assignment_1
/Assignment1_9.py
213
4.1875
4
print("Write a program which display first 10 even numbers on screen.") print("\n") def EvenNumber(): i=1 while i<=10: print(i*2," ",end=""); i=i+1 #no=int(input("Enter Number")) EvenNumber()
true
47715f1e3fe9c0cc7dbb898ff0082d053ea6fa51
csyhhu/LeetCodePratice
/Codes/33/33.py
1,324
4.15625
4
def search(nums, target: int): """ [0,1,2,4,5,6,7] => [4,5,6,7,0,1,2] Find target in nums :param nums: :param target: :return: """ def binSearch(nums, start, end, target): mid = (start + end) // 2 print(start, mid, end) if start > end: return -1 ...
true
c39b8d31be3c31cc2a914a2bd0ae5a380363b27b
zhanengeng/mysite
/知识点/字符串和常用数据结构/日付け計算.py
638
4.3125
4
'''入力した日付はその年何日目''' def leap_year(year): return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def which_day(year,month,day): days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days_count = 0 if leap_year(year): days_of_month[1...
true
9de40eb8d5d6abd67ff90ff2195562822399567f
lucien-stavenhagen/JS-interview-research
/fizzbuzz.py
902
4.21875
4
# # and just for the heck of it, here's the # Python 3.x version of FizzBuzz, using a Python closure # # Here's the original problem statment: # "Write a program that prints all # the numbers from 1 to 100. # For multiples of 3, instead of the number, # print "Fizz", for multiples of 5 print "Buzz". # For numbers which...
true
d4e9e097d89d3db339d92adde12b682548adf8c8
Dipesh1Thakur/Python-Basic-codes
/marksheetgrade.py
329
4.125
4
marks=int(input("Enter the marks :")) if (marks>=90): print("grade A") elif (marks>=80) and (marks<90): print("grade B") elif marks>=70 and marks<80: print("grade C") elif marks>=60 and marks<70: print("grade D") elif marks>=50 and marks<40: print("grade E") else: print("Your grade i...
true
774075170cd50e0197b4c5a830515a9a5fac7211
zungu/learnpython
/lpthw/ex14.py
982
4.4375
4
#!/usr/bin/python from sys import argv #defines two items to be inputted for argv (script, user_name) = argv prompt1 = 'give me an answer you ass > ' prompt2 = 'I\'ll murder ye grandmotha if ye don\'t tell me > ' prompt3 = 'Sorry please answer, I\'m just having a bad day > ' print "Hi %s, I'm the %s script." % (use...
true
acca2584c588aab08753d32484a804b5e492d8e0
zungu/learnpython
/lpthw/ex20.py
1,249
4.28125
4
#!/usr/bin/python from sys import argv script, input_file = argv #defines the function, the j can be any letter def print_all(j): print j.read() def rewind (j) : j.seek(0) # defines a function, with a variable inside of it. line_count is a variable cleverly named so that the user knows what it is doing. late...
true
5dde55554b5745f3dc71a7bb201d20a3e0496239
rehmanalira/Python-Practice-Problems
/Practice problem8 Jumble funny name.py
908
4.21875
4
""" It is a program which gives funny name """ from random import shuffle # for shffling from random import sample # sampling shuffle def function_shuffling(ele): # this is a function which is used to shuflle with this is used for shuflling ele=list(ele) # store the valu of list in ele shuffl...
true
53df6c7f31947ba21c4a0e0bbed1840ed790e8d9
Ivankipsit/TalentPy
/May week5/Project1.py
1,917
4.25
4
""" Create a python class ATM which has a parametrised constructor (card_no, acc_balance). Create methods withdraw(amount) which should check if the amount is available on the account if yes, then deduct the amount and print the message “Amount withdrawn”, if the amount is not available then print the message “OOPS! Un...
true
d12f4c3636de41e75e9a4bf5e435166f00866b4e
minal444/PythonCheatSheet
/ArithmaticOperations.py
770
4.125
4
# Arithmetic Operations print(10+20) # Addition print(20 - 5) # Subtraction print(10 * 2) # Multiplication print(10 / 2) # Division print(10 % 3) # Modulo print(10 ** 2) # Exponential # augmented assignment operator x = 10 x = x + 3 x += 3 # augmented assignment operator x -= 3 # augmented assignme...
true
c7237ded5227b686fe4d6a005db6b52a7c5bf435
chandthash/nppy
/Project Number System/quinary_to_octal.py
1,525
4.71875
5
def quinary_to_octal(quinary_number): '''Convert quinary number to octal number You can convert quinary number to octal, first by converting quinary number to decimal and obtained decimal number to quinary number For an instance, lets take binary number be 123 Step 1: Convert t...
true
e0da7a3dd1e796cf7349392dc1681663e36616ad
chandthash/nppy
/Minor Projects/multiples.py
317
4.25
4
def multiples(number): '''Get multiplication of a given number''' try: for x in range(1, 11): print('{} * {} = {}'.format(number, x, number * x)) except (ValueError, NameError): print('Integer value was expected') if __name__ == '__main__': multiples(10)
true
dddc399fa7fc2190e838591ae38c24b3065afadd
purwar2804/python
/smallest_number.py
660
4.15625
4
"""Write a python function find_smallest_number() which accepts a number n and returns the smallest number having n divisors. Handle the possible errors in the code written inside the function.""" def factor(temp): count=0 for i in range(1,temp+1): if(temp%i==0): count=count+1 ret...
true
5ff2b74ab932957cfe36253a8d686018564a8c16
purwar2804/python
/longestsub.py
451
4.15625
4
def longest_substring(string): l=[] for i in range(0,len(string)): s1=string[0] for j in range(i+1,len(string)): if(string[j] not in s1): s1=s1+string[j] else: if(len(s1)>=3): l.append(s1) s2="" for k ...
false
37e7b3c7ea73bc62be4d046ce93db984b269e2aa
brawler129/Data-Structures-and-Algorithms
/Python/Data Structures/Arrays/reverse_string.py
805
4.40625
4
import sys def reverse_string(string): """ Reverse provided string """ # Check for invalid input if string is None or type(string) is not str: return 'Invalid Input' length = len(string) # Check for single character strings if length < 2: return string # Retur...
true
3425852ccba1415b95e0feaf62916082d4a3f8b6
itu-qsp/2019-summer
/session-8/homework_solutions/sort_algos.py
2,501
4.125
4
"""A collection of sorting algorithms, based on: * http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html * http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html Use the resources above for illustrations and visualizations. """ def bubble_sort(data_l...
true
b6e003c0946e13e0f2bc4d386cab5e3c966f2998
itu-qsp/2019-summer
/session-6/homework_solutions/turtle_geometry.py
1,424
4.34375
4
from turtle import Turtle, done class GeometryTurtle(Turtle): def make_square(self, width): moves = [width] * 4 for move in moves: self.right(90) self.forward(move) def make_rectangle(self, width, height): moves = [width, height] * 2 for move in mov...
false
3f859b0275a136b8b8078b7d0798c3496d57af06
itu-qsp/2019-summer
/session-6/homework_solutions/A.py
2,864
4.6875
5
""" Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this, see file mad_libs.txt: The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected...
true
7cf44380af29bb10e89ef1ec62ba1b2ee96c0066
fortiz303/python_code_for_devops
/join.py
290
4.34375
4
#Storing our input into a variable named input_join input_join = input("Type a word, separate them by spaces: ") #We will add a dash in between each character of our input join_by_dash = "-" #Using the join method to join our input. Printing result print(join_by_dash.join(input_join))
true
81151f0a5de8a7edda840bb24e97288a99d29ab0
MyreMylar/artillery_duel
/game/wind.py
2,110
4.15625
4
import random class Wind: def __init__(self, min_wind, max_wind): self.min = min_wind self.max = max_wind self.min_change = -3 self.max_change = 3 self.time_accumulator = 0.0 # Set the initial value of the wind self.current_value = random.randint(self.min,...
true
a39693609674bd616fe3f12e1cc173188d3688ae
svfarande/Python-Bootcamp
/PyBootCamp/Advance DS/advanced_lists.py
1,096
4.375
4
mylist = [1, 2, 3, 2] print(mylist) print(mylist.count(2)) # 2 # appending element - print(mylist.append(4)) # None print(mylist) # [1, 2, 3, 2, 4] # appending list - incorrect way - mylist.append([3, 5]) print(mylist) # [1, 2, 3, 2, [3, 5]] # appending list - correct way - mylist = [1, 2, 3, 2] mylist = m...
false
69e105a8de8977b9177b21a4219a2a6ea6b42e33
svfarande/Python-Bootcamp
/PyBootCamp/Advance DS/advanced_strings.py
1,664
4.28125
4
s = 'hellow world' print(s.capitalize()) # Hellow world print(s.lower()) # hellow world print(s.upper()) # HELLOW WORLD print(s) # hellow world print(s.count('o')) # 2 print(s.find('o')) # 4 # 1st occurrence of that string print(s.center(20, 'z')) # zz...
false
ea2e97ed068f7dc534f6d1dd6318927d2ed01a4a
svfarande/Python-Bootcamp
/PyBootCamp/errors and exception.py
957
4.125
4
while True: try: # any code which is likely to give error is inserted in try number1 = float(input("Enter Dividend (number1) for division : ")) number2 = float(input("Enter Divisor (number2) for division : ")) result = number1 / number2 except ValueError: # it will run when ValueError ...
true
9b6c4e8219809f7e2235bdedad400d80f6d0be98
nage2285/day-3-2-exercise
/main.py
1,027
4.34375
4
# 🚨 Don't change the code below 👇 height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #print(type(height)) #print(type(weight)) #BMI Calculator BMI = round(weight/ (height * height)) if BMI <...
true
f008d9f277104d710ab6268fd562d220c7850c86
semihsevik/BasicPython
/bubleSort.py
415
4.21875
4
#Buble Sort def bubbleSort(arr): arrLen = len(arr) for i in range(arrLen - 1): for j in range(0, arrLen-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [14 , 63 , 56 , 22 , 756 , 29 , 3] print("Array:" , arr) bubbleSort(arr) #Sıralanmış listeyi list comprehension yapısı ...
false
e7b53c7fbc4d829b538dd65e5b6014376d5416c2
semihsevik/BasicPython
/biggestDigit.py
247
4.1875
4
number = input("Sayı: ") numOfDigits = len(number) number = int(number) digitList = [] for i in range(numOfDigits): digit = number % 10 digitList.append(digit) number //= 10 biggestDigit = max(digitList) print(biggestDigit)
false
c49c011ba6e6cf3ab79a148655948f6b51a0f3c1
AstroOhnuma/Unit5
/displaydate.py
446
4.125
4
#Astro Ohnuma #11/16/17 #displaydate.py - displays the current date import datetime today = datetime.date.today() today.day today.month today.year today.weekday() month = ['January','February','March','April','May','June','July','August','September','October','November','December'] weekday = ['Monday','Tuesday','Wednes...
false
6c635536f0536a5559620557dde4b1d49941b1fc
waynessabros/Linguagem-Python
/script_13.py
834
4.53125
5
"""Em python strings são objetos pode-se aplicar métodos a strings string = string.metodo() """ #-*- coding: utf-8 -*- a="Diego" b="Mariana" concatenar = a + " " + b print(concatenar) print(concatenar.lower())#lower = deixar tudo em minisculo print(concatenar.upper())#upper = deixar tudo em maiusculo concatenar2=con...
false
5d6f1d2bb57b752e8d5bbff3d6fad38c375976c5
waynessabros/Linguagem-Python
/script_17.py
747
4.3125
4
#listas em python #-*- coding: utf-8 -*- minha_lista = ["abacaxi","melancia", "abacate"] minha_lista2 = [1,2,3,4,5] minha_lista3 = ["abacaxi", 2, 9.89, True] print(minha_lista) print(minha_lista2) print(minha_lista3) print(minha_lista[0])#exibe determinado item da lista for item in minha_lista:#imprime item por item...
false
4d7defe699a93eaed852f88c73029be2f50465f2
cs24k1993/Offer
/1.1.bubbleSort.py
763
4.1875
4
# coding:utf-8 ''' 冒泡法: 第一趟:相邻的两数相比,大的往下沉。最后一个元素是最大的。 第二趟:相邻的两数相比,大的往下沉。最后一个元素不用比。 ''' def bubbleSort2(lists): count = len(lists) for i in range(count-1): for j in range(count-i-1): if lists[j] > lists[j+1]: lists[j], lists[j+1] = lists[j+1], lists[j] return lists lists...
false
61d5f409e19effec42600395ec8e9ce06f88b956
UjjwalDhakal7/basicpython
/typecasting.py
1,793
4.46875
4
#Type Casting or Type Cohersion # The process of converting one type of vaue to other type. #Five types of data can be used in type casting # int, float, bool, str, complex #converting float to int type : a = int(10.3243) print(a) #converting complex to int type cannot be done. #converting bool to int : ...
true
48741d9ccf235ca379a3b7ead7082637b33c450d
UjjwalDhakal7/basicpython
/booleantypes.py
248
4.21875
4
#boolean datatypes #we use boolean datatypes to work with boolean values(True/False, yes/no) and logical expressions. a = True print(type(a)) a = 10 b=20 c = a<b print(c) print(type(c)) print(True + True) print(False * True)
true
50ed06f5df2f648636a8237cca5ca3cd36732b2c
UjjwalDhakal7/basicpython
/intdatatypes.py
1,181
4.40625
4
#we learn about integer datatypes here: #'int' can be used to represent short and long integer values in python 3 # python 2 has a concpet of 'long' vs 'int' for long and short int values. #There are four ways to define a int value : #decimal, binary, octal, hexadecimal forms #decimal number system is the default...
true
8709a8799021fed49bb620d7088c22bc086492dd
ewrwrnjwqr/python-coding-problems
/python-coding-problems/unival tree challenge easy.py
1,921
4.25
4
#coding problem #8 #A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. #Given the r to a binary tree, count the number of unival subtrees. # the given tree looks like.. # 0 # / \ # 1 0 # / \ # 1 0 # / \ # 1 ...
true
1f3b48d098480dd34dee90aaabe24822b6682e71
ColeCrase/Week-5Assignment
/Page82 pt1.py
228
4.125
4
number = int(input("Enter the numeric grade: ")) if number > 100: print("Error: grade must be between 100 and 0") elif number < 0: print("Error: grade must be between 100 and 0") else: print("The grade is", number)
true
e25f0c584eecec3fba8b638eba070b15fc4d245c
subho781/MCA-Python-Assignment
/Assignment 2 Q6.py
213
4.375
4
number = int(input(" Enter the number : ")) if((number % 5 == 0) and (number % 3 == 0)): print("Given Number is Divisible by 5 and 3",number) else: print("Given Number is Not Divisible by 5 and 3",number)
false
8de67b2e8d4fb914a3b9f3e29a5a85d9cba30c0c
subho781/MCA-Python-Assignment
/Assignment 2 Q7.py
337
4.1875
4
#WAP to input 3 numbers and find the second smallest. num1=int(input("Enter the first number: ")) num2=int(input("Enter the second number: ")) num3=int(input("Enter the third number: ")) if(num1<=num2 and num1<=num3): s2=num1 elif(num2<=num1 and num2<=num3): s2=num2 else: s2=num3 print('second smallest...
true
bd2ef2d43a62650f68d140b1097e98b73a27f293
Athenstan/Leetcode
/Easy/Edu.BFSzigzag.py
888
4.15625
4
class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None #first try at the problem def traverse(root): result = [] if root is None: return result # TODO: Write your code here queue = deque() queue.append(root) toggle = True while queue: levelsize = ...
true
d407f3540a1a4d7240fb572a3e1fa12e430cdced
rjimeno/PracticePython
/e6.py
273
4.125
4
#!/usr/bin/env python3 print("Give me a string and I will check if it is a palindrome: ") s = input("Type here: ") for i in range(0, int(len(s)/2)): l = len(s) if s[i] != s[l-1-i]: print("Not a palindrome.") exit(1) print("A palindrome!") exit(0)
true
f72b45ba5408c8ab5afbe1d88e96c10bb157b920
rjimeno/PracticePython
/e3.py
1,479
4.15625
4
#!/usr/bin/env python3 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] default_limit = 5 for x in a: if x < default_limit: print(x) # Extras: # 1.Instead of printing the elements one by one, make a new list that has all # the elements less than 5 from this list in it and print out this new list. def list_less...
true
4c45d8b55ec5830f9fc6d0287b513fdc129b44dc
siglite/nlp100knock
/chapter1/knock00.py
1,274
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 00. 文字列の逆順 # 文字列 "stressed" の文字を逆に(末尾から先頭に向かって)並べた文字列を得よ. text = "stressed" answer = "desserts" # Case 1 ########## case1 = text[::-1] # str[start:end:step] : start から end まで step 毎の文字列を取得 # text[1:7:2] => "tes" (1 から 7 まで 2 文字毎) ...
false
b5a3565e203b64adf84a1446dda1b7fe0d6ce6c6
james-hadoop/JamesPython
/web_crawler/showTuple.py
1,166
4.21875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- __author__ = 'hstking hstking@hotmail.com' class ShowTuple(object): def __init__(self): self.T1 = () self.createTuple() self.subTuple(self.T1) self.tuple2List(self.T1) def createTuple(self): print(u"创建元组:") print(u"T1 = (1,2,3,4,5,6,7,8,9,10)") self.T1 = (1...
false
c6e36b6fb21454dbfb35fcf4862afeb97c3abbc5
souzartn/Python2Share
/other/completed/Rock_Paper_Scissors.py
1,296
4.34375
4
################################################################ # Challenge 02 # Game "Rock, Paper, Scissors" # Uses: Basic Python - e.g. If, elif,input, print ################################################################ import os clearScreen = lambda: os.system('cls') def computeGame(u1, u2): if u1 == u2...
true
80e6a92937db9f5a34465ec78fff113e99b1e4a9
neerajmaurya250/100-Days-of-Code
/Day-12/power.py
417
4.125
4
terms = int(input("How many terms? ")) result = list(map(lambda x: 2 ** x, range(terms))) # display the result print("The total terms is:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) # output: # How many terms? 5 # The total terms is: 5 # 2 raised to power 0 is 1 # 2 raised t...
true
a805c9af0f10ca75770fc88d7b33967e5af71cfc
everydaytimmy/code-war
/7kyu.py
716
4.1875
4
# In this kata, you are asked to square every digit of a number and concatenate them. # For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): return int(''.join(str(int(i)**2) fo...
true
cdc5c85f46fd305ca907c9fbade019303c7b3c9d
Keion-Larsen/cp1404practicals
/prac_05/hex_colours.py
587
4.25
4
HEXADECIMAL_COLOURS = {"AliceBlue": '#f0f8ff', 'beige': 'f5f5dc', 'black': '000000', 'blue': '#0000ff', 'brown': '#a52a2a', 'chocolate': '#d2691e', 'coral': '#ff7f50', 'cyan1': '#00ffff', 'DarkGreen': '#006400', 'firebrick': '#b22222'} colour_name = input("Please enter a c...
false
1a240fc55219fb3bc62c04352bbc734a568ffd46
frobes/python_learning
/abnormal/json.py
1,443
4.28125
4
#使用模块json存储数据 #json能让简单的python数据结构转储到文件中,并在程序再次运行时加载文件中的数据。 #json.dump()和json.load() #number_writer.py import json numbers = [2,3,5,7,11,13] filename = 'numbers.json' #使用函数json.dump()将数字列表存储到文件numbers.json with open(filename,'w') as f_obj: json.dump(numbers,f_obj) #AttributeError: module 'json' has no attrib...
false
08c96e56664470ca7bd05aed0a3d8f583bd57b1d
ksakkas/Learn-Python
/greek/class.py
835
4.125
4
# Κλάσεις στην Python class mclass: # Δημιουργία κλάσης με όνομα mclass x = 5 p1 = mclass() # Δημιουργήστε ένα αντικείμενο με το όνομα p1 και εκτυπώστε την τιμή του x print(p1.x) print("--------------------") class Person: def __init__(self, name, age): # Η συνάρτηση __init __ () καλείτ...
false
c944e5314444364dfcffe437c49a16cd70062888
rjrishav5/Codes
/Linkedlist/insert_doubly_linkedlist.py
2,193
4.28125
4
class Node: def __init__(self,data): self.data = data self.next = None self.prev = None class doubly_linkedlist: def __init__(self): self.head = None # insert node at the end of a doubly linkedlist def at_end(self,data): new_node = Node(data) if self.head is...
true
596d01a48433701abcdf0b13d338b6d176d3de90
YOON81/PY4E-classes
/09_dictionaries/exercise_04.py
973
4.25
4
# Exercise 4: Add code to the above program to figure out who has the most messages # in the file. After all the data has been read and the dictionary has been created, # look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum # loops) to find who has the most messages and print how many me...
true
92514ac1daed990f7d22f402f23760511642d1c1
YOON81/PY4E-classes
/04_functions/exercise_06.py
759
4.15625
4
# Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and # create a function called computepay which takes two parameters (hours and rate). # ** 첫번째 질문에 문자 입력했을 때 에러 메세지 뜨는 건 아직 해결 안됨 ** # ** 마지막 프린트문에 에러 뜸 ! ** hours = input('Enter Hours: ') rate = input('Enter Rate: ') try: hours = float...
true
8dbdb6407f75391c2148ac54a31056364c8cb58c
SindiCullhaj/pcs2
/lecture 5 - sorting/insertion.py
280
4.125
4
def insertionSort(list): for i in range(1, len(list)): for j in range(0, i): if (list[i] < list[j]): item = list.pop(i) list.insert(j, item) a = [5, 1, 4, 2, 6, 3] print("Initial: ", a) insertionSort(a) print("Final: ", a)
false
7f9d7da99a451c6e90b34331a02076cdbe4b2d3b
brad93hunt/Python
/github-python-exercises/programs/q12-l2-program.py
482
4.125
4
#!/usr/bin/env python # # Question 12 - Level 2 # # Question: # Write a program, which will find all such numbers between 1000 and 3000 (both included) # such that each digit of the number is an even number. # The numbers obtained should be printed in a comma-separated sequence on a single line. def main(): # Prin...
true
9bd97f882ac5185dd2f78b4f4ed83e3e7c930de6
brad93hunt/Python
/github-python-exercises/programs/q13-l2-program.py
595
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # Question 13 - Level 2 # # Question: # Write a program that accepts a sentence and calculate the number of letters and digits. # Suppose the following input is supplied to the program: # hello world! 123 # Then, the output should be: # LETTERS 10 # DIGITS 3 def main(): user...
true
2af9387667d6254a491cef429c85c32e75a3c2d8
Artem123Q/Python-Base
/Shimanskiy_Artem/homework_5/homework5_2.py
788
4.25
4
''' Task 5.2 Edit your previous task: put the results into a file. Then create a new python script and import your previous program to the new script. Write a program that reads the file and prints it three times. Print the contents once by reading in the entire file, once by looping over the file object, and once by ...
true
14d073161823c4a5e088b42bf08480dc072cc804
KonstBelyi/Python_hw
/lesson_9/task_3.py
1,566
4.25
4
""" Даны значения двух моментов времени, принадлежащих одним и тем же суткам: часы, минуты и секунды для каждого из моментов времени. Известно, что второй момент времени наступил не раньше первого. Определите, сколько секунд прошло между двумя моментами времени. Программа на вход получает три целых числа: часы, минуты,...
false
5b8d1ace63c60e8cd8b80d6a9dbeb6fdd003f55b
KonstBelyi/Python_hw
/lesson_5/task_4.py
958
4.21875
4
""" 4. Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в строку и выведите получившуюся строку. При решении этой задачи посторайтесь не пользоваться циклами и инструкцией `if`. """ string = 'Волшебный Пендаль' # input('Please, enter a string: ...
false
90f7be5030f16383990d1b86da825e14378d3e99
KonstBelyi/Python_hw
/lesson_5/task_7.py
876
4.65625
5
""" Дана строка, в которой буква `h` встречается минимум два раза. Удалите из этой строки первое и последнее вхождение буквы `h`, а также все символы, находящиеся между ними. При решении этой задачи использовать циклы - ЗАПРЕЩЕНО! (Задача решается в 3 (три) строчки кода. Понадобятся методы поиска, срезы и метод repla...
false
cc3ac6ecc1a37725a461e77c9bc38e0b8670763a
KonstBelyi/Python_hw
/lesson_9/task_5.py
749
4.5625
5
""" Дано целое, положительное ЧИСЛО (не строка). Необходимо его перевернуть (работаем как с ЧИСЛОМ). Программа принимает на вход целое число, возвращает ЧИСЛО являющееся зеркальным отражением исходного. Нечего, кроме, цикла и арифметических операторов применять нельзя. """ number = int(input('Введите целое число: ')) ...
false
30ab4ea8670f90b416f0b6fc86d33ecfa1490fb7
KonstBelyi/Python_hw
/lesson_6/task_6.py
2,631
4.125
4
""" Петя перешёл в другую школу. На уроке физкультуры ему понадобилось определить своё место в строю. Помогите ему это сделать. Программа получает на вход невозрастающую последовательность натуральных чисел, означающих рост каждого человека в строю. После этого вводится число X – рост Пети. Все числа во входных данных...
false
27495ff095e063331f70111ca9a9055a3b4d1c4a
my-sundry/FinanceTools
/sh_hk_hq_financial_report/unzip.py
668
4.125
4
#zip文件解压缩并删除原压缩文件 #巨潮下载三表和行情为压缩文件 import zipfile import os def un_zip(file_name): """unzip zip file""" zip_file = zipfile.ZipFile(file_name) if os.path.isdir(file_name[:-4]): pass else: os.mkdir(file_name[:-4]) for names in zip_file.namelist(): zip_file.ex...
false
4a0ba4aa999fe8dc26cbe25ca313f61e6fd8d9c4
gryzzia/Python-tasks
/The sum of the values of two elements.py
494
4.125
4
# Генерируется 3 случайных значения, если сумма значений двух элементов будет равна 3-му вывести ДА # 3 random values ​​are generated if the sum of the values ​​of two elements is equal to the 3rd; print YES from random import randint a=[randint(1,10) for i in range(3)] if a[0]==a[1]+a[2]: print ('yes') if a[...
false
9ecf2afb58c4c9a938b4d8a96f75a4858d5138bc
xinmu01/python-code-base
/Advanced_Topic/Iterator_example.py
1,113
4.28125
4
class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) # After define the __iter__, the iter() and for in loop can be used. def __iter__(self): return self #As long as define __next__, the next()...
true
e5ea2965be23486032a8d31ee2bfc01cd8d59126
cryptoaimdy/Python-strings
/src/string_indexing_and_slicing_and_length.py
1,180
4.4375
4
#!/usr/bin/env python # coding: utf-8 # In[35]: # string indexing and slicing s = "crypto aimdy" # printing a character in string using positive index number print(s[5]) # printing a character in string using negative index number print(s[-5]) # In[28]: ##String Slicing #printing string upto 5 characters print(...
true
310c2e0bbde417cbf69ee2768a833c6c3cbdb51a
thonathan/Ch.04_Conditionals
/4.2_Grading_2.0.py
787
4.25
4
''' GRADING 2.0 ------------------- Copy your Grading 1.0 program and modify it to also print out the letter grade depending on the numerical grade. If they fail, tell them to "Transfer to Johnston!" ''' grade= int(input("Please enter your grade: ")) exam= int(input("Please enter your exam score: ")) worth= int(input("...
true
370cfa9c4c18e0345cd14d49f6bc5762886d3b84
SHajjat/python
/binFunctionAndComplex.py
359
4.1875
4
# there is another data type called complex complex =10 # its usually used in complicated equations its like imaginary number # bin() changes to binary numbers print(bin(10000)) # this will print 0b10011100010000 print(int("0b10011100010000",2)) # im telling it i have number to the base of 2 i wanna change to int ...
true
9e3d56ac56705389fedaae15d3598f07fbe20996
axelsot0/Repositorio-1
/PracticaII-2.py
1,713
4.15625
4
print("-----------------------------------------------------------------") print("Ejecicio 2") def opciones(): print(" 1- Convertir grados a Celsius a Fahrenheit 2- Convertir dólar a pesos 3- Convertir metros a pies 4- Salir : ") opciones () accion = input("Elija una opción:") accion = int(accio...
false