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 |
|---|---|---|---|---|---|---|
3080a293a7af5caa9cdc2b02ca90ad5b38de3f1f | diegocolombo1989/Trabalho-Python | /Revisao2/Ex2pessoa.py | 969 | 4.09375 | 4 | # Crie uma classe pessoa contem 3 atributos e 7 metodos
class Pessoa:
def __init__(self, nome:str, sobrenome:str, idade:int) -> None:
self.__nome = input('seu nome: ')
self.__sobrenome = input('seu sobrenome: ')
self.__idade = 0
if type(nome) == str:
self.__nome = nome
... |
9a663800a3297b241c303872727654ff573595c6 | rGustave07/python-tictactoe | /main.py | 3,074 | 4 | 4 | # tic tac toe game
import random
global current_player
current_player = 'X'
board = ['hold', '1', '2', '3', '4', '5', '7', '7', '8', '9']
def print_board(board):
print("Enter the corresponding number on the keyboard to make your selection!\n")
print(" | | ")
print(" "... |
640f5f36dffbd5cda416c28282172fd71341eb2f | Lewixx/lewypython | /dzien4/slownik-zakupy.py | 309 | 3.609375 | 4 | zakupy = {}
zakupy["chemia"] = ["ace", "plyn do naczyn", "szampon"]
zakupy["nabial"] = ["mleko", "maslo", "sereeek"]
print(zakupy)
for k in zakupy.keys():
print(f"klucz: {k}")
for v in zakupy.values():
print("wartosci", v)
for i, h in zakupy.items():
print("klucz", i, "wartosci to ", h)
|
3658b398a582a550c566e46c3146cc9e69063ecd | Lewixx/lewypython | /dzien10/towar.py | 775 | 3.9375 | 4 | class Towar(object):
def __init__(self, nazwa, kolor, cena):
self.nazwa = nazwa
self.kolor = kolor
self.cena = cena
#overright - nadpisana metoda w obiekcie
def __str__(self):
return f'{self.nazwa.capitalize} {self.kolor} {self.cena}'
# def __add__(self, other):
# ... |
f7e4eb59b30039028608c83098f874b1f1d8db83 | Lewixx/lewypython | /dzien3/petla-for.py | 259 | 3.8125 | 4 | #listy sa mutowalne
zakupy = ["piwo", "kielba", "cebula", "krewetki", "jajka"]
#konkretna ilosc
for i in range(10):
print("eloo lewix")
for j in range(8):
print("moja lliczba to ", j**3)
for i in zakupy:
print(f"musze kupic: {i.capitalize()}")
|
0acbad19ec29c8ce0e13d9d44eff09759e921be0 | Patrick-J-Close/Introduction_to_Python_RiceU | /rpsls.py | 1,779 | 4.1875 | 4 | # Intro to Python course project 1: rock, paper, scissors, lizard, Spock
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# where each value beats the two prior values and beats the two following values
import random
def name_to_number(name):
# convert string input to integer value
if name == ... |
b70510e76cd5c560e7ad4109b893b8d9b3ef7048 | Looble/Blackjack-2.0 | /game_logic.py | 5,595 | 3.65625 | 4 | from cards import card, deck, shoe
class player:
def __init__(self, name, *args, **kwargs):
self.score = 0
self.hand = []
self.name = str(name)
def get_name(self):
"""
Return the player's name
"""
return self.name
def get_score(self):
"""
... |
173b7fd651e7fac51eb3c0cbfd1d52ab14c9bf40 | avi527/Basic-oops | /count_instance.py | 200 | 3.8125 | 4 | class Person:
instance_count=0
def __init__(self,name):
Person.instance_count+=1
self.name=name
p=Person('avinash')
p1=Person('avinash')
print(Person.instance_count)
|
801212ca8b348b5b01ffe02971ad9305a655eb5a | avi527/Basic-oops | /instance_method.py | 581 | 3.71875 | 4 | class Person:
def __init__(self,first_name,last_name,age):
self.first_name=first_name
self.last_name=last_name
self.age=age
def full_name(self):
return self.first_name + ' '+self.last_name
def check_age(self):
if (self.age>18):
return True
p1... |
264595d7a6d62fa80cb0091dd5d6daa4c6dae583 | Prasanthdemigod/Python_Ex2 | /Ex_5.py | 735 | 3.8125 | 4 | '''
To implement a program that parses a program with HTML tags, with attributes too
'''
import sys
import Stacks
def html_tags(raw_code):
stk = Stacks.LimitedStack()
j = raw_code.find('<')
while j != -1:
k = raw_code.find('>', j+1)
if k == -1:
return False
tag = raw_code[j+1:k]
if not tag.startswith... |
41ad33f73f1e766b17dcb98a3755f0ef162fdced | KIMSIYOUNG/Algorithm-study | /grouping/dp/Fibo.py | 129 | 3.671875 | 4 | def fibo(value):
if value == 1 or value == 2:
return 1
return fibo(value - 1) + fibo(value - 2)
print(fibo(4))
|
e032b3741971024ab77674a3b95686fb87d94697 | KIMSIYOUNG/Algorithm-study | /programmers-1/DivideArray.py | 610 | 3.65625 | 4 | '''
파이썬에서 문자열, 튜플, 리스트가 비어있는 경우 False를 반환한다.
return문에서도 and | or 를 사용하면 boolean 유무를 판단하여 리턴한다.
둘을 합치면 return answer or -1 이 가능하다.
- answer가 빈 리스트가 아니면 true이기에 그냥 리턴하고,
빈 리스트라면 false를 리턴하여 or 뒤의 구문이 실행된다.
'''
def solution(arr, divisor):
answer = sorted([v for v in arr if v % divisor == 0])
return answer or ... |
40f32ad069b650d62bee37caedaf910b1d8a3229 | cpe202spring2020/lab0-ainsleymuir | /planets.py | 258 | 3.65625 | 4 | def weight_on_planets():
earth=float(input('What do you weigh on earth? '))
print('\nOn Mars you would weigh %.2f pounds.\nOn Jupiter you would weigh %.2f pounds.' %(earth*0.38, earth*2.34))
if __name__ == '__main__':
weight_on_planets() |
99c532b4453e4318f3c12c4746140d9a718aa96b | Dsmit05/Some_algorithms | /algoritms_sort/Аlg_sort.py | 3,486 | 3.90625 | 4 | import random
def buble_sort(arr):
# Пузырьковая сортировка
# от O(n^2) до O(n)
for i in range(len(arr) - 1, 0, -1):
for j in range(i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def insertion_sort(arr):
# Сортировка вставками
... |
ee8ff8648e324b2ca1c66c4c030a68c816af1464 | Merrycheeza/CS3130 | /LabAss2/LabAss2.py | 1,331 | 4.34375 | 4 | ###################################
# #
# Class: CS3130 #
# Assignment: Lab Assignment 2 #
# Author: Samara Drewe #
# 4921860 #
# #
###################################
#!/usr/bin/env python3
import sys, re
running = True
# prints the menu
print("--")
print("Phone Number ")
print(" ")
while(r... |
0382a9f59b7eda2a10d2cd97e2e86bccd2ab380d | AhmarBaig/WebScraper | /main.py | 2,224 | 3.53125 | 4 | # Imports
import requests
from bs4 import BeautifulSoup
from googlesearch import search
import json
# Input to website
searchQuery = "phones" #input("What are you looking to buy? Use this search like you use Google to buy something. The more descriptive your query is, the more accurate the search results are: ")
# ... |
80a8d27bc2d7a21db06957042ad6da17f04d941f | Swetapadma94/Kaggle | /kaggle-house price-data analysis-part1.py | 5,707 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# Display all the columns of the data frame
pd.pandas.set_option('display.max_columns',None)
# In[3]:
data=pd.read_csv(r... |
30e22c55bb0fe9bd5221270053564adbe4d83932 | ine-rmotr-projects/INE-Fractal | /mandelbrot.py | 854 | 4.21875 | 4 | def mandelbrot(z0:complex, orbits:int=255) -> int:
"""Find the escape orbit of points under Mandelbrot iteration
# If z0 isn't coercible to complex, TypeError
>>> mandelbrot('X')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/davidmertz/git/INE/unittest/0... |
253a6287010528e97afa3ba3f83b39600ba66495 | knowit/granada-python-ws | /simpleplot.py | 689 | 3.625 | 4 | # coding: utf-8
import io
import matplotlib.pyplot as plt
def plot(points):
"""
Plots an iterable of points onto a matplotlib Figure object
A point is an n-tuple with one x value and one to n y value(s): (x, y, y1, y2, y3, ... yn)
"""
fig, ax = plt.subplots(1)
formatted = list(zip(*points))
... |
4c31a52ac95dbaf77791140bc67d888c95a380f6 | andresfelipe9619/algorithm-workshops | /lab1-diana/punto1.py | 1,712 | 3.78125 | 4 | #ALGORITMIA GRUPO 03
#LABORATORIO 1 - PUNTO 1
#NOVIEMBRE 10 2019
#PROF: DIANA LOZANO
#AURA JULIETH HINOJOSA MUÑOZ – 1626392-3752
################################################################
#Defino funciones
def calculaPotencia(voltaje, rt):
potencia = (voltaje * voltaje) / rt
return potencia
def calcul... |
07330d86401fcad647b44df60f04dbae68e0019f | RShang97/Propositions | /propositions.py | 10,138 | 3.9375 | 4 |
from enum import Enum # requires Python >= 3.4
'''
program that provides general suite of functions for representing and manipulating propositions
'''
#----------------------------
# reduce function. Takes an iterable and reduces it to one value by applying a function to all the items in the iterable
#---------... |
468be130b55acbc1be1625b75702010bb77dd314 | sawildonger/wcc | /wcc/rps.py | 1,606 | 3.953125 | 4 | import random
def check_move(move):
if move == 'rock':
return True
elif move == 'paper':
return True
elif move == 'scissors':
return True
else:
return False
def get_player_move():
player_input = raw_input('Pick your move: rock, paper, or scissors?')
while check_move(player_input) == Fa... |
9c8edde09cbe6abe66d270836bd31922189d6aaf | bharath210/PythonLearning | /MatrixDemo.py | 304 | 3.78125 | 4 | from numpy import *
num1 = array([
[1,2,3,4,5,6],
[1,2,3,4,5,6]
])
mx1 = matrix(num1)
print(mx1)
mx2 = matrix('1 2 3 ; 4 5 6 ; 7 8 9')
print(mx2)
mx3 = matrix('1 4 3 ; 7 5 6 ; 1 3 9')
print(diagonal(mx2))
mx4 = mx2 * mx3
print(mx4) |
257f2d67b700463e128b2251d285e8ce53065b6f | bharath210/PythonLearning | /Assignments/FibonacciDemo.py | 388 | 4.15625 | 4 |
def fibb(n):
num1 = 0;
num2 = 1;
temp =0
if(n == 1):
print(num1)
else:
print(num1)
print(num2)
for i in range(2,n):
num3 = num2 + num1
# if n <= num3:
# break
print(num3)
temp = num3
num1 = num2... |
040c18be4111f028692c969a7dbbfc60e6ff959b | bharath210/PythonLearning | /Assignments/LinearSearch.py | 251 | 3.625 | 4 | pos = -1
def search(list,n):
for i in list:
global pos
pos += 1
if i == n:
return True
return False
nums = [10,2,3,4,5,6]
n = 4
if search(nums,n):
print('Found at',pos+1)
else:
print('Not Found') |
3286d9f6043530b8078b94f4b0721849d7e1198a | mretersdorf/PracticeExercises | /10.py | 629 | 4.09375 | 4 | # Question 10: Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list
def combine_lists(list1, list2):
new_list = []
for i in list1:
if i % 2 == 1:
new_list.append(i)
for x in list2:
... |
f29f301157ad32c624fa6de921616e09ca74e5c4 | ayushdpsg12/binary-search | /binary_search.py | 663 | 4.09375 | 4 | def BinarySearch(arr, lower, higher, key):
if higher >= lower:
mid = (lower+higher)//2
if arr[mid] == key:
return mid
elif arr[mid] > key:
return BinarySearch(arr, lower, mid-1, key)
else:
return BinarySearch(arr, mid+1, higher, key)
e... |
0d24827c20ed97cbdf445f2691554cac1b99f8c8 | naochaLuwang/Candy-Vending-Machine | /tuto.py | 1,288 | 4.25 | 4 | # program to mimic a candy vending machine
# suppose that there are five candies in the vending machine but the customer wants six
# display that the vending machine is short of 1 candy
# And if the customer wants the available candy, give it to the customer else ask for another number of candy.
av = 5
x = int(input("... |
7060bf2821895a6ea490cdfff57e8fefc59ebaea | hast3d/Exercises | /Extracting_Digits.py | 103 | 3.953125 | 4 |
#input a number
num = int(input())
# output the last digit of the number
newnum = num%10
print(newnum) |
4de32a5c4d1e84ae597dfe51d2e5f8f55f37f5ea | Dmdv/CS101 | /Unit6/fibonacci.py | 211 | 3.921875 | 4 | __author__ = 'dmitrijdackov'
dic = {0:0, 1:1}
def fibonacci(n):
if n in dic:
return dic[n]
value = fibonacci(n - 1) + fibonacci(n-2)
dic[n] = value
return value
print (fibonacci(36)) |
789ac887653860972e9788eb9bc2d7c4e6064abc | Sajneen-Munmun720/Python-Exercises | /Calculating the number of upper case and lower case letter in a sentence.py | 432 | 4.1875 | 4 | def case_testing(string):
d={"Upper_case":0,"Lower_case":0}
for items in string:
if items.isupper():
d["Upper_case"]+=1
elif items.islower():
d["Lower_case"]+=1
else:
pass
print("Number of upper case is:",d["Upper_case"])
print("Numbe... |
411141a33ac9acddd7c19f64a17794ff5af38d49 | Sajneen-Munmun720/Python-Exercises | /Printing even number from a list.py | 196 | 3.90625 | 4 | def even_list(list):
even_number=[]
for items in list:
if items%2==0:
even_number.append(items)
return even_number
print(even_list([1,2,3,4,5,6,10,20,49,50])) |
e77f81634fe80477ab44cc0a79fadc0c78d90d8f | yongge666/advancePython | /collectios.py | 446 | 3.671875 | 4 | # coding:utf8
import bisect
from collections import deque
# 一.deque
#用来处理已排序的序列,用来维持已排序的序列, 升序(二分查找)
## 1.通过bisect维护一个有序的deque
inter_list = deque()
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)
print(bisect.bisect_left(i... |
90c05b719fb809350fedb8a4dbd5f4438a14c05b | yongge666/advancePython | /Thread_sync.py | 689 | 3.75 | 4 | # coding:utf8
# 线程同步
# lock在同一个线程(函数)里面只能有一个acquire 和 release
# Rlock在同一个线程(函数)里面要有相同数目的acquire和release
from threading import Thread,Lock,RLock
total = 0
lock = RLock()
def add():
global total
global lock
for i in range(100000):
lock.acquire()
total += 1
lock.release()
def desc():
... |
5ff32c6cefc906558fc0d3f9132f2e7f8e5a8acb | yongge666/advancePython | /class_var.py | 221 | 3.8125 | 4 | # coding:utf8
class A:
b = 1
def __init__(self, x, y):
self.x = x
self.y = y
a = A(2,3)
a.b = 100 #改变的是实例变量
print(a.x,a.y,a.b)
print(A.b) # 类变量可以直接通过类名访问
|
13b4788968d5b4576dc47f2b3cb459e835d3f869 | frishkorn/lottoScripts | /lib/lottoAnalysis.py | 1,834 | 3.953125 | 4 | #!/usr/bin/env python3
import re
from lib import lottoDatabase
# lottoList function creates a list of integers for easier analysis.
def lottoList():
# Call lottoDatabase.py to download current winning numbers.
lottoDatabase.lottoData()
# Load lottoDatabase.txt into list.
with open('lottoDatabase.txt', 'r') as w... |
edf7b53def0fffcecef3b00e4ea67464ba330d9c | Malcolm-Tompkins/ICS3U-Unit5-06-Python-Lists | /lists.py | 996 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on June 2, 2021
# Rounds off decimal numbers
def round_off_decimal(user_decimals, number_var):
final_digit = ((number_var[0] * (10 ** user_decimals)) + 0.5)
return final_digit
def main():
number_var = []
user_input1 = (input("Enter your... |
27b85920a9a7d8d9c2b42f5d3227ffb3f48acda8 | jorgegarba/CodiGo9 | /BackEnd/Semana4/Dia3/09-listas.py | 488 | 4.15625 | 4 | nombres = ["Juan","Jorge","Raul","Eusebio","Christian",100]
nombre = "Eusebio"
# para saber si el nombre esta en nuestro arreglo nombres
print(nombre in nombres)
# Buscar un nombre en esa lista
# for (let i = 0; i< nombres.lenght; i++){
# console.log(nombres[i])
# }
# Por cada nombrecito en nuestra lista nombres, ens... |
60a98ea2fab4158e74e7f8378e0d5c72ea1171c8 | jorgegarba/CodiGo9 | /BackEnd/Semana6/Dia6/02-ejercicio-herencia.py | 1,380 | 3.828125 | 4 | # Tenemos una clase padre llamada Persona que tiene como constructor un nombre, edad, nacionalidad y dni y sobreescribir su metodo str para que me diga lo siguiente : "Hola me llamo ___, tengo ___ años, soy ____ y mi DNI es ___", luego tener una clase hijo que sea Empleado que herede de Persona y que su constructor apa... |
ce0b2c7af0602e780b9f4c4660a8e02c63c3f1a8 | jorgegarba/CodiGo9 | /BackEnd/Semana4/Dia6/03-funciones-anonimas.py | 199 | 3.96875 | 4 | # en python a las funciones anonimas se les pone el prefijo lambda y son funciones de una sola linea de ejecucion.
def sumar(a,b):
return a+b
resultado = lambda a,b: a+b
print(resultado(20,10)) |
b0cac05c7e10244b8a24689a88dfabd7e5223e4c | jcchen-hmc/math189bigdata | /hw1/hw1pr2.py | 3,814 | 3.96875 | 4 | """
Start file for hw1pr2 of Big Data Summer 2017
Before attemping the problem, please familiarize with pandas and numpy
libraries. Tutorials can be found online:
http://pandas.pydata.org/pandas-docs/stable/tutorials.html
https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
This file only has one part: the main ... |
aabdc9c74e87d0e22a9ea1e84c6838c4717146ee | PatrickUncle/python | /文件操作/seek_text.py | 188 | 3.59375 | 4 | # f = open(file = "text.txt",mode="r",encoding="utf-8")
# # data = f.read()
# f.seek(3)
# print(f.read())
f = open(file='text.txt',mode='a',encoding='utf-8')
f.write("hello worldaaaa")
|
f7700a22194096b54ec0ba4d63bb341e87d8c80b | bionictoucan/multi_pow | /utils.py | 2,436 | 3.96875 | 4 | import numpy as np
def segmentation(img, n):
"""
This is a preprocessing function that will segment the images into segments with dimensions n x n.
Parameters
----------
img : numpy.ndarray
The image to be segmented.
n : int
The dimension of the segments.
Returns
------... |
3e78ea8629c13cefe4fdcbf42f475eb4da525b2a | vladbochok/university-tasks | /c1s1/labwork-2.py | 1,792 | 4.21875 | 4 | """
This module is designed to calculate function S value with given
accuracy at given point.
Functions:
s - return value of function S
Global arguments:
a, b - set the domain of S
"""
from math import fabs
a = -1
b = 1
def s(x: float, eps: float) -> float:
"""Return value of S at given point x with gi... |
56ef135a3b8134aa549121b806fc036ddbace3c2 | vladbochok/university-tasks | /c2s1/aos/main.py | 6,248 | 3.546875 | 4 | class MachineInstance:
# constants, built-in settings of processor
REG_SIZE = 18
BYTE_SIZE = 9
INT_MAX = 2 ** REG_SIZE
MAX_BYTE = 2 ** BYTE_SIZE
def __init__(self):
self.stack = []
self.commands = {'add': self.add,
'sub': self.subtracts,
... |
18f7d0efce36f81e2d625089fab7b09871a5f058 | ug2057pz/Tic_Tac_Teo | /prc.py | 230 | 3.609375 | 4 | for i in [0,1,2,3,4]:
for y in ['a', 'b', 'c']:
print(i, y)
total = 0
for i in range(100+1):
total += i
print(total)
number = 0
total = 0
while number <100:
number = number +1
total += number
print(total) |
8dca8f17a5a48fc78abcda5bb4e1fead7e8a2add | IgnacioMazuran/ajedrezMetodologia | /GrupoK-TM/Kaprekar/kaprekar_master.py | 1,198 | 3.734375 | 4 | from kaprekar_mostrarResultado import mostrarResultado
from kaprekar_ascendente import ascendente
from kaprekar_descendente import descencente
casosDePrueba = int(input("Cuantos numeros desea testear? "))
caso=0
while(caso<casosDePrueba):
n = input("\nIngresa un numero de 4 digitos: ")
# Compruebo que teng... |
6f0bc83046ec214818b9b8cc6bc5962a5d819977 | thivatm/Hello-world | /Python/Counting the occurence of each word.py | 223 | 4.21875 | 4 | string=input("Enter string:").split(" ")
word=input("Enter word:")
from collections import Counter
word_count=Counter(string)
print(word_count)
final_count=word_count[word]
print("Count of the word is:")
print(final_count)
|
90a55ef8f89321593ebaa1fd95068f18677945dc | thivatm/Hello-world | /Python/CurrentDirDetails.py | 627 | 3.828125 | 4 | import os
import csv
import io
# os.walk returns three tuples- dirpath, dirname, filenames.
# We can use them and get the list of the files and folders of the current directory.
filenames = []
for root, dirs, files in os.walk(".",topdown = False):
for name in files:
print(os.path.join(root,name))
filenames.ap... |
ac092a7049def999dd1488cde4fbbaf1b37a5d3e | paulcacheux/mpsi_python_cours | /python/crypt/cours.py | 1,202 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf_8 -*-
import string
def quick_pow(x, n):
if n == 1:
return x
elif n % 2 == 0:
return quick_pow(x * x, n // 2)
else:
return x * quick_pow(x * x, (n - 1) // 2)
def exp_pow(x, n):
res = 1
puiss = x
while n:
q, r = divmod(... |
c0ae6a8a3bb216342768c334ae4511a7db19fac1 | paulcacheux/mpsi_python_cours | /python/knight_tour/DM/cavalier2_original.py | 2,745 | 3.6875 | 4 | # -*- coding : utf-8 -*-
from random import randint # Module importé
N = 6; HISTORIQUE = [] # Variables globales
def afficher():
""" Dessine la grille n x n """
liste = [' .'] * (N**2)
for i in range(len(HISTORIQUE)):
(x,y) = HISTORIQUE[i]
liste[x + y * N] = i
Espace = "\n"... |
6bec5d96402ec19c298a694c329911e4904b5018 | PaddyK/biosi | /biosi/emg/datadecorators.py | 25,032 | 3.546875 | 4 | """ This module contains classes implementing the decorator pattern. Purpose
is to easily streamline different operations on data.
For more information on the decorator pattern refer to
`Wikipedia <https://en.wikipedia.org/wiki/Decorator_pattern>`_
All decorators manipulating data expect lists/generat... |
d185f36ed19a3076bee29f5305bc898dbe9f5912 | sandeshsuvarna7/LearnFullStack-Python | /Python Program Project/Session 1/VolumeofSphere.py | 225 | 4.09375 | 4 | fl = input("Enter Diameter of shpere in cm: \t" )
fl = float(fl)
v = 0
v = float(v)
import math
v = (4/3) * math.pi * (fl/2) * (fl/2) * (fl/2)
print("volume of sphere with diameter " + str(fl) + " cm is " + str(v) + " cu.cm") |
a6afedc0f8d6d11a2288fb58ac31a42d5ce0a395 | GMadhu921/python_scripts | /forloop.py | 131 | 3.9375 | 4 | list1=["saket","saurabh","rohit","rambhool"]
#print(f"List is {list1}")
for i in list1:
print("Student name is {0}" .format(i))
|
2c6dd2c3a2d65ed93157e408d0ec329c7b020c7b | elinot15/IT-security | /lab1/es2.py | 229 | 3.515625 | 4 | encrypted= open('crypt.txt' , 'r').read()
key= open('key.txt' , 'r').read()
key=key.encode()
encrypted=encrypted.encode()
decrypted=bytearray()
for (k,val) in zip (key, encrypted):
decrypted.append(k^val)
decrypted.decode()
|
0cb00f6f4798c9bc5770f04b8a2a09cb0e3f0c43 | ssavann/Python-Data-Type | /MathOperation.py | 283 | 4.25 | 4 | #Mathematical operators
print(3 + 5) #addition
print(7 - 4) #substraction
print(3 * 2) #multiplication
print(6 / 3) #division will always be "Float" not integer
print(2**4) #power: 2 power of 4 = 16
print((3 * 3) + (3 / 3) - 3) #7.0
print(3 * (3 + 3) / 3 - 3) #3.0
|
5d4260fbdbff695cd93371367aed2a7c11b579bc | ssavann/Python-Data-Type | /TipCalculator.py | 646 | 4.09375 | 4 | #Tip Calculator
print("Welcome to the Tip Calculator")
theBill = float(input("What was the total bill? "))
theTip = int(input("What % tip would you like to give? 10, 12, 15 or 20? "))
splitPeople = int(input("How many people to split the bill? "))
tipConvertion = (theTip / 100) + 1
#will calculate the "bill" * "ti... |
19492f9a51ace4ebfab9130aea1f8a0219452b2e | alokojjwal/Adython | /palindrome_test.py | 445 | 4 | 4 | def isPalindrome(str):
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
b="-"
d="-"
a = [item for item in input("Enter for Palindrome test: ").split()]
b=b.join(a)
c=list(b)
data = [x for x in c if x.isalnum()]
d=d.join(data)
s=d.u... |
a47981b6eaf143195c3c5df64918d04e21946cbf | ddaimon/kayit | /kayıt.py | 4,375 | 3.546875 | 4 | import sqlite3
import math
import time
class öğrenci():
def __init__(self,isim,soyisim,sınıf,adres,veli_numarası,kilometre):
self.isim = isim
self.soyisim = soyisim
self.sınıf = sınıf
self.adres = adres
self.veli_numarası = veli_numarası
self.kilometre... |
c54d75b36108590ba19569ae24f6b72fd13b628b | Alankar-98/MWB_Python | /Functions.py | 239 | 4.15625 | 4 | # def basic_function():
# return "Hello World"
# print(basic_function())
def hour_to_mins(hour):
mins = hour * 60
return mins
print(hour_to_mins(float(input("Enter how many hour(s) you want to convert into mins: \n")))) |
ce788f6c65b9b8c4e3c47585b7024d2951b59d19 | GLARISHILDA/07-08-2021 | /cd_abstract_file_system.py | 928 | 4.15625 | 4 | # Write a function that provides a change directory (cd) function for an abstract file system.
class Path:
def __init__(self, path):
self.current_path = path # Current path
def cd(self, new_path): # cd function
parent = '..'
separator = '/'
# Absolute path
... |
6a88a0568fed7a5f136cd7b990b1f25c1ad43045 | hiddenworlds225/School-code | /Python/Emplyee.py | 304 | 3.828125 | 4 |
#load from json file
import json
name = ""
age = 0
id = 0
def main():
with open("info.json", "r") as file:
data = json.load(file)
for i in data:
print("Name:", i["Name"])
print("Age:", i["Age"])
print("ID:", i["ID"])
print()
main() |
b98ef52039282f2aca22780a1f9728905dc4c832 | hiddenworlds225/School-code | /FOUNDPRO/segment 1/2.06 Project.py | 2,901 | 4.03125 | 4 | # 2.06 Project
#
# Author: Shawn Velsor
#
# Date of Creation: 10/19/2020
# We are doing the wishlist one.
# We need some sort of interaction.
# Allow the user to input text inputs. Sounds good enough.
# Maybe we can store this stuff inside a dictonary? Seems the best way.
# Note: 6.5% tax and $5.99 flat shipping ... |
bccbb301aca6a2785414b4a821d36a4800b559e2 | rinivelkum/ProiecteSabo | /Spanzuratoare/Base.py | 1,730 | 3.53125 | 4 | import codecs
import random
words = codecs.open('cuvinte_de_verificat.csv','r','utf8')
def alphabet():
alphabet = list(map(chr, range(65, 91)))
alphabet.append(chr(536))
alphabet.append(chr(538))
alphabet.append(chr(194))
alphabet.append(chr(258))
alphabet.append(chr(206))
alphabet.remove(... |
281c014573ff3bc198bd1ded22ad36dc7832a930 | jaehyuk-code/python | /0416/factorial.py | 128 | 3.765625 | 4 | n = int(input("정수 입력 :"))
fact = 1
for i in range(1, n+1):
fact= fact * i
print(n, "!은", fact, "입니다")
|
41c974108a3ce436f90650f036d2be5ef9557fda | jaehyuk-code/python | /0506/coffee.py | 366 | 3.625 | 4 | coffee = 10
while True:
print("돈을 받았으니 커피를 줍니다.")
coffee = coffee -1
print("남은 커피의 수는 %d개 입니다." % coffee)
if coffee == 0:
print("키피가 다 떨어졌습니다. 판매를 중단합니다")
break
print("휴식이 길어지면 몸이 아파집니다.")
|
56c906319d9579ae16c2377ab4de1518bf545505 | jaehyuk-code/python | /0415/ifStmt.py | 231 | 3.796875 | 4 |
#ifStmt
#if
#if else
# if elif elif elif elif ... else
num = int(input("나이 입력 : "))
money = 10000
if num > 20:
money += 5000 #money = money + 5000
print("당신의 입장료는",money,"입니다")
|
685833f7744da494ed4d9702937b47ea44a483a8 | jaehyuk-code/python | /0506/score.py | 540 | 3.609375 | 4 | marks = []
for i in range(5):
scr = int(input("%d번 학생의 성적" %(i+1)))
marks.append(scr)
print(marks)
sum = 0
number = 0
for mark in marks:
number = number + 1
sum = sum + mark
if mark >= 60:
print("%d번 학생의 성적은 %d이고 합격입니다." %(number,mark))
else:
... |
cd5321dd3779fbce1ebea1aee2d926a498391984 | moreirab/practice-python | /exercise_05.py | 312 | 3.734375 | 4 | # source: https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html
from utils import random_list
a = random_list(50, 50)
print('List a:')
print(sorted(a))
b = random_list(50, 50)
print('List b:')
print(sorted(b))
c = [x for x in set(a+b) if x in a and x in b]
print('List c:')
print(sorted(c))
|
90367f442ed20f2c91ba147820f2a19f2b2a1ed6 | rafaeloliveira00/coding-challenges | /10_valid_number/main.py | 3,133 | 3.609375 | 4 | class Solution:
def isNumber(self, s: str) -> bool:
# this problem was solved by using a finite state machine
# states
NUMBER = 1
DOT = 2
E = 3
SIGN = 4
current_state = 0
got_dot = False
got_e = False
got_numbers = False
s =... |
42cac811a81ccd3bd0c6a656902253e9f9e745f3 | GuilhermeDeizeppe/python-bank | /teste_mysql.py | 832 | 3.5625 | 4 | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="testdb"
)
mycursor = mydb.cursor()
"""
# INSERT
sql_formula = "insert into students(name, age) values(%s, %s)" # fórmula sql que será executada (note que os '%s' serão
# substituídos pelas variá... |
62a03d0731f82dc79cd506bd6ff4640b2a210854 | sdudas/221Final | /basicClassifier.py | 2,358 | 3.609375 | 4 | from keras.layers import Input, Dense, Dropout
from keras.models import Sequential, Model
import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(sys.path[0])), 'configs' ))
import constant
"""
Classifier class contains method to create NN classifier
"""
class Classifier:
def __init__(self):
... |
96ee686869f517e9527ca1dc37d6666468c9e511 | shafeen/Utilities | /Python/Geo/Geo.py | 6,533 | 3.875 | 4 | #!/usr/bin/env python
# Author : Shafeen M.
# tools to determine distances between 2 (or more) GPS coordinates
# provided the latitudes and logitudes of the coords are given in the
# appropriate form
import numpy as np
from math import radians, cos, sin, asin, sqrt
# Returns dist between 2 points in km
def havers... |
def3197e42884ecfedf32c424f66c0bd6ed10a34 | WazedKhan/Statistics | /variance2.py | 274 | 3.703125 | 4 | import math
a = [2,2,3,3]
b = [0,0,5,5]
def variance(data):
xminus_mean = 0
mean = sum(data)/len(data)
for i in data:
xminus_mean += math.pow((i - mean), 2)
print(f'The Variance is : {xminus_mean/(len(data)-1)}')
variance(a)
variance(b) |
225245711dde85953eecc0caff1c208fe7dd32a8 | jlf6/pyTest | /commaCode.py | 382 | 3.609375 | 4 | spam = ['apples', 'bananas', 'tofu', 'cats']
print(spam)
def commaCode(nameList):
n = len(nameList)
newList = nameList[0]
for i in range(0, n):
if i == 0:
newList = newList
elif i == n-1:
newList = newList + ',and ' + nameList[i]
else:
newList = n... |
a84755fd8627c33535f669980de25c072e0a3c83 | sandeshsonje/Machine_test | /First_Question.py | 555 | 4.21875 | 4 | '''1. Write a program which takes 2 digits, X,Y as input and generates a
2-dimensional array.
Example:
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Note: Values inside array can be any.(it's up to candida... |
295dc10c95e716a9739c5269f9323d6bf4b145e1 | Arey14/Python | /PythonPOO/setter-getters.py | 785 | 3.671875 | 4 |
class Millas:
def __init__(self, distancia = 0):
self.distancia = distancia
def convertir_a_kilometros(self):
return (self.distancia * 1.609344)
# Creamos un nuevo objeto
avion = Millas()
# Indicamos la distancia
avion.distancia = 200
# Obtenemos el atributo distancia
print(avion.distancia)
# Obtenemos el ... |
ed845561c531a3a03134c72860556f45ce49240a | ericbollinger/AdventOfCode2020 | /day10/first.py | 516 | 3.59375 | 4 | #with open("demo2.txt", "r") as f:
with open("input.txt", "r") as f:
lines = f.readlines()
adapters = [int(l.strip()) for l in lines]
adapters.sort()
lo = adapters[0]
hi = adapters[len(adapters)-1]
# Add the outlet and your device to list
adapters.insert(0, 0)
adapters.append(hi+3)
diffs = [0, 0, 0]
for... |
ca0bfad31bb788610d4abaa15187409253718900 | vitaliyshian/dota2-matcher | /item.py | 487 | 3.734375 | 4 | class Item:
"""
Клас Предмет, состоит из
имя
цена
параметры
"""
name: str = str()
price: int = None
params: dict = dict()
def __init__(self, name: str, price: int, params: dict):
self.name = name
self.price = price
self.params = params
def __str__(s... |
36c175405abd25f98e721e9d9f2d7f3d86ea3e18 | Auto4C/Python | /设计模式/S7 Proxy.py | 2,053 | 3.640625 | 4 | # 代理-结构化模7/7,通常用来处理实体之间 of 关系,使得这些实体能够更好地协同工作
'''
意图:
为其他对象提供一种代理以控制对这个对象的访问。
适用性:
在需要用比较通用和复杂的对象指针代替简单的指针的时候,使用Proxy模式。
下面是一些可以使用Proxy模式常见情况:
1远程代理(Remote Proxy)为一个对象在不同的地址空间提供局部代表。
NEXTSTEP[Add94] 使用NXProxy 类实现了这一目的。Coplien[Cop92]称这种代理为“大使”(Ambassador)。
2虚代理(Virtual Proxy)根据需要创建开销很大的对象。在动机一节描述的ImageProxy就是这样一种代理的... |
31d03d569bb2095fe8decfe0f50a516c71bd439c | Lipe-lx/conversor-moedas-base-usd | /conversor-de-moedas.py | 1,104 | 3.9375 | 4 | import requests
url = "https://api.exchangerate-api.com/v6/latest" #endereço da API da corretora para montar um conversor de moedas
requisicao = requests.get(url)
print(requisicao.status_code) #verificação se o endereço está funcionando - retornando (obj: 200) está tudo ok
dados = requisicao.json() #Recuperando os da... |
f5e7a155de761f83f9ad7b8293bc5c81edda3f1f | Luciekimotho/datastructures-and-algorithms | /MSFT/stack.py | 821 | 4.1875 | 4 | #implementation using array
#class Stack:
# def __init__(self):
# self.items = []
# def push(self, item):
# self.items.append(item)
# def pop(self):
# return self.items.pop()
#implementation using lists
class Stack:
def __init__(self):
self.stack = list()
#inse... |
5072f323bcb39b8663be3781f70300b2bc2793a6 | Luciekimotho/datastructures-and-algorithms | /MSFT/readn.py | 935 | 3.953125 | 4 | '''
Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters.
For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”.
'''
class FileRead:
def __init__(self, str):
self.str = str
self.offset = 0
... |
244cf1e2b31ae4a9ce0517202e89053735febd14 | mariannyfidelis/curso_python | /20_banco_de_dados/banco1.py | 3,395 | 3.9375 | 4 | import sqlite3
# CRIAR A CONEXÃO
def cria_conexao(banco="basededados1.db"):
conexao = sqlite3.connect(banco)
cursor = conexao.cursor()
return cursor, conexao
# CRIAR A TABELA COM COMANDO SQL
def cria_tabela(cursor):
cursor = cursor
cursor.execute('CREATE TABLE IF NOT EXISTS clientes('
... |
b573112738befe13479ad9ac2071d995ebc7ac0b | dflatow/compjour-hw | /usajobs-midterm-2/2-10.py | 347 | 3.5 | 4 | from midterm_utils import get_state_jobs
import pandas as pd
import re
jobs = get_state_jobs("California", number_of_jobs=250)['JobData']
data = [[x['OrganizationName'], 1] for x in jobs]
df = pd.DataFrame(data, columns=['name', 'count'])
s = df.name.value_counts()
print("Counts as a pandas series:\n",s)
print("\nCou... |
f3f221051318191cb590906e2da3d738d2604b3e | dflatow/compjour-hw | /usajobs-midterm-1/1-3.py | 309 | 3.859375 | 4 | from midterm_utils import get_country_total_jobs
countries = ['China', 'South Africa', 'Tajikistan']
total = 0
for country in countries:
count = get_country_total_jobs(country)
print("%s has %s job listings." % (country, count))
total += count
print("Together, they have %s total job listings." % total)
|
0be974c5320fa13c56322564e6c9aa2e33a9842b | YangZeCN/PythonLearningCenter | /flowcontrol_if.py | 864 | 4.03125 | 4 | '''
Name: flowcontrol_if.py
Author: Yang Ze
Created: 2019.04.02
Last Modified:
Version: V1.0
Description: An example for if...elif...else...
'''
# There is no switch statement in Python. You can use an if..elif..else statement to
# do the same thing (and in some cases, use a dictionary to do it quickly)
number = 23
g... |
ea79a1973e64d45562723b67f2808922b417a550 | Babsia/ej2-2021 | /Viajeros.py | 676 | 3.625 | 4 | class viajerofrecuente:
__numero=''
__dni=''
__nombre=''
__apellido=''
__Macum=0
def __init__(self,numero='',dni='',nombre='',apellido='',millas=0):
self.__numero=numero
self.__dni=dni
self.__nombre=nombre
self.__apellido=apellido
self.__Macum=m... |
eab5e0186698af32d9301abf155e1d0af25e5f6f | jzamora5/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 647 | 4.1875 | 4 | #!/usr/bin/python3
""" Minimum Operations """
def minOperations(n):
"""
In a text file, there is a single character H. Your text editor can execute
only two operations in this file: Copy All and Paste. Given a number n,
write a method that calculates the fewest number of operations needed to
resu... |
1ef7ad4df0293ee86388ba91991fa6e0de50c11e | kiady66/Stone_Age | /GameSetup/GameBoardSetup.py | 1,149 | 3.5625 | 4 | from typing import Set, List
from Place import UpperPartPlace, CivilizationPlace, BuildingPlace
class GameBoardSetup:
"""
Object GameBoardSetup which represent the parameters of the gameboard
"""
def __init__(self, max_nb_food_production: int, nb_points_when_do_not_feed: int,
places... |
c654f1bac29c5116bd99f046fa559a40d2550b08 | joeblackwaslike/codingbat | /recursion-1/changePi.py | 987 | 3.546875 | 4 | """
changePi
Given a string, compute recursively (no loops) a new string
where all appearances of "pi" have been replaced by "3.14".
changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"
"""
def changePi(string):
def recurse(s, output=""):
if not s:
return outp... |
c2809bed33b4b240c301addd72ab785e92922759 | joeblackwaslike/codingbat | /recursion-1/count8.py | 868 | 3.90625 | 4 | """
count8
Given a non-negative int n, compute recursively (no loops) the count of the
occurrences of 8 as a digit, except that an 8 with another 8 immediately to
its left counts double, so 8818 yields 4. Note that mod (%) by 10 yields the
rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost
d... |
883d59af7f7d44bcb5d86eab712eeda185a047af | joeblackwaslike/codingbat | /recursion-1/count11.py | 1,104 | 3.890625 | 4 | """
count11
Given a string, compute recursively (no loops) the number of "11" substrings
in the string. The "11" substrings should not overlap.
count11("11abc11") → 2
count11("abc11x11x11") → 3
count11("111") → 1
"""
from typing import List
def count11(string: str) -> int:
searchString = "11"
windowSize = ... |
746c24e8e59f8f85af4414d5832f0ec1bf9a4f7c | joeblackwaslike/codingbat | /recursion-1/powerN.py | 443 | 4.25 | 4 | """
powerN
Given base and n that are both 1 or more, compute recursively (no loops) the
value of base to the n power, so powerN(3, 2) is 9 (3 squared).
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
"""
def powerN(base, n):
if n == 1:
return base
else:
return base * powerN(base, n - 1)... |
594ffd055fa7cacbe3889aa10757baa8694f1df8 | joeblackwaslike/codingbat | /recursion-2/groupNoAdj.py | 1,439 | 3.828125 | 4 | """
groupNoAdj
Given an array of ints, is it possible to choose a group of some of the ints,
such that the group sums to the given target with this additional constraint:
If a value in the array is chosen to be in the group, the value immediately
following it in the array must not be chosen. (No loops needed.)
... |
03b43700fb968a63db9e03ef18153004e583aa85 | artcheng6/123 | /123.py | 203 | 3.515625 | 4 | name = input('你叫什麼名字?')
print('hello', name)
hight = input('請輸入身高')
weight = input('請輸入體重')
print('你的身高', hight, '公分,而你的體重是', weight, '公斤') |
aeb8a33a7838611be49af249a46f3dde6420d7ab | zacarrell/image-dupes | /imgdupes2.py | 5,906 | 3.734375 | 4 | #!/usr/bin/env python3
"""Find and report similar-looking pictures or images on your computer.
This script detects duplicate images on your computer in a unique way.
For standard text files, a file hashing algorithm, such as MD5, would
work well. However, there are problems with this approach when dealing
with im... |
666744bacc5ccaf651400cc99e39e37805edeaa2 | laihaotao/myscript | /ta/grep_grade.py | 1,322 | 3.625 | 4 | import os
import re
import sys
'''
Author: Haotao Lai (Eric)
Contact: h_lai@encs.concordia.ca
This script is used for grep the grade from a directory where contains the assignment submited through EAS in ENCS department in Conconrdia University (Montreal).
The marker MUST used the "mark.txt" to give the grade and t... |
92000f5f7c500cbf1c82971a1999e004d0669b73 | vsoch/natacha-bot | /tests/test_duplicates.py | 597 | 3.640625 | 4 | class TestClass:
# Read data
with open("data/trump/input_raw.txt", "r") as f:
data = f.read()
words = data.split()
word_count = len(words)
def test_duplicate_speeches(self, phrase_len=100):
duplicates_found = False
for i in range(0, self.word_count - phrase_len):
... |
234700ba20900fa2a3bba30be82b95537bfaa039 | LingChenBill/python_first_introduce | /4-5-condition.py | 1,206 | 3.96875 | 4 | # Date:2019/9/21
# Author:Lingchen
# Mark:
# 条件控制
# 如果if后面的布尔表达式过长或者难于理解,可以采取给变量赋值的办法来储存布尔表达式返回的布尔值True或者False
# 多条件判断同样很简单,只需在if和else之间增加上elif,用法和if是一致的
def account_login():
password = input('Password:')
password_correct = password == '12345'
# if password == '12345':
if password_correct:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.