blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
edbf3c59e3bd5a353e438bb79921a189e2019eff | Anubhav27/python_handson | /listdemo.py | 327 | 3.734375 | 4 | __author__ = 'Anubhav'
shoplist = ['a','b','c','d']
print shoplist.__len__()
shoplist.append('e')
print shoplist.__len__()
shoplist.append('z')
shoplist.append('f')
print shoplist.__len__()
print shoplist
shoplist.sort()
print shoplist
for items in shoplist:
print items
for i in range(100):
pr... |
bceac41714c08ff36ed0481b68cfffe69f61f3ad | Kanguru9/SimpleLogin | /login.py | 3,121 | 4.28125 | 4 | def login():
username_vault = ["john", ]
password_vault = ["smith", ]
choose = input(
"Do you want to create a account or login? Type login for logging in or type create for creating an account: ")
choose.lower()
six = 6
if choose == "create":
Create()
elif choose == "login":... |
d94c3e993bd855c950dfe809dba92957b40c4a20 | JimiofEden/PyMeth | /Week 1/TEST_roots_FalsePosition.py | 470 | 4.25 | 4 | import roots_FalsePosition
import numpy
'''
Adam Hollock 2/8/2013
This will calculate the roots of a given function in between two given
points via the False Position method.
'''
def f(x): return x**3+2*x**2-5*x-6
results = roots_FalsePosition.falsePosition(f,-3.8,-2.8,0.05)
print results
results = roots_FalsePositi... |
9356de0d86bb5dd10b881f2e71df30e6bf827c58 | mitalshivam1789/python | /else with for file.py | 235 | 4.09375 | 4 | khana = ["roti","sabzi","chawal"]
for item in khana:
if item == "roti":
print(item)
break
else: # it will execute when for loop goes properly. or their is no break in loop
print("Your item is not found") |
b591d8d0928cc4e959880875bd3003d07efa20fc | mitalshivam1789/python | /practice_test_3.py | 708 | 3.890625 | 4 | list_value=input("enter a list with spaces between numbers.")
list_value=list_value.split(" ")
for i in range(len(list_value)):
list_value[i] = int(list_value[i])
print(list_value)
print(type(list_value[1]))
list_value.reverse()
print(list_value)
list_value.reverse()
print(list_value[::-1])
len=len(list_v... |
7126fe424d609939ae4aa0247f6681c261b1c13a | mitalshivam1789/python | /project6differentway.py | 978 | 3.796875 | 4 | def adddata(name):
whattoadd = input("diet or exercise")
details = input("what you what to add")
f = open(name + whattoadd + ".txt", "a")
f.write(details)
f.close()
def retrievedata(name):
whattoretrieve = input("diet or exercise")
f = open(name + whattoretrieve + ".txt")
p... |
ab806e66a29e7c19be1b8fa9b3703a723604597d | mitalshivam1789/python | /functionsfile.py | 427 | 3.953125 | 4 | c = sum((5,7))
print(c)
def function1(a,b):
"""this is a doc which we can print using doc whic i will show you . So we should write here about the role of the function so that we can see it using the the doc function."""
print("thsi is a nice function.")
print(function1.__doc__)
num1 = input()
num2 = inp... |
055edf392302483538c41b1b0739c445dc08598a | mitalshivam1789/python | /mapfilterreduce.py | 576 | 3.71875 | 4 | lis = ["1","2","5","3","4"]
num = list(map(int,lis))
print(num,type(num),lis)
def sq (a):
return a*a
square = list(map(sq,num))
print(square)
sqr = list(map(lambda x: x*x,num))
print(sqr)
def sqr1(a):
return a*a
def cube(a):
return a*a*a
func = [sqr1,cube]
for i in range(5):
val = list(ma... |
a935561050f1775260a7f7fa3da95d9ab53c718f | mitalshivam1789/python | /updating a spread sheet.py | 511 | 3.578125 | 4 | import openpyxl
wb=openpyxl.load_workbook('produceSales.xlsx')
sheet = wb.get_sheet_by_name('Sheet')
PU = {'Garlic':3.07,
'Celery': 1.19,
'Lemon':1.27}
condition = "y"
while condition == "y":
produce = input("item whose price is increased")
for keys,values in PU.items():
if keys ... |
e579fadc31160475af8f2a8d42a20844575c95fa | mitalshivam1789/python | /oopfile4.py | 940 | 4.21875 | 4 | class A:
classvar1= "I am a class variable in class A."
def __init__(self):
self.var1 = "I am in class A's constructor."
self.classvar1 = "Instance variable of class A"
self.special = "Special"
class B(A):
classvar1="I am in class B"
classvar2 = "I am variable of class ... |
5a4875dbdec041460161d45c208d4313b797fd16 | yangyang6/daily-python | /chapter8/python8.4.py | 859 | 3.71875 | 4 | def greet_users(names):
for name in names:
print ("hello : " + name)
#python中不用main方法也可以运行方法也,这样不同于java
usernames = ["yang","li","he"]
greet_users(usernames)
unprinted_designs = ["iphone_case","robot_pendant","yyy"]
completed_models = []
def print_mode(unprinted_designs):
while unprinted_designs:... |
267083e774a5a5d9f79b25de916509f214d938cc | yangyang6/daily-python | /chapter5/note5-9.py | 486 | 3.796875 | 4 | #完整删除整个列表元素 实现
foods = ["egg","beaf","dock"]
# 第一种方式
# print(foods)
# del foods[len(foods):]
# print(foods)
# 第二种方式(最简单的方式)
# foods = []
# print(foods)
#第三种方式
#创建两个列表解决循环删除列表中多个元素的问题
# del_foods = ["egg","beaf","dock"]
# for i in del_foods:
# foods.remove(i)
# print(foods)
#第四种方式
for i in foods:
print(foo... |
f5acf4093e6c85483e029ecee6a146d2e9ddef6f | yangyang6/daily-python | /design-pattern/decorator-pattren.py | 1,493 | 3.9375 | 4 | #装饰器模式
import time
# def display_time(func):
# def wrapper():
# t1 = time.time()
# func()
# t2 = time.time()
# print((t2-t1))
# return wrapper
# def display_time(func):
# def wrapper():
# t1 = time.time()
# result = func()
# t2 = time.time()
# ... |
d07692da0f2fe51c22231e55d589a0fd1ea91f4c | vjek/procedural_generation | /otp-enc.py | 2,499 | 3.828125 | 4 | #!/usr/bin/env python3
# script to demonstrate mod10 Message + Key = Ciphertext
# by vjek, 20200426, updated 20230422
###
from getpass import getpass
import random,hashlib,sys
def getphrase():
#get sha512 of passphrase, use it as rand seed to generate OTP of any length
#if you wanted true OTP, add ISO 8601 met... |
35776a487367e9338bb0701f87b9f5bea1425ed6 | Gavin4th/Meituan-Crawl | /test.py | 716 | 3.546875 | 4 | #导入必要的包
import requests
from bs4 import BeautifulSoup
# 武汉理工大学科url
url = 'https://www.whut.edu.cn/'
# 发起访问请求
page = requests.get(url = url)
# 输出返回信息
print(page.url)
print(page.status_code)
for k,v in page.headers.items():
print(k,":\t",v)
# 初始化soup对象
soup = BeautifulSoup(page.text,"html.parser")
#... |
311d777bd37de1334727b61fb383a67f3a80f117 | zhangxiutao/AIScripts | /yield.py | 111 | 3.59375 | 4 | def func1(x):
while True:
print(x)
x=x-1
if x == 0:
break
func(5)
|
18f3122df32eab19f3346206fedc3bec28cab042 | Nerubes/review1 | /ceasar.py | 956 | 3.921875 | 4 | import alphabet
def encrypt(string, seed, n):
"""
Шифрует или дешифрует строку используя шифр Цезаря
:param string: текст для шифровки или дешифровки
:param seed: ключ
:param n: указывает на то, будет ли функция шифровать или дешифровать строку
:return: зашифрованый или расшифрованный... |
ce8e51cd0072f1c34eb34655d5c753e5267e383d | harfeyar/python-noobie | /index.py | 165 | 4 | 4 | # x = 10
# y = 20
# print (x)
# x += y
# print (x)
# x -= y
# print (x)
# x *= y
# print (x)
# x /= y
# print (x)
x = 10
y = 20
resulte = x < y
print (resulte) |
4ecd4d3a20e875b9c0b5019531e8858f4722b632 | victorbianchi/Toolbox-WordFrequency | /frequency.py | 1,789 | 4.5 | 4 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a li... |
8851fb83fd60acb70bd883e09f89a51673195729 | dev-vishalgaurav/algo | /codechef/TSORT/python/TSORT_ARRAY.py | 397 | 3.5 | 4 | maxValue = 1000001
inputValue = int(raw_input())
sortedList = [0] * maxValue
for each in range(inputValue):
number = int(raw_input())
sortedList[number] = sortedList[number] + 1
printList = ""
for number in range(maxValue):
while(sortedList[number] > 0):
printList = printList + str(number) + "\n"
... |
2ac130b6bad97756b27258e8148c9c15a59be86d | vanechipi/Python-BeautifulSoup-Sqlite-Tkinter | /Practice-with-Python/p3_tuplas.py | 1,174 | 3.828125 | 4 | #encoding: utf-8
t = ("Vanessa", "Alvaro", "Juana", "Rocio")
def campanaNombres(var):
for l in var:
print "Estimad@",l+",","vote por mi"
if __name__ == "__main__":
campanaNombres(t)
t = ("Vanessa", "Alvaro", "Juana", "Rocio")
def campanaNombresYPosicion(var, p):
if p >= len(... |
3419d96ab611b0fb171ed8b27b23d996cb63820c | Pradoshks/CS513-Data-Cleaning-Project | /CS513 - Data Cleaning Final Project - Submission/Python Code & python YW diagrams/ywparse.py | 3,494 | 3.78125 | 4 | import pandas as pd
import re
# @BEGIN main
def main():
# @Param data @URI file: data/NYPL-menus.csv
# @Param subset
data = pd.read_csv("../data/NYPL-menus.csv")
# print(data.head())
'''Select a subset of the data for cleaning with Python'''
subset = data[['event', 'venue', 'place', 'dat... |
f0010c9aa51410c1ab24f6a75467c630d6d42e2e | Gecazo/RockPaperScissors | /rockpaperscissors.py | 1,226 | 3.890625 | 4 | import random
count_draws = 0 # Counter - Draw, Loose, Win
count_loses = 0
count_wins = 0
TYPE_LIST = ('rock', 'scissors', 'paper') # Items - rock, scissors, paper
def inp(): # Number of turns
global n
while True:
try:
n = int(input('Enter an amount of games n '))
... |
d2de097ee33f0060830681df81f87f600f5da69c | Scott-Dixon-Dev-Team-Organization/cs-guided-project-linked-lists | /src/demonstration_3.py | 804 | 4.1875 | 4 | """
Given a non-empty, singly linked list with a reference to the head node, return a middle node of linked list. If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list
The returned node has value 3.
Note that we returned a `ListNode` object `ans`, su... |
5cfd2d5724a2113b3cfa67233d6532400cb32c7f | QixiangLiu/personalWeb | /webPage/EECS/2019/EECS660/Project/HW2/bfs_dfs_input-output/dfs_liu.py | 1,529 | 3.890625 | 4 | # use python 3.7.2
# -*- coding: UTF-8 -*-
"""
Author: Qixiang Liu
Description: depth-first search
Date: 03/14/2019
Log: depth-first search is recursion;
"""
import os
import sys
if len(sys.argv) != 2:
print ("python3 <EXE><Input.txt>")
exit(1)
# open a file: default access: ready only
# Enter a input file
f... |
3294384c70f73640b4eb72b0b24888738293c161 | QixiangLiu/personalWeb | /webPage/EECS/2019/EECS660/Project/HW4/minimum_spanning_tree/msp_2856114.py | 4,279 | 4.0625 | 4 | # use python 3.7.2
# -*- coding: UTF-8 -*-
"""
Author: Qixiang Liu
Description: Minimum spanning tree in Kruskal's Algorithm
Date: 04/05/2019
Log: Always choose the minimum edges, if edges have been connected, just give up; Sort by edges
1) learn class in python
2) how to create 2D array in python
3) Us... |
54488222c54e9107dbd48dd5e29fe68ccd4bbe23 | AryanshuArindam08/Simple-Quiz-Game-In-Python | /Quiz_game.py | 899 | 3.953125 | 4 | # Simple-Quiz-Game-In-Python
print('Welcome to Aryanshu Quiz')
answer=input('Are you ready to play the Quiz ? (yes/no) :')
score=0
total_questions=3
if answer.lower()=='yes':
answer=input('Question 1: what is the easiest programming language?')
if answer.lower()=='python':
score += 1
print('co... |
961f89e5aa40a3377dc4e513b67afb232e4e525f | KayWinkler/nirs | /curve.py | 6,506 | 4.03125 | 4 | """
curve fitting
- approximate the given values of a data frame with a polynomial curve x^8
used to identify the curve minima and maxima to identify the direction and
calculate the tendencies
"""
from scipy import optimize
class Curve():
"""
low level mathematical helper to fit a data set
"""
de... |
0f4ad94ce5b6d5619ce4cfdf106e0778cf21994b | MaxchilKH/pySimulation | /Organisms/Organism.py | 1,405 | 3.75 | 4 | from abc import abstractmethod, ABCMeta
class Organism(metaclass=ABCMeta):
def __init__(self, tile, world):
self.tile = tile
self.world = world
self.isDead = False
def kill(self):
self.isDead = True
@property
def strength(self):
return self.__strength
@s... |
9474a0ab7d388a230ef9abdef461b871abe0ef66 | MaxchilKH/pySimulation | /Organisms/Animals/Antilope.py | 1,017 | 3.515625 | 4 | from Organisms.Animals.Animal import Animal
import random
class Antilope(Animal):
def __init__(self, tile, world):
super().__init__(tile, world)
self.strength = 4
self.initiative = 4
def draw(self):
return "#875409"
def action(self):
moves = set()
moves.u... |
27a41a40a8009d7287434b3f4e2653c9b9a965d2 | menezesluiz/MITx_-_edX | /week1/exercise/exercise_happy.py | 574 | 4.09375 | 4 | """
Exercise: happy
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise: happy
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 3 minutes
Write a piece of Python code that prints out the string 'hello world' if the
value of an integer variable, happy, is strictly greater than 2.
Do no... |
045ec74a9cc39d32ff4541f9c69f7bdac54ef31d | menezesluiz/MITx_-_edX | /week1/codes/V01_bindings.py | 316 | 3.71875 | 4 | """
Vídeo sobre variáveis e as melhores práticas para se trabalhar com elas.
"""
# Vídeo: Bindings
x = 2
x = x * x
y = x + 1
print(y)
# Dessa forma, é mais fácil de se perder
x = 1
y = 2
y = x
x = y
print(x)
# A solução seria criar uma variável temporária
x = 1
y = 2
temp = y
y = x
x = temp
print(x) |
00ead084fe729599aeedba61cc88fc277e7726ad | menezesluiz/MITx_-_edX | /week1/exercise/exercise-for.py | 442 | 4.34375 | 4 | """
Exercise: for
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise: for exercise 1
5.0/5.0 points (graded)
ESTIMATED TIME TO COMPLETE: 5 minutes
In this problem you'll be given a chance to practice writing some for loops.
1. Convert the following code into code that uses a for loop.
... |
36e8464800601f9fc4553aacc2f48369940393df | menezesluiz/MITx_-_edX | /week1/exercise/exercise04.py | 2,056 | 4.40625 | 4 | """
Exercise 4
Finger Exercises due Aug 5, 2020 20:30 -03
Completed
Bookmark this page
Exercise 4
5/5 points (graded)
ESTIMATED TIME TO COMPLETE: 8 minutes
Below are some short Python programs. For each program, answer the associated
question.
Try to answer the questions without running the code. Check your answers,... |
1156cca475eab407f874b887f625dffd6592e4be | kapilbisht/Python_Tutorial | /Hello.py | 14,347 | 4.34375 | 4 | print("Code with me!!!")
print("*" * 10)
xyz = 100 # variable store the value temporary in memory so that we can use it in our program
price = 123 # integer value
ratings: float = 4.5 # floating value
name: str = "Kapil" # String value
is_published = True # boolean value (python is case sensitive language thus Tr... |
622351f3e7a0a0b374e648d439ebe4b9db74320c | r0a91/Taller1Ciencias3Grupo81UD | /Ejercicio2/almacen.py | 817 | 3.625 | 4 | import pila
class Almacen:
def __init__(self, peliculas):
self.peliculas= peliculas
def buscar_peliculas_por_genero(self,busqueda):
#se empieza a buscar el genero entre el almacen de peliculas
if self.peliculas.es_vacia():
print ("No hay mas peliculas para mostrar."... |
dff8bc261320d6c228a7cb4d9765c14acc2ca521 | naemnamenmea/machine-learning-theory | /sections/regression_analysis/pca.py | 6,769 | 3.640625 | 4 | import numpy as np
from numpy.linalg import norm
def find_min(funObj, w, maxEvals, verbose, *args):
"""
Uses gradient descent to optimize the objective function
This uses quadratic interpolation in its line search to
determine the step size alpha
"""
# Parameters of the Optimization
optTo... |
e1c3baf9c0d25e5e275398ea1a681b69d8c4669c | Iwan-Zotow/runEGS | /XcMath/voxarea.py | 5,575 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import math
#
# Q1 Q0
# Q2 Q3
#
# rotation matrices
mtxQ0 = (( 1.0, 0.0), ( 0.0, 1.0))
mtxQ1 = (( 0.0, 1.0), (-1.0, 0.0))
mtxQ2 = ((-1.0, 0.0), ( 0.0,-1.0))
mtxQ3 = (( 0.0,-1.0), ( 1.0, 0.0))
def rotate(x, y, mat):
"""
Given 2D matrix, rotate x, y pair and return rotated pos... |
e2e4ae3acb162553475efa37669e4b14518815b1 | Iwan-Zotow/runEGS | /XcMath/conversion.py | 629 | 3.71875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
def mm2cm(v):
"""
Converts value from mm to cm
Parameters
----------
v: value
input value, mm
returns:
value in cm
"""
if np.isnan(v):
raise ValueError("mm2cm", "Not a number")
... |
79d8ef07aeb2eae84c451d48f74d4f0007218e3a | L200180012/algostruk | /MODUL_5/routineswap.py | 442 | 3.5 | 4 | def swap(A,p,q):
tmp = A[p]
A[p] = A[q]
A[q] = tmp
def cariPosisiYangTerkecil(A, dariSini, sampaiSini):
posisiYangTerkecil = dariSini #anggap ini yang terkecil
for i in range(dariSini+1, sampaiSini): #cari di sisa list
if A[i] < A[posisiYangTerkecil]: #kalau menem... |
bd99265f54d83c730f9f386210f1fea3ede5177b | christinegithub/reinforcement_march7 | /class.py | 1,313 | 4 | 4 |
classroom = [
[None, "Pumpkin", None, None],
["Socks", None, "Mimi", None],
["Gismo", "Shadow", None, None],
["Smokey","Toast","Pacha","Mau"]
]
row_index = 0
seat_index = 0
for row_index, row in enumerate(classroom):
for seat_index, seat in enumerate(row):
if seat == None:
print("Row {... |
2af12ab5ece3bf900831099cd069a46a6135bf8e | Mah1r2005/Python | /Sets.py | 3,497 | 3.859375 | 4 | s1={1,2,3,4}
s0={"a","b","c"}
s2={True,False}
s3=set((1,2,3,4))
print(1 in s3)
print(s1) #Printining the set
#Duplicate not allowed
#Unchanged
s4={1,2,3,4,5,5,3,2,1,3,5}
print(s4) #Duplicated element will no be printed
print(len(s4)) #Length of the set
print(type(s4))
... |
fd5641182de6babf5a1903469daac0fcb41e18af | Mah1r2005/Python | /Numbers.py | 926 | 3.90625 | 4 | #3 types of number
Normal_num=4
Float=4.89988
Complex=5j
x=4
y=6
z=5
print(x+y) #Sum
print(x*y) #Multiply
print(x**y) #Power
print(x/y) #Divide
print(x//y) #Divide but returns only the whole integer
print(x%y) #Modulas or re... |
d525504efb47a6d52c2fcf8c3817cba176054709 | Mah1r2005/Python | /Data types.py | 3,960 | 3.515625 | 4 | x=4 #Numbers
print(x)
print(type(x)) #Checking the type of the data
x="mahir" #String
print(x)
print(type(x))
x=True #Boolean
print(x)
print(type(x))
x... |
2e78c752ae5ca040e45f834444cae1076f61b758 | yinxingyi/Python100day_Learning | /Day4.py | 1,260 | 3.96875 | 4 | # ---------------------------------------------------------------
# print prime number within 0~100
# num = int(input('input a integer:'))
# for number in range(0,101):
# for i in range(2, number):
# if number%i == 0:
# print("%d is a not prime number!" %number)
# break
# ... |
386bdb2fc5eff97d6047b5a9aa10b5285bf04169 | yonggyulee/gitpython | /practice02/prob04.py | 431 | 3.65625 | 4 | #문제4 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 출력해보세요. 1부터 99까지만 실행하세요.
count = 0
for n in range(1,100):
clab = 0
clab += str(n).count('3')
clab += str(n).count('6')
clab += str(n).count('9')
if clab > 0:
print('{0} '.format(n) + '짝'*clab)
count += 1
print('총 객수 : {0}'.format(coun... |
c142beb40fb5f0bf1527f2a5fc3172165d0d4d09 | yonggyulee/gitpython | /02/07.operater_logical.py | 744 | 4.3125 | 4 | #일반적으로 피연산자(operand)는 True 또는 False 값을 가지는 연산
a = 20
print(not a < 20)
print(a < 30 and a !=30)
b = a > 1
# 다른 타입의 객체도 bool 타입으로 형변환이 가능하다
print(bool(10), bool(0))
print(bool(3.14), bool(0.))
print(bool('hello'), bool(''))
print(bool([0,1]), bool([]))
print(bool((0,1)), bool(()))
print(bool({'k1':'v1', 'k2':'v2', 'k3... |
5870f29cd1de872b91906c45f7115a2aa87ecc5c | yonggyulee/gitpython | /practice01/prob06.py | 579 | 3.6875 | 4 | #문제6. 키보드에서 정수로 된 돈의 액수를 입력 받아 오만 원권, 만원 권, 오천 원권, 천원 권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전 각 몇 개로 변환 되는지 작성하시오.
money = input("금액:")
print(money, type(money))
money = int(money)
value = 50000
a = 5
for i in range(10):
print('%d원 : %d개' % (value, money//value))
money %= value
a = 5 * ((i+1) %... |
15af66f61c1f130aa6242535ba3ac8a016958e0d | yonggyulee/gitpython | /02/03.list.py | 2,468 | 3.734375 | 4 | # 생성
l1 = []
l2 = [1, True, 'python', 3.14]
print('\n======================sequence 타입 특징============================')
# 인덱싱 (sequence 타입 특징)
print(l2[0], l2[1], l2[2],l2[3])
print(l2[-4], l2[-3], l2[-2], l2[-1])
# slicing
print(l2[1:4])
l3 = l2
l4 = l2[:]
print(l3)
print(l3 is l2)
print(l4 is l2)
print(l2[len(l2)::... |
d54e42fe882045fdcccd3a34e984f72520bc926e | machinebarker/Python_Advance_Calculator | /keling.py | 120 | 3.609375 | 4 | Phi = 3.14
r = float(input("Masukkan nilai jari-jari: "))
keling = 2*Phi*r
print("Jadi nilai keliling: " + str(keling))
|
ed92b3dbb578b29762acf5dd6f6a4f738da7d690 | roger0503/Guessing-game | /guessing_game.py | 583 | 4.09375 | 4 |
import random
num = random.randrange(10)
Guesses = 5
for i in range(1, Guesses+1):
guess = int(input("Enter your guess:"))
if(guess == num):
print("Your guess is correct!")
break
elif(guess > num and i < Guesses):
print("You are close, keep trying lower")
elif... |
f5d16aa2f450646289b53de99b16f9cf8b899778 | laueste/algorithms-ucsf-2019 | /hw3/alignment/utils.py | 794 | 3.71875 | 4 | # Some utility classes to represent a fasta sequence and a scoring matrix
class Sequence:
"""
A simple class for a sequence (protein or DNA) from a FASTA file
"""
def __init__(self, name, sequence='', header=''):
self.name = name #the file name
self.header = header #the name in the fil... |
107fb1edb7dd2a995c4c9b163b8f7ea255f1533f | melissathatblondie/snowflakePygame | /snowflake.py | 2,341 | 3.8125 | 4 |
import pygame
import random
# Some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
pygame.init()
# Sets the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)
bg = pygame.image.load("gwcpic3.png")
pygame.... |
ee8a92f165e86d4b17ada35b224bc68db1e59528 | aniljp97/DeepLearning | /Lab1/Source Code/classifcation.py | 3,912 | 3.609375 | 4 | """
Part 5:
Run-through of exploratory data analysis, evaluation, comments, and conclusions printed to the output.
Please follow through with the output.
Dataset: https://www.kaggle.com/jeevannagaraj/indian-liver-patient-dataset
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from ... |
11696c575bae8dd21f93451f2ec213d0f7518e73 | sanjaykvo/substring_palindrome | /substringpalindrome.py | 849 | 3.953125 | 4 | """ This program will create the substring of the string and check the substring or not. if the substring is a
palindrome then it will print the substring if anyone of the substring is not a palindrome it will print invalid
input. """
def pal(st):
if st == st[::-1]:
return 1
def l(s):
l1 ... |
840738469fffa42ed7a25b954fac5888d1cbe6a1 | mateuszlatkowski/projekt_sinwo | /algos/algorithms.py | 5,308 | 4.21875 | 4 | import math
class Euclidean:
def __init__(self):
self.algorithm_name = "Euclidean Algorithm"
def executes(self, a, b):
'''Method for computing the greatest common divisor of two numbers (a, b)'''
while(a!=b):
if(a>b):
a -= b
else:
... |
70a8c239ba87c9dff901ca51cffc205a96a574f0 | Knasten/battle_ships | /run.py | 4,095 | 4.125 | 4 | import random
# If player miss I will show an "-"
# If player hit I will show an "X"
# For water I will show "^"
# Variables turns and num_ship declared here and later changed by user.
# Size declared for board size here so grid 5x5
# admitted_input is used to verify row and column input from user
turns = 32
num_ship... |
8d6d347432112c3884102402bf0c269bcbd2ab89 | Preet2fun/Cisco_Devnet | /Python_OOP/encapsulation_privateMethod.py | 1,073 | 4.4375 | 4 | """
Encapsulation = Abstraction + data hiding
encapsulation means we are only going to show required part and rest will keep as private
"""
class Data:
__speed = 0 #private variable
__name = ''
def __init__(self):
self.a = 123
self._b = 456 # protected
self.__c ... |
10e98d3ce264b97ea09bd7ccb83261964a894b37 | Preet2fun/Cisco_Devnet | /DevNet/01-programming_fundamentals/file_read_write.py | 653 | 4.09375 | 4 | from datetime import datetime
log = "log_file.txt"
"""
when we use "with open" then we don't need to explicitly close open file , it will be atomically taken care
"""
def read_log(log):
with open(log, "r") as f:
print(f.read())
def write_log(log, data):
with open(log, "a") as f:
... |
38cc881c104071c107379271012465907a0b3fde | Preet2fun/Cisco_Devnet | /DevNet/01-programming_fundamentals/csv_reader.py | 229 | 3.546875 | 4 | import csv
raw_csv = open('text.csv').read()
print(raw_csv)
exp_csv = open('text.csv')
data_read = csv.reader(exp_csv)
for data in data_read:
print('{} is in {} with ip : {}'.format(data[0], data[2], data[1]))
|
cd9c959a5bc604f523799d07470931d281d79698 | paulc1600/Python-Problem-Solving | /H11_staircase.py | 1,391 | 4.53125 | 5 | #!/bin/python3
# ---------------------------------------------------------------------#
# Source: HackerRank
# Purpose: Consider a staircase of size n:
# #
# ##
# ###
#
####
#
# Observe that its base and height are both equal to n, and
# ... |
85b96d3983eb1391604fe96f454099584335ef5a | paulc1600/Python-Problem-Solving | /H15_PowerSum_hp.py | 7,709 | 4.0625 | 4 | #!/bin/python3
# ---------------------------------------------------------------------#
# Source: HackerRank
# Purpose: Find the number of ways that a given integer, X, can be
# expressed as the sum of the Nth powers of unique, natural
# numbers.
#
# For example, if X = 13 and N = 2, we... |
2cc6154799ccae67f873423a981c6688dc9fb2b5 | paulc1600/Python-Problem-Solving | /H22_migratoryBirds_final.py | 1,740 | 4.375 | 4 | #!/bin/python3
# ---------------------------------------------------------------------#
# Source: HackerRank
# Purpose: You have been asked to help study the population of birds
# migrating across the continent. Each type of bird you are
# interested in will be identified by an integer value. Each... |
dbfbeb14f596bb7c893440d263b581ddc7047199 | paulc1600/Python-Problem-Solving | /H17_kangaroo.py | 2,208 | 3.984375 | 4 | #!/bin/python3
# ---------------------------------------------------------------------#
# Source: HackerRank
# Purpose: You are choreographing a circus show with various animals.
# For one act, you are given two kangaroos on a number line
# ready to jump in the positive direction (i.e, toward
# ... |
49b44f2440ab260a432f2cb269e064d03712aeda | iiivvv/alg | /Хэширование/L3Z2.py | 316 | 3.671875 | 4 | def convert( s1 ) :
return ( s1[ 0 ].split() )
s1 = [' Сегодня вечером мы с моим другом видели красивый алый закат ']
b = convert( s1 )
s2 = [ ' R ' , ' k ' , ' r ' , 9 , ' m ' , ' I ' , ' S ' , 8 , ' A ' , ' O ' ]
for a in zip( b , s2 ) :
print( a ) |
02aece42d770b2fada73eeb263f196ca6d89dd54 | 826167518/python | /ceshi/zuqiu.py | 365 | 4 | 4 | #!/usr/bin/env python
# -*- conding:utf-8 -*-
x = str(raw_input("Enter sex m/f: "))
if x == "f" or x == "F":
n = float(raw_input("Enter age : "))
if n >= 10 and n <= 12:
print "Congratulations, you can join the team!!!"
else:
print "Unfortunately, you do not meet the requirements!"
else:
print "Unfor... |
41f531a819c7ece1e66b9d612375c801dd28f863 | hydrotop/PythonStudy | /test/098.py | 317 | 3.828125 | 4 | strdata=input('정렬할 문자열을 입력하세요.')
ret1=sorted(strdata)
ret2=sorted(strdata,reverse=True)
print(ret1)
print(ret2)
ret1="".join(ret1)
ret2="".join(ret2)
print('오름차순으로 정렬된 문자열은 <'+ret1+'>입니다.')
print('내림차순으로 정렬된 문자열은 <'+ret2+'>입니다.') |
9e5ab200350e382951898ec6046ca094abb8f5fa | aniszahrodl/Praktikum-Chapter-08 | /LATIHAN/12.py | 2,405 | 3.75 | 4 | def dataBuah():
print('>>>>DAFTAR HARGA BUAH<<<<')
for x,y in buah.items():
print('-',x,'(Harga: Rp.', y,')')
print('')
def tambah():
print('Masukkan nama buah yang ingin ditambahkan:',end='')
nama=input()
if nama in buah:
print('Buah',nama,'sudah ada di dalam daftar')
else:... |
7848000793ffb7f8426d7d95f0eea4645e63b0b2 | aniszahrodl/Praktikum-Chapter-08 | /LATIHAN/13.py | 901 | 3.71875 | 4 | print(' DAFTAR NILAI MAHASISWA')
print('----------------------------------------------------')
nilaiMhs = [{'nim' : 'A01', 'nama' : 'Amir', 'mid' : 50, 'uas' : 80},
{'nim' : 'A02', 'nama' : 'Budi', 'mid' : 40, 'uas' : 90},
{'nim' : 'A03', 'nama' : 'Cici', 'mid' : 50, 'uas' : ... |
e955679387cd90ad3e5dfbbff7f941478063823d | Hajaraabibi/s2t1 | /main.py | 1,395 | 4.1875 | 4 | myName = input("What is your name? ")
print("Hi " + myName + ", you have chosen to book a horse riding lesson, press enter to continue")
input("")
print("please answer the following 2 questions to ensure that you will be prepared on the day of your lesson.")
input("")
QuestionOne = None
while QuestionOne not in... |
93e2e4f5475a8cfc451625e077d618348447a121 | chabeerabsal/python | /program.py | 6,087 | 3.796875 | 4 | # decimal to binary
num=int(input('enter no'))
binary=''
while num>0:
rem=num%2
binary=str(rem)+binary
#print(rem)
num=num//2
else:
print(binary)
print(1%2)
# binary to decimal
import math
no=int(input('enter no'))
power=int(input('enter no'))
print(math.pow(no,power))
no=int(input('enter no'))
dec... |
5af4dd76f666dfc971b96135f7e31bc1d945e3cf | nurriol2/startup_scripts | /python/make.py | 1,168 | 3.515625 | 4 | #!/usr/bin/env python3
#module that allows access to command line input
import sys
import os
from github import Github
#module that hides typed keys; only use via command line
from getpass import getpass
#path to projects directory on machine
path = "/Users/nikourriola/Desktop/projects/"
#prompt for github username ... |
5fc8770f4652613aa2c1ee2de68a320a0d07ffad | jeetmeena/PyFun-Backend | /stage/Help with more python lessons for beginners (Part 5).py | 4,018 | 4.4375 | 4 | ##Variable Type
##Strings are defined either with a single quote or a double quotes
veriable_name="string"
#example 1
mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)
##python supports two types of numbers - integers and floating point numbers
ver_name=4 #integer
ver_name=4.0 #float
##Long intege... |
7b5ecddd9dd286db5182d1f9754dd30dcafc8481 | wujunwei928/python_study | /before_2016/2015-07/demo1.py | 1,392 | 3.9375 | 4 | #!/usr/bin/python
# _*_ coding: utf-8 _*_ # 指定字符编码的上面不能有空行, 否则报错
print 'Hello Python' #老版本直接print
print('测试') #新版本要print()函数, 文件中有中文的话, 文件开头要指定utf-8编码
# python中每条语句结尾的分号,可写可不写
print('hello');
# 但是如果一行中有多条逻辑语句的时候,必须以分号隔开,最后一条语句的分号可以省略
# 在python中, 一般每行语句最后的分号省略不写
print( 1+ 8);print( 3* 6)
# 定义整型变量
x=y=... |
df7e5dd7708411aea3f749997255bea5d5a8dd13 | Beisenbek/pp2-lecture-samples-2020 | /week5/today/4.py | 81 | 3.5 | 4 | import re
text = "av"
pattern = r"a+"
res = re.match(pattern, text)
print(res)
|
062f7f2539365c4e0144505720dc34cac5a22900 | Beisenbek/pp2-lecture-samples-2020 | /week2/dicts/4.py | 72 | 3.59375 | 4 | thisdict = {1:"a",2:"b"}
for x, y in thisdict.items():
print(x * x, y) |
e875f00f7f0f68d28aad89d0747c1bdc5e323fdc | mur6/exercises | /wordcount/wordcount.py | 422 | 3.6875 | 4 | from pathlib import Path
import sys
def wordcount(path):
with path.open() as fh:
lines = 0
words = 0
chars = 0
for line in fh:
chars += len(line)
words += len(line.split())
lines += 1
print(f"chars={chars} words={words} lines={lines} {pat... |
059ab3e13f6f705db7e90b7b3d37c5e9b81a8539 | anupamking01/image-processing | /distance.py | 365 | 3.703125 | 4 | # import math
px, py = map(int, input("enter coord of p: ").split())
qx, qy = map(int, input("enter coord of q: ").split())
print("eucledian distance between 2 pixels is:",((px-qx)**2 + (py-qy)**2)**(0.5))
print("manhattan distance between 2 pixels is:",abs(px-qx) + abs(py-qy))
print("chess-board distance betw... |
d74028fef519ab339955a57ab32d9502236c59ec | MangoMaster/chinese_pinyin_input_method | /src/char2/convert_pinyin.py | 3,544 | 3.671875 | 4 | import copy
import json
def load_table(table_path):
"""
Load table from table_path.
Args:
table_path: Path to the source table json file.
Returns:
table, a datastructure converted from json file.
"""
with open(table_path, 'r') as f:
return json.load(f)
def convert_p... |
2b73a75901607565c0aeaf785bdbc16b79d29a81 | Teju-mestry/PracticePython | /Exercise-Solution-Functions-Medium.py | 349 | 4 | 4 | # Define a function that adds two numbers and returns the result
def returnSum(numberOne, numberTwo):
return(numberOne + numberTwo)
# Declare two numbers
numberOne = 10
numberTwo = 20
# Declare a variable that would store the result of the returned function
additionResult = returnSum(numberOne, numberTwo)
print(add... |
20aae63f1956a2211f853bf1d509205904db4451 | Teju-mestry/PracticePython | /Marks apprecition.py | 1,202 | 3.96875 | 4 | import operator
x = int(input("how many students are present in class?"))
name = []
marks = []
dic ={}
if x>=3:
for i in range(0,x) :
n = input("Name of student {} = ".format(i+1))
name.append(n)
m = int(input("Marks of student {} = ".format(i+1)))
marks.append(m)... |
bcb7617ed059bbed6382b21a51ea43de2a406f10 | maxfer1221/rpi-bluetooth-tests | /findmyphone.py | 443 | 3.515625 | 4 | import bluetooth
target_name = "AL HydraMotion"
target_address = None
nearby_devices = bluetooth.discover_devices()
print(nearby_devices)
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print("foun... |
594d1a8d21079af653535af2c0617d866d2537e5 | xingleigao/study | /python/base-knowloage/for/test2.py | 167 | 3.65625 | 4 | #!/usr/bin/python
#coding =utf-8
fruits = ['banana','apple','mango']
for index in range(len(fruits)):
print('当前水果 : %s'%fruits[index])
print ('Good bye!') |
251aac02f6cc42c6b3146adc6bf2a8d314e32d9a | xingleigao/study | /python/base-knowloage/tuple/del.py | 129 | 3.640625 | 4 | #!/usr/bin/python
# codingg = utf-8
top = ('physics','chemistry',1997,2000)
print(top)
del top
print('After deleting top:',top) |
ea9baf6807a757adca26d6e0d8d295afbd41166c | xingleigao/study | /python/base-knowloage/function/tests7.py | 278 | 4.09375 | 4 | #!/usr/bin/python
# coding = utf-8
#可写函数说明
def printinfo( arg1, *vartuple ):
"打印任何传入的参数"
print('输出:')
print(arg1)
for var in vartuple:
print(var)
return
#调用printinfo函数
printinfo( 10 )
printinfo( 70, 60, 50) |
428daa8b1f6ad9dac313e849435390ce05155f2e | xingleigao/study | /python/base-knowloage/tuple/test1.py | 139 | 3.734375 | 4 | #!/usr/bin/python
top1 = ('physics','chemistry',1997,2000)
top2 = (1,2,3,4,5,6,7)
print('top1[0]:',top1[0])
print('top2[1:5]:',top2[1:5]) |
c2524e59714f938836553a0c964ab7936ca2058e | xingleigao/study | /python/base-knowloage/if/elif.py | 208 | 3.75 | 4 | #!/usr/bin/python
#coding = urf-8
num = int(input())
if num ==3:
print('boss')
elif num ==2:
print('user')
elif num ==1:
print('worker')
elif num <0:
print ('error')
else:
print ('rodman') |
27279a639ce31e647b7d18a6e05f1678c494d5cf | SerialSata/ITEA-PythonBasic | /lect 4 work.py | 3,856 | 4.15625 | 4 | # import random
#
# MAX_TRIES = 5
# secret = random.randint(1, 10)
# tries = 0
# # is_guessed = False
#
# while tries < MAX_TRIES:
# try:
# guess = int(input('You have 5 tries. Guess a number: '))
# except ValueError:
# print("Please, provide a number between 1 and 10")
# continue
# ... |
3963af4f201ab605c818b0307db4611ae722015c | noorulislam770/guass_seidel | /simple.py | 8,258 | 4.125 | 4 | import math
def main():
get_equations()
def get_equations():
eq1 = ["5x1","-2x2","3x3","-1"]
eq2 = ["-3x1","9x2","1x3","2"]
eq3 = ["2x1","-1x2","7x3","3"]
print("steps to enter equations : ")
print("Enter each coeff of x1 x2 and so on as ")
print("1 -1 2 0 0 1 and write 0 if there is no ... |
a3b8127727aab91acb49a0c57c81aa5bf8b7ea4a | atishay640/python_core | /comparison_oprators.py | 363 | 4.28125 | 4 | # Comparison operators in python
# == , != , > , < >= ,<=
a= 21
b= 30
c= a
print(a==b)
print(c==a)
print(a>=b)
print(a<=b)
print(a<b)
print('------------------------------------')
# Chaining comparison operators in python
# 'and' , 'or' , and 'not'
print(a == b and b == c)
print(a == b or a == c)
print(not a == 2... |
fd7715910c9fee1405c6599869252b112b098520 | atishay640/python_core | /dictionary.py | 891 | 4.4375 | 4 | # Dictionary in python
# It is an unordered collection
# Used 'key'-'value' pairs to store values.
# it is identified with {}
print("**********dictionary in python")
students_dic = {1 : 'Atishay' ,2 : 'Vikas' ,3 : 'Aakash' }
print(students_dic)
print("**********fetch value in python")
print(students_dic[2])
print... |
22e758582061d1f3f911afd3008c87b9e8c00bf3 | atishay640/python_core | /variable_assignment.py | 360 | 3.96875 | 4 | # Variable assignment
#
#
#
#
#
#
#
#
#
#
#
#
a = 5
print(a)
print("-----------")
print (a+a)
print("-----------")
a = 15 ;
print(a)
print("-----------")
a=a + a
print (a)
print("----Power-------")
print(5**5)
print("-----Yearly Income calcultor------")
income = 15000
months_in_a_year = 12
yearly_income = income *... |
2599892f0d1edf3a23907bad202b1d1b0f10328f | atishay640/python_core | /polymorphism.py | 922 | 4.15625 | 4 | # Inheritance in python
class Person:
def __init__(self,name,mob_no,address):
self.name = name
self.mob_no = mob_no
self.address = address
def eat(self):
print('I eat food')
class Employee(Person):
def __init__(self,name,mob_no,address,company_name):
Person.__init... |
e98c5729c38f3e6394f06efad7125981324ef230 | Anamican/design-patterns | /strategy/python/sorting_using_func_object.py | 585 | 3.65625 | 4 | # Sort by name
def sort_by_name(sort_list):
return sorted(sort_list, key=lambda dct: dct['name'])
# Sort by price
def sort_by_price(sort_list):
return sorted(sort_list, key=lambda dct: dct['price'])
products = [
{'name': 'Mobie', 'price': 12},
{'name': 'Camera', 'price': 20},
{'name': 'Flask', '... |
fcbcbde6b50cbfd2fb5c3ad21153c3c6a55981ac | jha-prateek/ML_basics | /gradientDescent.py | 1,220 | 3.859375 | 4 | from numpy import genfromtxt
data = genfromtxt("data.csv", delimiter=",")
N = float(len(data))
def get_error(m, b):
error = 0
for points in data:
x = points[0]
y = points[1]
error = error + (y - ((m * x) + b)) ** 2
return error/N
def gradient_descent(m_cur, b_cur, learningRate):
... |
cc6d670c6fcb735d6786dc77a655ccef7c769962 | kaanf/password_generator | /passwordGenerator.py | 1,533 | 3.65625 | 4 | import random
import os
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!$%&/#*="
class colors:
BLUE = '\033[94m'
CYAN = '\033[96m'
WARNING = '\033[93m'
GREEN = '\033[92m'
FAIL = '\033[91m'
ENDC= '\033[0m'
# Choose an option
def optionMenu():
... |
0d0892bf443e39c3c5ef078f2cb846370b7852e9 | JakobLybarger/Graph-Pathfinding-Algorithms | /dijkstras.py | 1,297 | 4.15625 | 4 | import math
import heapq
def dijkstras(graph, start):
distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph
# The distance to each vertex is not known so we will just assume each vertex is infinitely far away
for vertex in graph:
distances[vertex] = math.... |
bf1be45cd079f5cfec0d919ac02f25561447e90f | daehyun1023/Python | /LeeJehwan/scraper/1.THEORY/1.1.Lists_in_Python.py | 101 | 3.75 | 4 | days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days)
days.append("Sat")
days.reverse()
print(days)
|
730813969c03631faf3a7cc53472800540584152 | AndresF97/Adventure_Game | /Adventure_game.py | 3,136 | 3.859375 | 4 | import time
import random
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def intro():
print_pause('Welcome to New Jersey, some people say that you can find the portal to hell \n')
print_pause('luckly for you that your grandfather is a archyologist. \n')
print_pause('You mak... |
a6c88fb61ffcaa9709941f272d9b311720e97768 | pawsey18/day-2-3-exercise | /main.py | 445 | 3.953125 | 4 | # 🚨 Don't change the code below 👇
age = input("What is your current age?")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
int_as_age = int(age)
remaining_years = 90 - int_as_age
remaining_days = remaining_years * 365
remaining_weeks = remaining_years * 52
remaining_months = remaining_years... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.