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
095c16d2e25fe3e5d076ea09bad8b18c0e0e140a
SastreSergio/Datacademy
/paper_scissors.py
2,815
4.1875
4
#A game of Scissors, paper and stone against the machine import random def choice_player2(): #Function with random for the other player, in this case: the machine options = ['Scissors', 'Paper', 'Stone'] random_choice = random.choice(options) return random_choice def play(choice_player1, choice_player2):...
509b0f82467388b0a8ff219db77d219d4a940b48
wt032320/code
/Python/mytext/insect.py
801
3.578125
4
# insect base class # class Insect(): """The Insect class creates for insect characteristics""" # Initialize Insect class data attributes body = ['head','chest','belly'] def __init__(self, backbone = 'none', exoskeleton = 'chitinous', body=['head','chest','belly'], leg = 'three_jointed_leg_pairs',eyes = 'c...
f5ce69546684d646834366f8693e35a296a8055b
wt032320/code
/Python/mytext/case conversion.py
206
3.984375
4
def normalize(name): return name.capitalize()#capitalize()方法用于将一个字符串的第一个字母变为大写,其余变为小写 L1 = ['adam', 'LISA', 'barT'] print(list(map(normalize,L1)))
f4cfe393b59043b24a9db3d9c775b3d892f92e0f
wt032320/code
/Python/mytext/triangle.py
324
4.03125
4
import math a = int(input('please input a number ')) b = int(input('please input a number ')) c = int(input('please input a number ')) if a+b>c and a+c>b and b+c>a: perimeter=a+b+c print('the perimeter is ',perimeter) pi=perimeter/2 area=math.sqrt(pi*(pi-a)*(pi-b)*(pi-c)) print('the area is',are...
ccc5adbbe89ee97f94be7de64bdf89b5ba67f0d9
nachiketdhamankar/playstore-scraper-moniotr
/play_store_scraper.py
3,358
3.515625
4
#!/usr/bin/python # -*- coding: utf-8 -*- """Script to scrape Google Play Store and save information about apps per category for different countries. Scrapes (using Play Store Scraper - see requirements.txt) the information about the top 100 apps for each category in India and United States of America. Stores the deta...
f1217d5ddd3b8c780f5d08eda75bd31481cd6b38
kissann/Lab1
/five.py
966
4.4375
4
#Задача 5 Задано чотири точки паралелограма за допомогою координат його вершин. # Визначити площу паралелограма та довжину його діагоналей. Результат округлити до тисячних. print("Введите координаты первой точки:") x1= input("x1 = ") y1= input("y1 = ") print("Введите координаты второй точки:") x2= input("x2 = ") y2= in...
99b8130b624d9eb875f91e930feda3cb5766fcac
s3506272/React-Final
/crawler/jobs/Functions.py
3,142
4.03125
4
# function to format a string from '1 of 100 jobs' to '100' # used when returning the number of jobs in a search def format_job_count(tmp_str): # remove whitespace tmp_str = tmp_str.strip() # remove chars on left of number tmp_str = tmp_str[tmp_str.find('of ') + 3: len(tmp_str)] # remove chars on...
a141c79f05ee4dfe9eb04f36e7ce0e2ca59e8fc2
tdounnyy/SampleCodes
/python/helloPython.py
961
4.15625
4
#!/usr/bin/python print 'hello python' print '' print '#\/*\'?:"' # fuck the golden lian print "what do you mean?" print '''hey, son. what`s your name? do \ i\ know # Hail the winterfell you? ''' i = 5 print i print i+1 i=i+1 print i string= '''Which family do you serve? Long live the king!''' print...
e49450bfdb945f7403e7430c4fd187b3c529fe19
vickiedge/cp1404practicals
/prac_01/electricity_bill_estimator_2.0.py
380
3.765625
4
#unsure how to link tariff to constants to call in estimated_bill - ?? TARIFF_11 = 0.244618 TARIFF_31 = 0.136928 tariff = (input("Which tariff? 11 or 31: ")) daily_use = float(input("Enter daily use in kWh: ")) billing_days = int(input("Enter number of billing days: ")) estimated_bill = [11/31] * daily_use * billing_...
27804af36166140fc6655be1c6fd1f60096f34ef
vickiedge/cp1404practicals
/prac_04/quick_picks.py
584
4.125
4
#relied heavily on solution for this exercise. Still not printing all quick picks import random MIN_NUMBER = 1 MAX_NUMBER = 45 NUMBER_PER_LINE = 6 number_of_quick_picks = int(input("How many quick picks? ")) for i in range(number_of_quick_picks): quick_pick = [] for j in range(NUMBER_PER_LINE): numbe...
4eeff59fa2b37e2ad1ad0c3618ad8f011a232cbb
VarunKesarwani/PythonFinance
/MatPlotLib/Oops.py
644
3.921875
4
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 11) y = x ** 2 fig = plt.figure() # Add set of axes to figure axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1) # Plot on that set of axes axes.plot(x, y, 'b') axes.set_xlabel('Set X Label') # Notice the us...
201f05397a98c6a7b3f0a2b7b95b202d4a8d08e5
VarunKesarwani/PythonFinance
/Pandas/Operation.py
699
3.5625
4
import pandas as pd df = pd.DataFrame({'col1':[1,2,3,4],'col2':[444,555,666,444],'col3':['abc','def','ghi','wxyz']}) print(df.head()) print(df['col2'].unique()) print(df['col2'].nunique())#count of unique value #Output: 3 print(df['col2'].value_counts())#count of value in col #Output # 444 2 # 555 1 # 6...
9be175c5586bdad2e2402a2ed03018241fe596aa
einyhime/beginner-project-solutions
/RockPaperScissors.py
1,018
4.0625
4
from random import choice comPoints = 0 userPoints = 0 choices = {'r': 'rock', 'p': 'paper', 's': 'scissors'} wins = ["pr", "sp", "rs"] print("------------------------") print("ROCK PAPER SCISSORS GAME") print("------------------------") while True: comChoice = choice('rps') while True: ...
6dc60bb546052e96de5800a8ea78a28c432808ae
einyhime/beginner-project-solutions
/MeanMedianMode.py
1,540
3.703125
4
import statistics def meanFunc(lst, decimalPlace): if decimalPlace == 0: return sum(lst) / len(lst) else: return round(sum(lst) / len(lst), decimalPlace) def medianFunc(lst): lst = sorted(lst) if len(lst) % 2: return lst[len(lst) // 2] else: return [lst...
f7c3ade65444b8fefc77f36791d78f6766286d4f
tomnt/leet_code
/remove-duplicates-from-sorted-array.py
1,963
3.921875
4
""" 26. Remove Duplicates from Sorted Array https://leetcode.com/problems/remove-duplicates-from-sorted-array/ Runtime: 96 ms, faster than 78.07% of Python3 online submissions for Remove Duplicates from Sorted Array. Memory Usage: 15.7 MB, less than 5.74% of Python3 online submissions for Remove Duplicates from Sorted ...
3373b955f6088a08a1f838dc7ad3cc1bb197ceef
tomnt/leet_code
/others/codility/shortest-compressed-length.py
1,842
4.0625
4
""" The shortest possible length of the compressed representation of a string http://prochal.com/2020/05/the-shortest-possible-length-of-the-compressed-representation-of-a-string/ https://app.codility.com/c/run/DA5DTY-KEN/ Test 1 Test 2: def solution(A): Test 3: def solution(A): """ # you can write to stdout for de...
2fcf0e1e206ae3cbfebd3fbf93e891b823fca081
lvbenson/Neural_Reuse_New
/Eduardo/old_viz/newviz.py
9,804
3.53125
4
import numpy as np import matplotlib.pyplot as plt """ Individual tasks1A. How are resources allocated in a circuit solving a task? Do some tasks use more resources than other ones? How does the circuit solve this task? (how many neurons are necessary and how many are participating) Figure: Impact vs neuron sorte...
b0901e599ce592fb16c823d09ec2d1d02f524990
lvbenson/Neural_Reuse_New
/Eduardo/Figures/Company_Size/Impact.py
10,294
3.625
4
""" Given the set of company projects and a fixed total employee count, how many important employees are required for the success of those projects? Importance defined as: removing the employee would cause project failure to some extent Options Option 0 -- None of the employees are important Option 1 -- All of the e...
f699d600e3fe28ba31785197eeeadfca2debd4b3
sid597/Nand-To-Games
/projects/11/tokenizer.py
11,128
4.1875
4
""" This will be a 2 pass algorithm in 1st pass I will remove all the comments and whitespace. In the 2nd pass will convert the input to tokens. How to implement this ? Can be done by procedural programming or by object oriented style 1. Procedure programming : a) Will make a function to remove the comments from ...
9081d278dd51ca7864172fd40d450f6fc260516e
mphoward/fieldkit
/fieldkit/simulate.py
30,471
3.59375
4
""" Perform simple simulations on meshes. """ from __future__ import division import os import random import numpy as np from . import _fieldkit def random_walk(domain, N, runs, steps, coords=None, images=None, seed=None, threads=None): """ Performs a simple random walk in a domain on a lattice. The random w...
699938f62a9f0d01a1aaa87ae74e9a52b4dbf325
likweitan/data-structure-projects
/search/linear search/linear_search.py
249
4.03125
4
# Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[]. arr = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170] x = 110 for i in arr: if x == i: break print('Element x is present at index 6')
952633b6849f124129920203a24e86bbe3bb19c8
noelduarte/python_band
/artists.py
1,692
3.78125
4
class Musician(object): def __init__(self, sounds): self.sounds = sounds def solo(self, length): for i in range(length): print(self.sounds[i % len(self.sounds)], end= " ") print() class Bassist(Musician): # The Musician class is the parent of the Bassist class def __ini...
d9ac2fef91e6f3ab9c9e511010ac4802383cacb0
adechan/LeetCode-Practice
/882.py
1,314
3.8125
4
# Given two strings s and t , write a function to determine if t is an anagram of s. class Solution: def toDictionary(self, s): result = {} for char in s: if char not in result.keys(): result[char] = 1 else: result[char] += 1 return r...
c3a83d3b3879d8e1440986192900565c74f99a08
adechan/LeetCode-Practice
/578.py
442
3.921875
4
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. class Solution: def containsDuplicate(self, nums) -> bool: if len(nums) == len(set(nums)): ...
3b46e00d83c644bd594a21d320dcd8ac80f834f1
otmoru/lesson02
/work03_02.py
334
3.890625
4
month = int(input('Введите порядковый номер месяца от 1 до 12: ')) calendar = {1: 'зима', 2: 'зима', 3: 'весна', 4: 'весна', 5: 'весна', 6: 'лето', 7: 'лето', 8: 'лето', 9: 'осень', 10: 'осень', 11: 'осень', 12: 'зима'} print(calendar.get(month))
017ff0122a2d38831f15126f917359b57d952c4a
shadunts/data_structures
/graph.py
4,553
4.125
4
from queue import Queue # Implementation of undirected graph using adjacency list class Vertex: def __init__(self, data): self.data = data self.neighbors = {} def add_neighbor(self, v, w=0): self.neighbors[v] = w def get_neighbors(self): return self.neighbors.keys() ...
cbd800f79c957a18f45eda76bed357cc4590c7e6
shadunts/data_structures
/stack.py
2,474
3.859375
4
class Stack: def __init__(self): self.__data = [] self.__size = 0 def __len__(self): return self.__size def push(self, item): self.__data.append(item) self.__size += 1 def pop(self): item = self.__data.pop() self.__size -= 1 return item ...
11ed3a0ab634d3fc1568dbfb38c9d9aff5aced21
introprogramming/exercises
/exercises/fibonacci/fibonacci-iterative.py
735
4.25
4
'''An iterative version, perhaps more intuitive for beginners.''' input = int(input("Enter a number: ")) def fibonacci_n(stop_after): """Iteratively searches for the N-th fibonacci number""" if stop_after <= 0: return 0 if stop_after <= 2: return 1 prev = 1 curr = 1 count = 2...
ba4c0322cd376b673bf7e45429fd5b8c1f21357a
introprogramming/exercises
/exercises/tictactoe/tictactoe.py
3,108
3.515625
4
gameArea = ['_'] * 9 # initialize a gamearea with nine underscore characters. Symbolising empty spot playerOneSign = 'X' playerTwoSign = 'O' players = ["Player1", "Player2"] signs = [playerOneSign, playerTwoSign] def is_busy(position): # determin if the position is occupied already or out of bounds if 0 <= po...
e6ca6a8207216df4ce34d79187e9e41e147ba4b8
introprogramming/exercises
/exercises/talbas/convert.py
657
4.1875
4
# # Decimal to binary (and back) converter # # Usage: # python convert.py bin|dec 100 # import sys def dectobin(dec_string): """Convert a decimal string to binary string""" bin_string = bin(int(dec_string)) return bin_string[2:] def bintodec(bin_str): """Convert a binary string to decimal string""" num = 0 in...
9e5956105dec1a309e045e391785f10f2213f289
introprogramming/exercises
/exercises/plot_2d/multiplot_2d.py
1,837
4
4
import math, pygame, plot_2d from pygame.locals import * # Extension of plot_2d with functionality to plot multiple functions. ############################################# ## Standard colors (RGB) BLACK = (20, 20, 40) WHITE = (255, 255, 255) BLUE = (20, 20, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) CYAN = (50, 255,...
4583ced0b2d1129fbd914eb5b6132d866614ab85
xaldey/OtusLotto
/game_stuff.py
9,433
3.90625
4
from random import randint, shuffle import sys def make_unique_numbers(count, minim, maxim): try: # Создаю пустое множество (для уникальных значений) num_row = set() # Генерю номера от min до max, пока не наполнится # (count элементов) множество if count <= 0: r...
196991085406829f01c4016ccdc5d4d28efc5862
JaideepPrasad/Data-Science
/Python Projects/Sudoku_w_Backtraking/Main.py
2,198
3.84375
4
from Sudoku import Sudoku from GUI import GUI import pygame # Sudoku puzzels with solutions can be found here: # https://www.puzzles.ca/sudoku/ Board = [ # '0' is an empty spot [1, 3, 0, 2, 0, 0, 7, 4, 0], # Row 1 [0, 2, 5, 0, 1, 0, 0, 0, 0], # Row 2 ...
d07c4d7444398e4a91d63f98587e92650c978fad
felipesilva023/flask_app
/exemplos/Exemplo3.py
243
3.96875
4
# coding: utf-8 list1 = [1, 2, 3, 4, 5] num = 1 my_name = 'felipe' if num not in list1: if my_name == 'felipe': print('O seu número não está na lista e o seu nome é felipe.') else: print('O seu número está na lista')
6750bd1eadebde6e64cbe1e9e155c59cafc8442b
felipesilva023/flask_app
/exemplos/Exemplo18.py
238
4.09375
4
def print_vowels(phrase: str) -> list: vowels = ['a', 'e', 'i', 'o', 'u'] found = [] for letter in phrase: if letter in vowels: if letter not in found: found.append(letter) return found
75b49b5e4144e26be79d0e7f19cedfce885894c0
SnehaShree2501/python-Turtle
/turtle-hex.py
367
3.703125
4
import turtle screen = turtle.Screen() screen.bgcolor("black") point = turtle.Turtle() point.color("white") point.pensize(2) point.speed(0) point.penup() point.right(45) point.forward(90) point.right(135) point.pendown() for x in range(120): for y in range (6): point.forward(200) point.right(61) ...
370dc9c96575f67c1d1adb6980e47b9dded4d30b
bailarinbonita/exercises-mit-ocw
/ps1b.py
1,339
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 27 12:32:24 2019 @author: tamar """ annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of your salary to save, as a decimal: ')) total_cost = float(input('Enter the cost of your dream home: '))...
3637a38a0d9dc965c889ede49c0dd4afb257fe7b
zxy1135/git
/printabs.py
117
3.953125
4
# print absolute value of an integer a=input() ##if a>=0: ## print(a) ##else: ## print(-a) print(type(a))
e435dd76259d6ad09b57f30f5b8b3647f565b086
shea7073/Algorithm_Practice
/phone_number.py
495
4.28125
4
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string # of those numbers in the form of a phone number. def create_phone_number(arr): if len(arr) != 10: return ValueError('Array Must be 10 digits long!') for i in arr: if i > 9 or i < 0: ...
8e7c5ae86705f864d636a1e414192f7ddde02755
shea7073/Algorithm_Practice
/code_timing.py
869
3.84375
4
import time import timeit def func_one(n): return [str(num) for num in range(n)] def func_two(n): return list(map(str, range(n))) # Current time start_time = time.time() # Run code result = func_one(10000000) # Record time after code end_time = time.time() elapsed_time = end_time - start_time print(elapse...
bc7d09adfc92bc644d3f7b407ffd0b83897dc11e
Zahidsqldba07/Python-Examples-2
/OOP Python/Book Store App OOP/FrontEndOOP.py
4,303
3.578125
4
""" A programme that stores of book's information below, """ from tkinter import * from BackEndOOP import DatabaseHelper class FrontEnd(object): def __init__(self,window): self.window = window self.window.wm_title("Book Store") self.databaseHelper = DatabaseHelper() lblTitle = Label...
de27667c7ab23c20b5da9bcb80f641bbd446771b
highgateschool/tkinter-miscellany
/responsive_button.py
540
3.53125
4
import tkinter as tk root = tk.Tk() root.geometry( '200x200' ) label_text = tk.StringVar() label_text.set( 'Hello World' ) root.grid_columnconfigure( 0 , weight = 1 ) root.grid_rowconfigure( 0 , weight = 1 ) root.grid_rowconfigure( 1 , weight = 1 ) my_label = tk.Label( root , textvariable = label_text , ...
c163a781929f6cdd5f922018ddfe2ec920075773
RaOne009/Python_oops
/method.py
573
3.53125
4
class Employee: increase = 1.5 def __init__(self,fname, lname, income): self.fname = fname self.lname = lname self.income = income #todo nothing use pass (kush ni) pass def increase(self): self.income = self.income * self.increase @classmethod def change_increme...
0fece841a15917402861006ea23e086a34082f1c
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap14_Funcoes/menu_restuarante_copy.py
2,474
4.09375
4
pedidos = [] valores = {'Lasanha':50, 'Penne':45, 'Ravioli':40, 'Spagheti':35 } # cardapio de carnes def carnes(): global pedidos print('Nosso cardápio de Carnes') escolha = input("""Selecione um dos nossos pratos: 1 - Carne de Panela 2 - Cont...
6e27d99fcad36eb38178f911580f322b9db9e747
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap07-estruturas_de_repeticao/revisao.py
1,093
3.734375
4
# #revisao # # # variaveis # # estruturas de dados compostas (listas, tuplas, dicionarios e sets) # # estruturas de decisao, if, elif e else # # estruturas de repeticao # # fruta = 'maça' # variaveis # # # estruturas de decisao # if fruta == 'banana': # print('Bananas são fonte de potássio') # elif fruta == 'maça':...
51598095741bb274f8980e52b946eb194967abdf
frclasso/CodeGurus_Python_mod1-turma1_2019
/atividades/menu_restaurante2.py
4,284
4.0625
4
#!/usr/bin/env python3 # -*-coding:utf-8 -*- def menu_massas(): print('Nosso cardápio de massas') escolha = input("""Selecione um dos pratos: 1 - Lasanha 2 - Penne 3 - Ravioli 4 - Spaghetti 0 - Para voltar p...
f619f9942ad4af68e1a9ef369d0f4b036f41cc1a
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap18_Tkinter/07_label.py
520
3.671875
4
from tkinter import * root = Tk() root.title("Lables") label = Label(root, text="Hey, How are you doing?", relief=RAISED) label.pack() Label(root, text='Sufficient width', fg='white', bg='purple', relief=RAISED).pack() Label(root, text='Width of x', fg='white', bg='green', relief=RAISED).pack(fill='x') Label(root,...
f6a6fe07b1678d57b8b3d600b2dfe9b84458313b
frclasso/CodeGurus_Python_mod1-turma1_2019
/atividades/imc_cris.py
1,218
4.15625
4
#imc = peso / altura * altura #input #criar um menu com osparametros print('Vamos calcular seu Indice de massa corporal!') input('Digite Enter para comecar!') altura = 0 peso = 0 while peso<=0: peso = float(input('Por favor digite seu peso: ')) if peso<=0: print('Digite um valor maior que 0!') whi...
ce1e6e0b36c9f3b099f69af172c9a8b837012d27
frclasso/CodeGurus_Python_mod1-turma1_2019
/Cap14_Funcoes/script4.py
143
3.515625
4
# argumentos de funções def multiplica(x, y): # argumentos requeridos x, y return x * y resultado = multiplica(4,5) print(resultado)
f651bb872a02e68ee9293d2279e5586a8b5aa251
frclasso/CodeGurus_Python_mod1-turma1_2019
/atividades/cadastro2.py
657
3.734375
4
# print('Esse programa foi importado com sucesso') def inserirDados(): nome = input('Digite seu nome: ') sobrenome = input('Digite seu sobrenome: ') email = nome.lower() + '.' + sobrenome.lower() + '@email.com' return nome, sobrenome, email pessoas = [] # variavel global def cadastrar(): pess...
26947952274161f99d73974e5c1dfb3710829025
RobertoLocatelli02/Python-Learning
/Estrutura de repetição/somaPares.py
136
4.21875
4
somaNum = 0 for i in range(6): num = float(input("Informe um número: ")) if num % 2 == 0: somaNum += num print(somaNum)
8adee0c0c6fff8ed9d9b5cbba036fa1b4dfd5bd6
RobertoLocatelli02/Python-Learning
/funções/fatorial.py
710
3.828125
4
def calculaFatorial(numero, mostrarCalculo = True): fatorial = 1 for i in range(numero, 0, -1): if mostrarCalculo: if i > 1: print(f'{i} x ', end = '') else: print(f'{i} = ', end = '') fatorial *= i return fatorial def pegaValor(): ...
715fd15e50c213ee5fa744d655c1c73074f4d309
RobertoLocatelli02/Python-Learning
/Estrutura sequencial/ConversãoMCm.py
102
3.8125
4
metros = float(input("Informe um número:\n")) print(f"{metros} metros = {metros * 100} centímetros")
0cc8ea87f6c8e233490078a7e4dea5d8881f7787
RobertoLocatelli02/Python-Learning
/dicionarios/aprimorandoCadastroDeJogadores.py
1,223
3.546875
4
dados = {} time = [] partidas = [] while True: dados.clear() partidas.clear() dados['nome'] = input("Nome: ").strip().capitalize() quantPartidas = int(input(f"Quantas partidas {dados['nome']} jogou? ")) for i in range(quantPartidas): partidas.append(int(input(f'Quantidade de gols na partida...
c8442fc43843d28363fc01809e25e6c94f0f6235
RobertoLocatelli02/Python-Learning
/listas/validandoExpressoesMatematicas.py
378
3.828125
4
expressao = input('Digite a expressão: ') lista = [] for simbolo in expressao: if simbolo == '(': lista.append('(') elif simbolo == ')': if len(lista) > 0: lista.pop() else: lista.append(')') break if len(lista) == 0: print('Sua expressão é válida...
bce9e4c4b190adcb14732535162d07f4b8682cc2
RobertoLocatelli02/Python-Learning
/listas/listaUnicaParesImpares.py
342
3.890625
4
numeros = [[], []] for i in range(7): valor = int(input(f'Digite o {i}º número: ')) if valor % 2 == 0: numeros[0].append(valor) else: numeros[1].append(valor) numeros[0].sort() numeros[1].sort() print(f'Os valores pares digitados foram: {numeros[0]}') print(f'Os valores ímpares digitados fo...
2b26b1980b92f0a00035015798310ecfb7a8e325
RobertoLocatelli02/Python-Learning
/funções/contador.py
1,054
3.953125
4
def contador(inicio, fim, passo): if inicio < fim: contador = inicio while contador <= fim: print(contador, end = ' ') contador += passo else: contador = inicio while contador >= fim: print(contador, end = ' ') contador -= passo de...
e3cf65512d10ae99f2c7d0733eee0e599a6567cd
RobertoLocatelli02/Python-Learning
/listas/dividindoLista.py
465
3.78125
4
lista = [] listaPar = [] listaImpar = [] while True: lista.append(int(input("Digite um número: "))) op = input('Deseja continuar?\n').strip().upper() if op != 'S': break for i in lista: if i % 2 == 0: listaPar.append(i) else: listaImpar.append(i) print("-=" * 30) print(f'L...
df32c76047b9939fd8ce056f0ff8c1eef8dc1c4e
RobertoLocatelli02/Python-Learning
/tuplas/contandoVogais.py
540
3.734375
4
lista = (input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digite uma palavra: ").lower(), input("Digit...
facfb27c2bf2432ee02a768abd0b3f24506cdc86
RobertoLocatelli02/Python-Learning
/Estrutura de decisão/DiasDaSemana.py
301
3.796875
4
op = int(input("Menu de opções: \n1- Domingo \n2- Segunda-feira \n3- Terça-feira \n4- Quarta-feira \n5-Quinta-feira \n6- Sexta-feira \n7- Sabado\nOpção: ")) if op == 1 or op == 2 or op == 3 or op == 4 or op == 5 or op == 6 or op == 7: print("Valor válido") else: print("Valor inválido")
d0aa39d37b3e202d577855b009b370537f9d4b8d
RobertoLocatelli02/Python-Learning
/funções/votacao.py
786
4.0625
4
from datetime import date anoAtual = date.today().year def voto(ano): idade = anoAtual - ano if idade < 16: return f'Com {idade} anos, a pessoa não vota ainda' elif idade >= 16 and idade < 18: return f'Com {idade} anos, o voto torna-se opcional' else: return f'Com {idade} anos...
c2909877c8175fa366564b477c47e175d6efc447
RobertoLocatelli02/Python-Learning
/Estrutura sequencial/AreaDeCirculo.py
122
4.03125
4
import math raio = float(input("Informe o raio do círculo: ")) print(f"área do círculo = {math.pi * math.pow(raio,2)}")
c740e8bdc7791f4ad07ef59dd7fe22d1b3d4109b
gy09/python-learning-repo
/PythonLearning/FunctionLearning/Func_1.py
351
3.796875
4
def addi(a, b): return a + b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b def expon(a, b): return a ** b a = float(input("Enter the value of num1")) b = float(input("Enter the value of num2")) print(addi(a, b)) print(sub(a, b)) print(mul(a, b)) print...
1e39b97b27ae437f614cb3b46c9467d64cca05a3
gy09/python-learning-repo
/pythonSelenium/read excel.py
433
3.71875
4
import xlrd # reading the excel file workBook = xlrd.open_workbook("DataFile.xlsx") # selecting the sheet sheet = workBook.sheet_by_name("login") # counting the row count row_count = sheet.nrows # counting the column col_count = sheet.ncols # reading the value from the excel for row in range(1, row_count): User...
dd7aa50d126ddab75b24da79f3b0ac1b0d61bcf3
gy09/python-learning-repo
/PythonLearning/FunctionLearning/forLoop.py
290
4.15625
4
def upperConversion(): sentence = input("Enter the sentence to loop on:") for word in sentence: print(word.upper()) def listLoop(): friends = ["test1","test2","test3","test4"] for friend in friends: print(friend.upper()) upperConversion() listLoop()
22271eb7dc1eb82a66c8d8e110d6af027bec5e98
yozeff/Python
/indexOfCoincidence.py
1,512
3.5625
4
#Joseph Harrison 2019 import timeit #index of coincidence of english ICEnglish = 0.0686 ALPHABET = 'abcdefghijklmnopqrstuvwxyz' #linear time complexity def index_of_coincidence(text: str) -> float: #record occurences of each character occurences = {char : 0 for char in ALPHABET} for char in text: ...
3cc6b450e94555267ff1f2ba14828ec85a4b1844
cd-public/BST
/autograder.py
3,445
3.75
4
# Autograder # This will attempt to perform intended tasks for Stack. It will only use naturals, for simplicity. # It is not required that your stack work with values other than naturals or only with naturals. # For each task, the autograder will: # - Define some expected behavior for some use case # - Perform the u...
0bbdc2c2ffdb4232f50f71fa6d0fe0e3236f341e
HugoKlepsch/grade12python
/Grade12Python/constellation project/HugoSortStars.py
3,658
3.75
4
import random def insertionSort(origList): sortedlist = [] firstTime = True for origIndex in range(len(origList)): todo = origList[origIndex] if (firstTime): sortedlist.insert(0, todo) firstTime = False else: listLen = len(sortedlist) ...
c7acc17b973cf59e302a6c066f9ebc68ba605e03
julioreis-dev/exercicio-puc2
/2-exercicio1_puc.py
1,319
3.765625
4
def consultar1(valor): if valor % 2 == 0: return 'Par' else: return 'Impar' def consultar2(valor): if valor >= 0: return 'Positivo' else: return 'Negativo' def consultar3(valor): if valor.isdigit(): x = int(valor) if type(x) == int...
ca44c61f44c3190f4b40d2a5c0c27f38c590a900
Manoo-hao/BS32010
/Assignment_2/parsemultalign.py
3,802
3.984375
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Tue Mar 10 10:53:15 2015 @author: dmamartin """ import sys #import module sys if len(sys.argv)!=3: #if the length of the command line arguments passed to python is not 3, print the following statement, then exit the script print """Run this parser with the ...
dc80e3cc49da109afa4011906cbc2fce3aabe571
sejalg1019/project-100-
/atm.py
1,147
3.78125
4
class Atm(object): def __init__(self, name, cardNumber, pin): self.name = name self.cardNumber = cardNumber self.pin = pin def checkBalance(self): print("Your balance is $50,000") def cashWithdrawal(self, amount): newAmount = 50000 - amount print("You h...
24d15ff970b25410dfc83bc35ec529c7fa677dcc
yxh13620601835/store
/yxhday3.8.py
261
3.609375
4
''' 使用while循环实现NxN乘法表的打印。 authur:yxh ''' num=int(input("请输入乘法表的层数:")) i=1 while i<=num: j = 1 while j<=i: print("%d*%d=%d"%(i,j,i*j),end=" ") j += 1 print() i += 1
758b8bec6328bfb4e403b1ea4bd3e12ca235d0b8
yxh13620601835/store
/day10/car.py
2,671
4.4375
4
''' 车类: 属性:车型号,车轮数,车身颜色,车重量,油箱存储大小 。 功能:跑(要求参数传入车的具体功能,比如越野,赛车) 创建:法拉利,宝马,铃木,五菱,拖拉机对象 ''' class Car: __type="" __wheelnum=0 __color="" __weight=0.0 __fuelstorge=0.0 def setType(self,type): self.__type=type def getType(self): return self.__type...
f9c6c33fbd7ee82999cc7cb64bf41190d1b71213
yxh13620601835/store
/day5/yxhday5.1.py
466
3.984375
4
''' dict = {"k1":"v1","k2":"v2","k3":"v3"} 1、请循环遍历出所有的key 2、请循环遍历出所有的value 3、请在字典中增加一个键值对,"k4":"v4" ''' dict = {"k1":"v1","k2":"v2","k3":"v3"} # 1、请循环遍历出所有的key for key in dict: print(key) # 2、请循环遍历出所有的value for key in dict: print(dict[key]) # 3、请在字典中增加一个键值对,"k4":"v4" dict["k4"]="v4...
3b4e09bc64a6a7eb05717961a25a7df5466845a6
yxh13620601835/store
/day10/student1.py
3,312
4.03125
4
''' i. 定义了一个学生类: 属性:学号,姓名,年龄,性别,身高,体重,成绩,家庭地址,电话号码。 行为:学习(要求参数传入学习的时间), 玩游戏(要求参数传入游戏名), 编程(要求参数传入写代码的行数), 数的求和(要求参数用变长参数来做,返回求和结果) ''' class Student: __stuno="" __name="" __age=0 __sex="" __height=0.0 __weight=0.0 __grade=0.0 __address=...
390bf55d9bfdb5269bc91c123835963b8b4e801a
yxh13620601835/store
/yxhday3.4.py
803
3.5625
4
''' 从键盘输入任意三边,判断是否能形成三角形,若可以, 则判断形成什么三角形(结果判断:等腰,等边,直角,普通,不能形成三角形。) author:yxh ''' list=input("请输入三条边的数值:").split(" ") list1=[] for i in range(len(list)): list1.append(int(list[i])) print(list1) a=list1[0] b=list1[1] c=list1[2] if a+b>c and b+c>a and c+a>b: if a==b or b==c or c==a: ...
8bc94bcd27fa27da575349118d7b8881bac7bf11
rodrigovegajaldin/codigo_python
/programas_3/prueba.py
373
3.5625
4
from os import strerror try: stream = open('/home/rodrigo/Escritorio/curso_python/codigo.txt' , 'rt') dato = stream.read() print('dato:',len(dato)) while dato != '': print('dato:',len(dato)) print('este es el dato:',dato,'!!!') dato = stream.read() print('termino de leer') stream.close() except IOE...
ce0514678d172538ccb8706e1d719afdcedf17c6
rodrigovegajaldin/codigo_python
/programas_2/codigo8.py
565
3.734375
4
#este programa practica la herencia #este es un ejemplo de polimorfismo class Nivel1: varia1 = 100 def __init__(self): self.var1 = 101 def fun1(self): return 102 class Nivel2(Nivel1): varia2 = 200 def __init__(self): super().__init__() self.var2 = 201 def fun2(self): return 202 class Nivel3(Nivel2...
bea72ea29e1d1bfd82fbdf50decb7880d47c2927
rodrigovegajaldin/codigo_python
/programas_2/codigo7.py
772
3.90625
4
#este programa practica las clases orientadas a objetos y las pilas #esta clase hace una pila class Pila: def __init__(self): self.__listaPila = [] def push(self, val): self.__listaPila.append(val) def pop(self): val = self.__listaPila[-1] del self.__listaPila[-1] return val class SumarPila(Pila...
8589c2bb7df1a48d53bee5b9c401b9cd5f7d8618
msharp9/DailyChallenge
/march.py
3,537
3.5625
4
# random case function from random import random def random_case(x): return ''.join([l.upper() if random() < 0.5 else l.lower() for l in x]) # string cleaning def correct(string): return string.replace('0', 'O').replace('1', 'I').replace('5', 'S') # or def correct(string): return string.translate(str.mak...
81c1f596f7fc464d654f5cbab423833ae1c63185
JLSchol/counting_cards
/src/black_jack_simulator/deck_of_cards.py
1,701
3.765625
4
import random class Card(): def __init__(self, rank, suit, value=None): self.rank = str(rank) self.suit = str(suit) self.id = rank+suit self.value = value def show(self): print("{} of value: {}\n".format(self.id, self.value)) class Deck(): def __init__(self, nr_decks=1): self.nr_decks = nr_decks se...
025255c6489265a53a0c309bc70e73e7853e0dff
Dani340/Pythoncoding
/ex18.py
61
3.796875
4
n =input("n= ") while n > 0: print (2 * n) n =input("n= ")
d5a18f6d143e15cbe2f320235825b121504edfc9
Dani340/Pythoncoding
/ex8.py
137
3.765625
4
a = input("a= ") b = input("b= ") if a > b: print ("a este mai mare") elif b > a: print ("b este mai mare") else : print ("sunt egale")
ae6847de2e97e25bfb752572365ae4bb5eb6974a
Dani340/Pythoncoding
/ex9.py
75
3.65625
4
sum = 0 for i in range (0,20): if i % 6 == 0: sum = sum + i print (sum)
acfff7421c86194026bc9c757ec0b4da14debc2d
valdadyne/python-snippets
/Sorting/sort.py
274
3.953125
4
''' This is a Python Snippet that sorts data in a JSON file based on the first_name ''' import json temp = [] dictList = [] with open('file.json') as data_file: data = json.load(data_file) s = sorted(data.keys()) for key in s: print(key, data['Users'])
58427134d8e43d8d8bd6336724c554674582b0b2
cmathi/PythonRepo
/PythonBasics/5.IFCondition.py
179
4.03125
4
x=5 print('Before 5') if x ==5 : print('Before 5') print('Here i am',x) print('After 5') if x==6: print ('Before 6') print('Here i am',x) print('After 6')
5e8fb7d3cfac98fef0b2605de1674e27a5b87479
cmathi/PythonRepo
/PythonBasics/36.CountRepetitionOfWordsEasyThruPrompt.py
164
3.890625
4
word = dict() text = input('Enter the text : ') names = text.split() print('words are :',names) for name in names : word[name] = word.get(name,0)+1 print(word)
308251b65e13ff2d2ca55034c66f27f928a1eb8b
cmathi/PythonRepo
/PythonBasics/41.TuplewithSorted.py
100
3.6875
4
d={'b':10,'c':21,'a':11} t= sorted(d.items()) print(t) for k,v in sorted(d.items()): print(k,v)
18ccd3d9b4d52437c9668191df14930b5f1d2e65
cmathi/PythonRepo
/PythonBasics/7.ElseIfCondition.py
251
3.90625
4
x = 1 if x<2: print ('Less than 2') elif x<4: print('Less than 4 ') elif x<6: #If any one of the elif runs will leave the remaining elifs print('Less than 6') elif(x<8): print('Less than 8') elif(x<10): print('Less than 10')
0d71e1575a90d36f477f8b7b72510b8912305e1f
akima9/algorithm
/baekjoon_2562.py
110
3.578125
4
a = [] for i in range(9): a.append(int(input())) maxNum = max(a) print(maxNum) print(a.index(maxNum) + 1)
5b10eb4ea0be1171959a29bf10969ffff2261051
akima9/algorithm
/baekjoon_1110.py
214
3.53125
4
N = int(input()) temp = N cnt = 0 while True: left = temp // 10 right = temp % 10 temp = left + right temp = int(str(right) + str(temp % 10)) cnt += 1 if N == temp: break print(cnt)
11d25348b29bdd293ae1abb370cd2b5a66756e22
rexius41/test_ness
/Hello_World_file_input.py
205
3.53125
4
try: file_test = open("test.txt","w+") except: print ("error while opening/creating file") for i in range(10): print (i) file_test.write(input()) file_test.write(" ") file_test.close()
b0269036d700756b5508c2a33677f2f85b4e794d
rexius41/test_ness
/InputWrite.py
240
3.5
4
try: file_test = open("test.txt","w+") except: print ("error while opening/creating file") x = int(input(">>nuber of inputs")) for i in range(x): print (i) file_test.write(input()) file_test.write(" ") file_test.close()
6f672fdf0186e26a79c9b26a4cae4a9662e01825
druyz/python-4linux
/python-4linux/python-fundamentals/Aula02/func4.py
357
4.09375
4
#!/usr/bin/python3 # Usando lambda ( é uma funcao anonima ) para calculos matematicos # Guardo em memoria a = lambda x, y: x + y # Guarda na variavel a(1,6) # Imprime a posicao na memoria # print(a) # Executa somente se chamado pelo proprio arquivo, nao é executado caso feito o import if __name__ == "__main__": ...
ed8da4c0f151b0d941097fdd04265bd84abb6251
xunxia/DBMS-Python
/project/frontEnd.py
7,460
3.59375
4
import sys import actions import os def showMenu(): print("\nSlice DB Menu\n") print("1.Create Database") print("2.Update Record") print("3.Add record") print("4.Delete Record") print("5.Bulk load") print("6.Display Join") print("7.Run Query") print("8.Report 1") p...
72227ce1f22e70c2e3c83cbf091ab93bd0cdecc6
Abanaser/Games
/guessing_game.py
5,281
4.21875
4
from random import * def intro(): """ intro function to describe the rules, and how to play the game""" print("Hello my friend, we will play a guessing game can you beat me?") print("Here are the rules,") print("1: We choose a number between 1 and a 100 and keep it in our mind.") print("2: We ...
c03e48d2e52bdeba72621f76ed49d7d95ca0139f
growupboron/UnderstandingOpenCV
/opencv3.py
1,596
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Dec 23 23:38:44 2018 @author: aman """ import cv2 import numpy as np ########################## COLOR SPACE HSV ############################## # HSV is particularly useful for color filtering. image = cv2.imread('./images/input.jpg') hsv_image = c...
95d635c91008f65fc85f93fed75c49c9d3aecfae
Ankan54/basic_python_practice
/Tic-Tac-Toe Game/player.py
3,250
3.90625
4
""" player classes for the game """ import math import time import random class Player: #base player class def __init__(self, letter): self.letter= letter #letter can be X or O def get_move(self,game): pass class ComputerPlayer(Player): def __init__(self,letter): super().__i...
36b80ff933eeb290a7714bca486c842d79d03c89
SaifAlDeenSamehMahrous/PortOpener
/ports.py
967
3.703125
4
import socket class ports: def __init__(self ,port): self.sock = socket.socket() self.host = socket.gethostname() self.port = port self.socketinfo = (self.host ,self.port) def setnewport(self ,port): self.port =port def isopen(self): try: self.s...
55ca9cdc9b8bb6ba956facf01556a4b66e70e52a
jwei7er/machine_learning
/NaiveBayes/attribute.py
2,613
3.6875
4
# Author: Jordan Weiler # Date: February 7, 2013 # # The Attribute class holds binary counts for the attribute value in relation to the class value. # class Attribute: def __init__(self, name): self.name = name self.zero_zero = 0 self.zero_one = 0 self.one_zero = 0 self....