blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8d6c0ba94d8ce91b549421a9e9d3bf9394f2f781 | Alberto-Oliveira-Barbosa/Desafios | /Python2/1008.py | 160 | 3.65625 | 4 | # -*- coding: utf-8 -*-
n = input()
horas =input()
valor = input()
salario = horas * valor
print ("NUMBER = %i" % n)
print("SALARY = U$ %.2f" % salario)
|
eabbe667a191d693dc7114f8b796a0b4ff849633 | vivi-and-tea/guess-the-number | /main.py | 1,281 | 4.125 | 4 | from art import logo
import random
print(logo)
NUMBERS = list(range(1, 101))
LIVES = 5
ANSWER = random.choice(NUMBERS)
def guess_number(lives):
if lives == 0:
print(f"The answer was {ANSWER}. GAME OVER")
return
guess = int(input("Guess a number from 1 to 100: "))
if guess == ANSWER:
print(f"The... |
2a923bfa052b052813e8f9193a43924b64800c0c | Dhrumil29/ArticleRecommendationSystem | /reverse_index.py | 497 | 3.5625 | 4 |
class ReverseIndex(object):
def __init__(self,text):
self.text = text.split()
#print self.text
self.index = dict()
#print self.index
def generate_index(self,mutator=lambda x:x):
self._generate_index(mutator)
def _generate_index(self,mutator):
... |
26e5f2178170e9abc721b0e0ddf3821d90fa8019 | ahbuckfire/tictactoe | /OOP/game.py | 1,881 | 3.921875 | 4 | class Game(object):
def __init__(self):
pass
def play_again(self):
"""
Prompt human for decision to play again or not until it inputs 'yes' or 'no'
Returns:
bool: True if play again ('yes'), False otherwise ('no')
"""
while True:
again = r... |
1aa5114e4b5638f3e91f5509a1befbc54ef4c85e | Jkker/basic-algo | /Chapter 8 - Shortest Path & Min Spanning Tree/Dijkstra SSSP.py | 676 | 3.703125 | 4 | DIJKSTRA(graph G, start vertex s, destination vertex d):
1 - let H = min heap data structure, initialized with 0 and s
#(0 indicates the distance from start vertex s)
2 - while H is non-empty:
3 - remove the first node and cost of H, call it U and cost
4 - if U has been previously explored:
5 - c... |
5d75172af12c9920d3b0904edfde338cca1699a3 | ElvarThorS/Forritun | /8.27.2020/advanced1.py | 475 | 4.125 | 4 | n = int(input("Input a natural number: ")) # Do not change this line
counter = 1
# Fill in the missing code below
while counter <= n:
if n ==1:
prime = False
break
elif n % 2 == 0 and n !=2:
prime=False
break
elif n % counter == 0 and counter == n or counter == 1:
pri... |
784d297f43d3d351499c642747c692b623298fbf | Athulya-Unnikrishnan/DjangoProjectBasics | /LaanguageFundamentals/python_collections/list_programs/seriesquestion_list.py | 168 | 3.90625 | 4 | value=[2,4,6]
print("Input list is ")
sum=0
for val in value:
sum+=val
print(sum)
print("Output list is: ")
for val in value:
out=sum-val
print(out,end=" ") |
8567e2a61382fa150988e176348b037e25e3bd39 | KurisuLim/pythonsChallenges | /chapter03/guess_my_number_limited.py | 1,212 | 4.28125 | 4 | #Guess My Number Limited Style
#
#The computer picks a random number between 1 and 100
#The player tries to guess it and the computer lets
#the player know if the guess is too high, too low
#or right on the money. As well as how many tries left
import random
print("\tWelcome to 'Guess My Number'!");
print("\t\tLimited... |
ec2cd1ed7b0823f1c5c622792d8ef9149f50b645 | higreenogre/Project-Sloth | /Conway's game of life.py | 3,155 | 3.5625 | 4 | def get_generation(matrix, generations):
cells = []
for i in range(len(matrix)):
cells.append([])
for j in range(len(matrix[0])):
cells[i].append(matrix[i][j])
n = 0
while n < generations:
cells = moore(cells); # For each step n+2xn+2 matrix is created to simu... |
aae246dcc9d502f22f486aa01d3deaa796944ab0 | KiaraRaynS/third_day_homework-18-5-16- | /word_histogram.py | 2,144 | 3.625 | 4 | import string
def histogram():
with open("sample.txt") as opened_file:
book = opened_file.read()
for x in string.punctuation:
book = book.lower()
book = book.replace(x,'')
book = book.replace(" ",'')
book_histogram = {}
ignore_words = ['a', 'able','about', 'across', ... |
ec9183e734cad0596ab43f203938ab2240767584 | Manmohit10/data-analysis-with-python-summer-2021 | /part01-e09_merge/src/merge.py | 791 | 3.828125 | 4 | #!/usr/bin/env python3
def merge(L1, L2):
len1=len(L1)
len2=len(L2)
mlist=[]
m=0
n=0
p=0
q=0
for i in range(len1):
if p or q == 1:
break
for j in range(len2):
if L1[m]<L2[n]:
mlist.append(L1[m])
m=m+1
... |
3151210e18b309282f8f17698d3a4cfc5f2399de | amarmulyak/Python-Core-for-TA | /hw06/yvasya/hw06_04.py | 756 | 4.3125 | 4 | """
Provide full program code of count_symbols(word) function which returns the dict with following structure:
{<symbol_1>: <number_in_word>, <symbol_2>: <number_in_word>,.....} or false when wrong input value.
word - type str.
EXAMPLE OF Inputs/Ouputs when using this function:
print count_symbols("abracadabra")
{'a': ... |
57351ee0f8ca23e2185bff57a0fce395b93892f2 | XBOOS/leetcode-solutions | /compare_version_numbers.py | 1,304 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a ... |
8d6f33234cff21032d9d2bb5c2879f1c863a4aae | PRATHAM1ST/Python-Projects | /TerminalShapes/creatingRectangles.py | 528 | 4.21875 | 4 | def rectangle(x, y):
count = 0 #counter
for b in range(x): #for making height
print('|', end = '')
for a in range(y): #for making width
if count == 0 or count == x - 1:
print('--', end='')
else:
print(' ', end ='')
pri... |
a13ca08a57ba34b85b33395974443340022bee9f | abhisheksingh75/Practice_CS_Problems | /Strings/Implement strStr().py | 1,382 | 3.984375 | 4 | """
strstr - locate a substring ( needle ) in a string ( haystack ).
Try not to use standard library string functions for this question. Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
NOTE: Good clarification questions:
What should be the return value if the... |
54bce6ccfa8820d46d55ae32625f79d7e0c4f96a | wilkinson/web-chassis | /misc/versus/python/blastoff.py | 405 | 3.5 | 4 | #- Python 2.x/3.x source code
#- blastoff.py ~~
# ~~ (c) SRW, 09 Aug 2011
import sys
def main(argv):
def countdown(n):
if (n <= 0):
return "Blastoff!"
else:
return str(n) + " ... " + countdown(n - 1)
print(count... |
4928252d5d1c118d9e0932de9915733a235fa094 | anemesio/Python3-Exercicios | /Mundo 03/ex084.py | 844 | 3.578125 | 4 | pessoas = []
dados = []
pesos = []
maior = menor = qttde = 0
while True:
nome = input('Nome: ')
peso = float(input('Peso: '))
dados.append(nome)
dados.append(peso)
pesos.append(peso)
pessoas.append(dados[:])
dados.clear()
qttde += 1
resp = input('Quer continuar: [S/N] ')... |
6fb228b19756d31637486290f86e51b6c34c5023 | yanlin025/user_login | /practice1.py | 1,475 | 3.953125 | 4 | # username = "seven"
# password = "123"
# _username = input("name:")
# _password = input("password:")
# if _username == username and _password == password:
# print("welcome")
# else:
# print("wrong username or password")
# username1 = "seven"
# username2 = "Alex"
# password = "123"
# count = 0
# w... |
18a35fefefa8291dba412a72aec0e3a5408cfa1b | varshitha8142/Binarysearch.io | /04_binary_search_io_programs.py | 735 | 4.3125 | 4 | """
The Fibonacci sequence goes like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number can be found by adding up the two numbers before it, and the first two numbers are always 1.
Write a function that takes an integer n and returns the nth Fibonacci number in the sequence.
Note: n will be less than or equal t... |
6c9c510d9a5668b6e98191a4cbd893c1df7a96a8 | longtaipeng/python_100_topic | /question4.py | 334 | 4.125 | 4 | """
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a
tuple which contains every number.Suppose the following input is supplied to the program:
"""
num_str = input('pelse input > ')
num_list = num_str.split(',')
num_tuple = tuple(num_list)
print(num_list)
print... |
5f1f77106a0adffc06abae04573ced3ae4a892d8 | jiyoung-dev/Algorithm | /Programmers/P나머지한점.py | 1,175 | 3.640625 | 4 | '''
https://programmers.co.kr/learn/courses/18/lessons/1878
직사각형을 만드는데 필요한 4개의 점 중 3개의 좌표가 주어질때, 나머지 한 점의 좌표를 반환하는 함수 작성.
v
----------------------
[[1,4], [3,4], [3,10]]
result
----------------------
[1,10]
'''
# 결과값으로 반환될 좌표는 입력된 세개의 좌표중, x와 y좌표에서 한번만 나온 값이다.
# 이중 리스트를 쪼개서 x와 y리스트에 각각 x, y ... |
6013e31e887ee9fb3bea957400b1a871ce5f2f00 | DFZephyr/CPO-Laboratory-works | /lab3/SingleLinkList.py | 3,586 | 3.578125 | 4 | from inspect import isfunction
class Node(object):
"""
node
"""
def __init__(self, value, next=None):
self.value = value
self.next = next
def initNode(value, next):
"""
:param value:
:param next:
:return: LinkList
"""
return Node(value, nex... |
c0da1c8f9f31492cdbbaa02f6fed02c8febb32b8 | Besufikad17/ChemistryTool | /Python/IUPAC.py | 1,414 | 3.765625 | 4 | from util import Constants, Character
class IUPAC:
""" IUPAC class contains a function used to name organic compounds.
Example: IUPAC i = new IUPAC("CH4");
i.getIUPACName(); . . . . . . methane """
def __init__(self, given: str):
self.given = given
def get_iupac_name(... |
f83f3fca220d1b8016b7fbae18c9ec0042fb18ec | Bodziowy/Party-Parrot-Puzzles | /Task04.py | 692 | 4.09375 | 4 | sample_input = "1 2 + 3 *"
final_input = "91.78 35.20 91.79 - + 29.09 82.39 96.03 - * *"
operator_list = ['+', '-', '*']
def reverse_polish_notation(input_string):
stos = []
for elem in input_string.split():
if elem not in operator_list:
stos.append(float(elem))
else:
... |
1d06da2024fe95ae981eb5ea389702644049338b | Karkanius/Security-Project | /security/sym_cipher.py | 3,904 | 3.546875 | 4 | """
=====================================================================================
Module: Security - Symmetric Keys Operations
AES Algorithm, CBC Mode, Key generated from a password
Version: 1.0 January 2020
Revision: 1
Authors: Paulo Vasconcelos, Pedro T... |
4165a247650a207d0fe9004ddd6dd73b4c3969fe | Badbeef72/Group-4-Chatbot | /bmi.py | 1,070 | 3.5 | 4 | # BMI calculator file.
import discord
import store
import random
client = discord.Client()
async def bmi_calculator(bmi_msg, height, weight):
# Converts reply to an integer.
bmi_height_int = float(height)
bmi_weight_int = float(weight)
# Calculates the BMI.
bmi_result = bmi_weight_int / (bmi_height... |
08bc3d8de8da7bdd9a1958a62eca907b6ad5b817 | amigo7777/-Pyhton-2 | /Прродолжайте говорить 'А'.py | 67 | 3.546875 | 4 | s = input()
while s[0] == 'а' or s[0] == 'А':
s = input()
|
9f10919074ee1c6388af2865375764a70acb0a6e | itsjessie/Python-Baseball | /stats/offense.py | 1,610 | 3.5625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from data import games
plays = games[games['type']=='play']
plays.columns= ['type','inning','team', 'player', 'count','pitches','event', 'game_id', 'year']
#print (plays)
hits = plays.loc[plays['event'].str.contains('^(?:S(?!B)|D|T|HR)'), ['inning','event']]
#print... |
18e5a82a3164199d19f3738372345a47034fa778 | kihyunchoi/COMP3522_Assignment2_A01054885_A01005378 | /Factory.py | 3,522 | 3.703125 | 4 | import abc
from Candy import CandyCanes, PumpkinCaramelToffee, CremeEggs
from Toy import SantasWorkshop, RCSpider, RobotBunny
from StuffedAnimal import EasterBunny, DancingSkeleton, Reindeer
class Factory(abc.ABC):
"""
A factory that creates shop items.
"""
@abc.abstractmethod
def create_candy(se... |
5467e6fd47d3b79dc370ae06cc785c17e059679f | ashleighb23124/RussATMMachine | /main.py | 1,303 | 3.65625 | 4 | from GHCDSAccount import Account
#import GHCDSAccount
KaisAccount = Account("Kai","Los Angeles","savings","56789")
MayaAccount = Account("Maya","Washington, DC","savings","12345")
MrRussAccount = Account("Mr. Russ","Washington, DC","checking","friedshrimp1")
AmaruAccount = Account("Amaru","Tokyo","Checking","109876... |
49f567a7bc471d19a66eca8894173aef96c49ffc | hadeelhhawajreh/data-structures-and-algorithms-c401 | /data_structures_and_algorithms/data_structures/ll_zip/ll_zip.py | 2,078 | 4.125 | 4 | """ Python program to merge two
sorted linked lists """
# Linked List Node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Create & Handle List operations
class LinkedList:
def __init__(self):
self.head = None
# Method to display the l... |
f2ec0623b51174eb53cdc455452ce2cbbb92ddfd | itbc-bin/1920-owe1a-afvinkopdracht2-ZoevdHeuvel | /Python 2.7.py | 459 | 4.1875 | 4 | #Zoe van den Heuvel, geschreven op 18-9-2019
#Boek opdracht 2.7, Miles per Gallon
#Use the formula "MPG=Miles driven/Gallons of gas used"
#Write a program that asks the user for the number of miles driven and the gallons of gas used.
#Then calculate the MPG and display the result
Miles_driven = int(input("How many mil... |
74366ed51c4b7a323bd93108c2a90e1a3a23913d | krazykoda/python-tutorials | /atm-app/db.py | 1,945 | 3.515625 | 4 | import os
import ast
base_path = "data/users/"
def create_user(email, data):
try:
if(user_exist(email)):
print("User already Exist. Please Use Another Email")
return False
else:
with open(base_path+email+".txt", "w") as f:
f.write(str(data))
print("User Created Succesfully")
return True
e... |
5b6ac368b68168de43f51d8d18eed4f758a44f75 | Antonio-Nappi/AADS | /Exercise5.py | 1,418 | 3.5625 | 4 | import random
import time
from graphs.my_graph import My_graph
def color_vertex(graph):
#Si poteva non fare l'ultimo ma computazionalmente è la stessa cosa perchè fare un confronto è come fare un
#assegnazione (entrambe O(1)) quindi abbiamo lasciato così
for vertex in graph.vertices():
if vertex.c... |
9abc8008e20e6ec2a9e8ec13e17f1cd5dc3d96ec | jinglepp/python_cookbook | /04迭代器与生成器/04.08跳过可迭代对象的开始部分.py | 2,572 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# 问题
# 你想遍历一个可迭代对象,但是它开始的某些元素你并不感兴趣,想跳过它们。
#
# 解决方案
# itertools 模块中有一些函数可以完成这个任务。 首先介绍的是 itertools.dropwhile() 函数。
# 使用时,你给它传递一个函数对象和一个可迭代对象。
# 它会返回一个迭代器对象,丢弃原有序列中直到函数返回Flase之前的所有元素,然后返回后面所有元素。
#
# 为了演示,假定你在读取一个开始部分是几行注释的源文件。比如:
with open('somefile.txt') as f:
for line in f:
print(li... |
706b96b635ea7bcc7cd45bb1845df8d4a87b04a0 | bgramesh76/kumar | /python_file4.py | 545 | 4 | 4 | #! /usr/bin/python3
print("this is python file 4")
users = ['val', 'bob', 'mia', 'ron', 'ned']
num_users = len(users)
<<<<<<< HEAD
print("We have " + str(num_users) + " users.")
print(users.sort())
print(users.sort(reverse=True))
print(sorted(users))
print(sorted(users, reverse=True))
print(users.reverse())
for use... |
c539a15351489c1f2543c9d5fc3c4065366fc498 | green-fox-academy/florimaros | /week-4/thursday/gyak2.py | 191 | 4.28125 | 4 | numbers = [3, 4, 5, 6, 7]
#write a function that filters the odd numbers
#from a list and returns a new list consisting
#only the evens
def reverse(input_list):
print(reverse(numbers))
|
9e733688b62c4aa28420bb08cbe7333334bef53d | dhina016/Student | /class/pattern2.py | 374 | 3.8125 | 4 | '''
*
* *
* * *
* * * *
* * * * *
'''
a = int(input())
space = 2 * (a-1)
for i in range(a):
print(" "*space, end="")
space -= 2
for j in range(0,i+1):
print("*",end=" ")
print()
space = 2
for i in range(a-1, 0, -1):
print(" "*space, end="")
space += 2
for j ... |
39a144c452c6172d22488bb3c3cf07016a10baab | ankithmjain/algorithms | /binarytreebfs.py | 685 | 3.953125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
else:
if node.value > root.value:
if root.right is None:
root.right = node
... |
62ec418fd99371727870460c5b1e573f87872e5e | decoded-cipher/Learn.py | /AgeCalculator.py | 1,231 | 4.21875 | 4 | from datetime import date
def findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year):
month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (birth_date > current_date):
current_month = current_month - 1
current_date = current_date + month[birth_month-... |
f7afe8d20adb0fd6698f871de7f8541272f2799b | shreykoradia/Python-with-Data-Science | /prac6-5.py | 214 | 3.609375 | 4 | str1 = "English = 78 Science = 83 Math = 68 History = 65"
str2 = str1.split(' ')
nums = 0
count= 0
for i in str2:
if i.isdigit():
nums+= int(i)
count+=1
print(nums)
print(nums/count) |
01bec2af6f7d8651f989e7bf056c6be780653785 | jorjiang/hams_data | /preprocessing.py | 3,826 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 13 00:12:22 2018
This file contains functions pre-process the data, including:
get_processed_data()
train_valid_test_split()
@author: Jiang Ji
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import scale, LabelBinarizer
from keras.utils... |
22c43b6e1d80af3d78c07319e26e09a1b3b2e3b0 | jonasht/CursoEmVideo-CursoDePython3 | /mundo1-Fundamentos/029 - Radar eletrônico.py | 128 | 3.53125 | 4 | km = int(input('Km: '))
if km > 80:
pre = 7 * (km - 80)
print('multa de R${}'.format(pre))
else:
print('sem multa')
|
4aa2a0139e2b14e2652b9d8ba40578f6a9718758 | ARRAJIAyoub/randomwalk_project | /rectangle/rectangle_util.py | 1,223 | 3.734375 | 4 | import random
import numpy as np
from matplotlib import pyplot as plt
import math
#setting the boundary conditions
def boundary(point, length, width,f_up, f_down, f_left, f_right):
for i in range(1, width):
point[0][i] = f_up(i)
point[length][i] = f_down(i)
for i in range(1, length):
po... |
cf3756605f44d7487b3dc75a0ee95a2413275377 | Szermekm/To-do-App | /main.py | 1,954 | 3.578125 | 4 | import sys
file_name = 'tasks.txt'
def print_usage():
print("""
Command Line Todo application
=============================
Command line arguments:
-l Lists all the tasks
-a Adds a new task
-r Removes an task
-c Completes an task""")
def read_file(file_path):
try:
... |
89b64ad3c5d46231bd56626cbd39620733072f61 | Fullmoon8507/PythonPracticeProject | /apply/ABCMeta_test3.py | 463 | 3.796875 | 4 | from abc import *
class Abstract(object, metaclass=ABCMeta):
@classmethod
@abstractmethod
def hello(cls):
print("Abstract hello")
class Implement(Abstract):
def hello(self):
print("Implement hello")
if __name__ == "__main__":
# 抽象クラスの抽象メソッドがクラスメソッドでも、
# 実装クラスはインスタ... |
86ef8a89d517b083eb2fa6d6b0c16a4655588a9d | ManishKadayat/CyberStorm | /Kevin/typing2.py | 498 | 3.578125 | 4 | password = raw_input()
timings = raw_input()
print "password = {}".format(password)
print "timings = {}".format(timings)
password = password.split(",")
password = password[:len(password) / 2 + 1]
password = "".join(password)
print password
timings = timings.split(",")
timings = [float(a) for a in timings]
keypress ... |
c82f6c4702c3f13060bcd281b9ba60a759ba6635 | kylebeard56/573proj2 | /server.py | 3,624 | 3.734375 | 4 | """
NC STATE CSE 573 PROJECT 2
@author kylebeard, hongyifan
------------------------------
The server listens on the well-known port 7735. It implements the receiver side of the Stop-and-Wait protocol,
as described in the book. Specifically, when it receives a data packet, it computes the checksum and checks
whether ... |
3d390d7d50f009bf9aaa30677332ed3d637a44d5 | SonoDavid/python-ericsteegmans | /CH1_integer_arithmetic/leapyear.py | 411 | 4.28125 | 4 | # Check whether a given year is a leap year.
# A year is a leap year if it is a multiple of 4 and
# not a multiple of 100, or it is a multiple of 400.
#
# Author: Joachim David
# Date: June 2019
year = int(input("Enter the year to examine: "))
if ((year % 4 == 0) and not (year % 100 == 0)) or (year % 400 == 0):
... |
f1026f41fa0c915dd7b560ca6b4340d766d519b4 | rafaelpascoalrodrigues/learning | /IBM_PY0101EN/module02/02_list.py | 3,176 | 4.5625 | 5 | # Lists are ordered sequence of elements contained by square brackets
# and separated by commas
[5.6, 87.8, 8.7, 9.1, 2.3]
list1 = ['first', 'second', 'third']
list2 = [10, 9, 5, 7, 2, 6]
# Tuples can be convert in to lists
list3 = list(('forth', 'fifth', 'sixth')) # it returns ['forth', 'fifth', 'sixth']
# Lists ca... |
2012c1c16fe4a43fddf746d4cf3d8ae44618e9b5 | Yet-sun/python_mylab | /Lab_projects/lab2/Lab2_06.py | 1,019 | 4.0625 | 4 | '''
需求:
编写程序,莫尔斯电码采用了短脉冲和长脉冲(分别为点和点划线)来编码字母和数字。
例如,字母“A”是点划线,“B”是点划线点点。见附件“完整的摩尔斯电码表.txt”
1)创建字典,将字符映射到莫尔斯电码。
2)输入一段英文,翻译成莫尔斯电文。
'''
def mostran(str):
f=open("D:\\实验2完整的摩尔斯电码表.txt","r")
mostext=""
for line in f:
mostext+=line #把每一行读取出来添加到一个字符串中
f... |
b7ee293867d47513acfb7d861c6fa742d1f2dc73 | kartik0001/Day9 | /Classes And Modules 2(OOPs)/Q4.py | 467 | 4 | 4 | # Q4.
class Shape:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def Area(self):
print(self.length * self.breadth)
class Rectangle(Shape):
pass
class Square(Shape):
pass
print("Area of rectangle:",end=' ')
rect=Rectangl... |
d2c45dcd9a57c76de03a3194962d6758a2c5199e | SaiSrinivas-10/INFytq | /Assignments/day8_exer38_lambda.py | 535 | 4.5 | 4 | '''rite a python lambda expression for the following:
Find the modulo of two numbers and add it to the difference of the same two numbers.
Find the square root of a number using math library built-in function.
Find the square root of a number without using built-in function.'''
import math
num1=36
num2=7
num... |
752897fc9718ffea255a635ce7561d23cb06db6a | xooxoo/homework | /task_rpn.py | 748 | 3.765625 | 4 | """
def convert(expr):
op = []
num = []
for i in expr:
if i == '(' or i == ')':
op.append(i)
elif type(i) is int:
num.append(i)
elif i == '+' or i == '-':
if '(' and ')' in op:
op.remove('(')
op.remove(')')
... |
fdc1fd6ffb1de62f1862f2ca7199d3ee582d3f72 | zhaochenf/test | /PycharmProjects/untitled/daima/day02.py | 13,016 | 3.75 | 4 | # -*- coding: utf-8 -*-
#模拟天猫登录脚本
# name = input("请输入用户名")
# password = input ("请输入密码")
#
# if name =="赵晨飞":
# if password == "123456":
# print("登录成功")
# else:
# print("密码错误,登录失败")
# else:
# print("登录失败,登录失败")
# num_1=10
# num_2=20
# 1、 * 应用于多个数字变量的求积
# h=num_1*num_2
# print(h)
# 2、 / 应用于多个数... |
81cf38668705ce035fffe5edd301d350ee420f87 | nileshpaliwal/Data-Structures-Algorithms-Nanodegree-Program | /Project3/Problem2/problem_2.py | 1,556 | 3.71875 | 4 | def rotated_array_search(input_list, number):
if len(input_list) == 0:
return -1
left=0
right=len(input_list)-1
while left<right:
mid = int( left +(right - left)/2)
if input_list[mid]>input_list[right]:
left = mid+1
else:
... |
5bf6b4952a70677761a631b5f9b439567ecc8c08 | hjungj21o/Interview-DS-A | /lc_binary_tree_practices/144_preorder_traversal.py | 1,717 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
# #iterative
# if ... |
993944f78ba2852828ae819eb12422a5a81d8e1d | uyen-carolyn/Arista-Internship | /python-practice-code/fibonacci-time.py | 1,019 | 4 | 4 | #!/usr/bin/python
print "--- Welcome to Fibbonacci Time! ---"
looper = True
while looper:
f = raw_input("Please enter the number you want to go up to or press 'q' to quit: ")
if f == 'q':
looper = False
else:
print "Here are your number(s): "
... |
532e353aef10831de12938614d4b15a77be791ea | GSvensk/OpenKattis | /LowDifficulty/reversebinary.py | 158 | 4 | 4 | # "{0:b}".format(n) turns n into binary, n[::-1] reverses n
# and int(n,2) turns n into base 10 from binary
print(int("{0:b}".format(int(input()))[::-1], 2))
|
86b76022f67097601f060e34def8f45519d473ee | CristianGastonUrbina/Curso_Python | /Clase03/informe.py | 2,869 | 3.796875 | 4 |
"""
def costeCamion(nombreArchivo):
suma = 0
with open (nombreArchivo,"rt") as f:
header = next(f)
for file in f:
try:
linea = file.split(",")
suma=suma + int(linea[1])* float(linea[2])
except ValueError:
print("Error en el archivo, la fruta",linea[0],"esta incompleta y se saco del calculo")
r... |
c002026499e622fcf54e054ca91d8caab5c37c3a | JKChang2015/Python | /w3resource/basic/Q017.py | 388 | 3.84375 | 4 | # -*- coding: UTF-8 -*-
# Q017
# Created by JKChang
# Wed, 31/05/2017, 15:34
# Tag: interval
# Description: Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n):
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print((near_thousand(1000)))
print((near_thous... |
6dbe6a9f10656c80c475400c26841ae6b93ac3bc | goodgodboy/clothoid | /clothoid_3.0.py | 1,629 | 4.09375 | 4 | """
功能:欧拉螺线(羊角螺线)
作者:焦奎洸
版本:3.0
2.0新增功能:运算次数增大,呈现螺旋
3.0新增功能:火树银花
日期:2020/5/16
"""
import turtle
# 引入turtle绘图库
def draw_clothoid_line(fun_length, fun_angle, fun_times):
"""
功能:绘图函数(迭代)
:param fun_length: 函数内部单位长度
:param fun_angle:函数内部单位角度
:param fun_times:函数循环次数
:return:... |
e41c1dffef6e32c6ce785f000d13f3fecb3abab3 | DanielLosada/ADM-Homework1 | /Strings.py | 5,353 | 4.15625 | 4 | #sWAP cASE
def swap_case(s):
return s.swapcase()
#String Split and Join
def split_and_join(line):
return "-".join(line.split(" "))
#What's Your Name?
#
# Complete the 'print_full_name' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
... |
4eac5201752fa5b05673c49fc92efb7ab03a9cbf | iamrishap/PythonBits | /InterviewBits/binary-search/median-of-array.py | 6,032 | 3.78125 | 4 | """
There are two sorted arrays A and B of size m and n respectively.
Find the median of the two sorted arrays ( The median of the array formed by merging both the arrays ).
The overall run time complexity should be O(log (m+n)).
Sample Input
A : [1 4 5]
B : [2 3]
Sample Output
3
NOTE: IF the number of elements in the... |
67e1794c4669f02d9af446858335265fe011a6b8 | coc-gatech-newelba/elbalog | /src/learning_model.py | 1,307 | 3.578125 | 4 | """Abstract learning model for anomaly detection."""
from sklearn.metrics import precision_recall_fscore_support
class LearningModel:
"""Abstract learning model."""
def __init__(self, model):
"""Initialize a learning model.
model -- [object] Learning model.
"""
self._model ... |
af2965a4fb2eac538db9e03faeeb274bdc1a24ff | mina0805/Programming-with-Python | /Programming_Basics_with_Python/06.Чертане на фигурки с цикли/06.Square_frame.py | 270 | 3.796875 | 4 | n = int(input())
plus = "+ "
minus = "- "
post = "| "
for row in range(n):
if row == 0:
print(plus + minus * (n-2) + plus)
elif 0 < row < n-1:
print(post + minus * (n-2) + post)
elif row == n-1:
print(plus + minus * (n - 2) + plus)
|
8757fbe34972c1917ece12f34ecaab62e0576426 | rheedaanur/Belajar-Biopython | /code/DNAtoolkit.py | 3,271 | 3.65625 | 4 | """
Yang Belajar: Nurhidayah Nordin
Tarikh: 2021=11-06
Tujuan: Saja nak belajar
"""
#Baca DNA
#-Pastikan yang dibaca ialah DNA
#Transkrip ke RNA
#Terjemah kepada Protein
from structures import *
# "GAKDAKCNAIWFHHDAOEFJWWODHWHFWO" setiap huruf ada tak dalam NukleotidaDNA?
def validate_string(DNAstr):
"""
... |
05082802d89cabead16090a9f32f6b7504ea200b | tamaranesterenko/Python.LR_7 | /Zadanie_1.py | 240 | 3.640625 | 4 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
a = list(map(int, input().split()))
s = 0
for item in a:
if item>3 and item<8:
s += item
print(s)
|
9d414a83cde5e6c20701014a45ced7ced64be5b5 | govardhananprabhu/DS-task- | /interleaved.py | 1,699 | 3.859375 | 4 | """
Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is preserved.
In des
First line contain three space separated strings.
Ot d... |
3c06ec53c980b5d397c3e04417760166c00e80c7 | ggopher/Python_GetStarted | /Lesson3/task6.py | 1,081 | 4.3125 | 4 | """
Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и
возвращающую его же, но с прописной первой буквой.Например, print(int_func(‘text’)) -> Text
"""
def int_func(string: str)-> str:
"""
Делаем певрую букву в строке заглавной
:param string: str
:return: str
"""
ret... |
fc790e658ea37ee586efc1f3d91581128995328c | alexstolr/Cyber-security-defense-of-network-based-environments | /final project/icmp_tunnel/icmp_client.py | 2,092 | 3.578125 | 4 | #!/usr/bin/python
"""
# This is an implementation of a simple ICMP Tunnel client
# as part of a final project of 'Cyber security defense of network
# based environments' course.
# the tunnel will transfer simple data such as plain text
# Authors: Alex Stoliar & Hen Mevashev
"""
from scapy import route
from scapy.layers... |
f1a1a114be9f18e1db141e0ef235f6bca240d070 | imagicgang/CP3-Thanapon-Pumeechokchai | /Exercise5_1_Thanapon_P.py | 301 | 4.125 | 4 | print("Calculator Program")
print("--------------------")
x = float(input("Number 1: "))
y = float(input("Number 2: "))
print("--------------------")
print("Result of Number 1+2 is:",x+y)
print("Result of Number 1-2 is:",x-y)
print("Result of Number 1*2 is:",x*y)
print("Result of Number 1/2 is:",x/y) |
c156796b98c39938f1c547d2a346fa75ad90e145 | tj2036/Hackbright- | /bill_calculator.py | 817 | 4.09375 | 4 | bill_amount = raw_input("What is the bill amount?")
bill_amount = float(bill_amount)
tip = raw_input("What is the tip percentage?")
tip = float(tip)
people = raw_input("How many people in the group?")
people = int(people)
def calculate_tip(bill, tip_percent):
percent = tip_percent/100.0
total_tip = bill*percen... |
b05d483a5eda5a48c71e382eccb693daa3268dd7 | ioanzicu/python_for_informatics | /ch_4_functions/ch_4_random_numbers.py | 316 | 3.671875 | 4 | import random
for i in range(10):
x = random.random()
print(x)
print('Random number between 5 and 10 inclusive: ', random.randint(5, 10))
print('Random number between 5 and 10 inclusive: ', random.randint(5, 10))
some_numbers = ['one', 'two', 'tree']
print('Random choice: ', random.choice(some_numbers))
|
b66f1801993d33c3511586d869e92c1196187df0 | comprobo18/comprobo18 | /simple_filter/scripts/simple_kalman.py | 4,463 | 3.53125 | 4 | #!/usr/bin/env python
"""
This script implements a Kalman filter for the system:
x_0 ~ N(0, sigma_sq)
x_t = x_{t-1} + w_t, w_t ~ N(0, sigma_m_sq)
z_t = x_t + v_t, v_t ~ N(0, sigma_z_sq)
"""
import matplotlib.pyplot as plt
import rospy
from numpy import arange
from numpy.random import randn
from math ... |
1c2b0e507fb4e431235ed56484b47743a26310e4 | hdmcspadden/CS5010 | /Module05/primes_fail1.py | 1,154 | 4.5 | 4 | # File: primes_fail1.py
# CS 5010
# Learning Python (Python version: 3)
# Topics:
# - Unit testing / debugging code
# - Using primes example
# - **inserting errors to show how primes_test can fail**
def is_prime(number):
# Return True if *number* is prime
#if number < 0: # Negative numbers are not ... |
38da6c950ac15044cbe608bc7f0c9e7f424bc4e3 | RomanKhudobei/Intro-to-Computer-Science-course | /gamers_network/gamers_network.py | 8,012 | 3.953125 | 4 | # Example string input. Use it to test your code.
example_input="John is connected to Bryant, Debra, Walter.\
John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\
Bryant is connected to Olive, Ollie, Freda, Mercedes.\
Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man... |
07cc7116609ef7c23f925fbb0bd1c98ece4b04ab | Viiic98/holbertonschool-machine_learning | /pipeline/0x01-apis/4-rocket_frequency.py | 910 | 3.703125 | 4 | #!/usr/bin/env python3
""" script that displays the number of launches per rocket """
import requests
if __name__ == '__main__':
rockets = {}
r = requests.get('https://api.spacexdata.com/v4/launches')
if r.status_code == 200:
launches = r.json()
for launch in launches:
rocket_id... |
b3041b79dd0081888b4db94255ad78f9719ca59d | kshitiz-upes/Python | /Nested_lists.py | 357 | 3.515625 | 4 | score_sheet = []
mark_sheet = []
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
score_sheet.append(score)
mark_sheet.append([name, score])
a = sorted(list(set(score_sheet)))[1]
for name,score in sorted(mark_sheet):
if score == a:
print(name)
... |
9aaa8c5f1e855655495c2a1ccdf91b04c054c2c5 | awong05/epi | /replace-and-remove.py | 1,390 | 4.1875 | 4 | """
Consider the following two rules that are to be applied to an array of
characters.
- Replace each 'a' by two 'd's.
- Delete each entry containing a 'b'.
For example, applying these rules to the array <a,c,d,b,b,c,a> results in the
array <d,d,c,d,c,d,d>.
Write a program which takes as input an array of characters, ... |
9a6bdae19747fdfadad33a0b84cca4db248cc4b3 | datstar2/python-basic | /practice03/03.py | 1,037 | 3.609375 | 4 | # 문제3.
#
# 중첩 루프를 이용해 신문 배달을 하는 프로그램을 작성하세요. 단, 아래에서 arrears 리스트는 신문 구독료가 미납된 세대에 대한 정보를 포함하고 있는데, 해당 세대에는 신문을 배달하지 않아야 합니다.
#
#
# apart = [[101, 102, 103, 104], [201, 202, 203, 204], [301, 302, 303, 304], [401, 402, 403, 404]]
# arrears = [101, 203, 301, 404]
#
#
# 실행 결과:
#
# Newspaper delivery: 102
# Newspaper delive... |
7b187a13055a7964bc42ee0883fe4f20eda00fbe | jbarcia/Python-Books | /Python Crash Course/Part 1 - Basics/Ch8 - Functions/Return_Values.py | 1,535 | 4.4375 | 4 | #! /usr/bin/python
# Returning a Simple Value
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
print()
# Making an Argument Optional
def get_... |
7b0b0867c740644d2a01879b4a562480c35fa244 | Luriii/programming_practice_2020 | /Turtle/Turtle part 1, 4.py | 417 | 3.84375 | 4 | import turtle
import math
turtle.shape("turtle")
turtle.color("olive")
turtle.width(2)
turtle.speed(5)
for i in range(10, 110, 10):
turtle.forward(i)
turtle.left(90)
turtle.forward(i)
turtle.left(90)
turtle.forward(i)
turtle.left(90)
turtle.forward(i)
turtle.right(45)
turtle.penup()
... |
1dee83dc7dddcad33b9986a1146af6ff7fa0da65 | muhozhyk/pythonintask | /IVTp/2014/Solokhin/2.py | 621 | 3.515625 | 4 | # Задача 2. Вариант 19.
# Напишите программу, которая будет выводить на экран наиболее понравившееся вам
# высказывание, автором которого является Эсхил. Не забудьте о том, что автор должен быть
# упомянут на отдельной строке.
# Солохин Н.И.
# 24.06.2016
print('Казаться глупым мудрому не страшно.\n')
print('... |
c47a541c220c89a657cdcb5833aed4f41e452d2b | zhangbailong945/pyqt5test | /test/15thread/thread3.py | 1,923 | 4.15625 | 4 | '''
queue 队列
Python 的 Queue 模块中提供了同步的、线程安全的队列类,
包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,
和优先级队列 PriorityQueue。
这些队列都实现了锁原语,能够在多线程中直接使用,
可以使用队列来实现线程间的同步
qsize() 返回队里大小
empty() 队列为空,返回True
full() 队列满了,返回True
full 大小
get(block,timeout) 获取队列,timeout等待时间
get_nowwait() 相当于get(False)
put(item) 写入队列
put_nowait(item) 相当于put(F... |
883e7767d58d29629c42b16c985b98b1f94c8b9e | Diveslon/Diveslon | /task51.py | 3,632 | 3.546875 | 4 | documents = [
{"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
{"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
{"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
'1': ['2207 876234', '11-2'],
'... |
5653a125568bc910bf8e56b96ff96e2a2e091b6e | scttohara/intro_to_python_class_labs | /lab7/passwords.py | 9,508 | 4.15625 | 4 | """
Program to check that 2 strings (should be same password twice) match
Requirements:
Passwords Must
be at least 8 characters long.
contain at least:
one alphabetic character (a letter from a-z or A-Z);
one numeric character (a digit from 0-9);
one character that is not alphabetic or numeric (! # @ $ % for example ... |
0dbaaf6e2fe2e5daf521575307c550edbf528dcf | odipojames/password-ip | /run.py | 6,025 | 3.890625 | 4 | #!/usr/bin/env python3.6
from password import User , Credential
def create_profile(first_name,last_name,password):
'''
function to create a new user
'''
new_user = User(first_name,last_name,password)
return new_user
def save_user(user):
'''
function that saves new users
'''
User.sa... |
d2dbf093eec1267f11a79ae07e60614f6f53a8d4 | ms10596/forecasting | /load.py | 458 | 3.5 | 4 | from datetime import datetime
import pandas as pd
def load_excel():
df = pd.read_excel('dataset.xls')
df = df[(df['Category'] == 'Furniture') | (df['Category'] == 'Office Supplies')][['Order Date', 'Sales']]
df['Year'] = df['Order Date'].dt.year
df['Month'] = df['Order Date'].dt.month
df['Date'] ... |
e92af75a592e6cc94057c7de95d758fb1fd72904 | satojkovic/algorithms | /python/binary_search.py | 2,337 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
def binary_search(data, target):
def _binary_search(data, target, left, right):
if left > right:
return -1
mid = left + (right - left) // 2
if data[mid] == target:
return mid
elif data[mid] > target:
r... |
6604bf38c8fa26953622365ab54987d0d425a4d2 | scls19fr/openphysic | /python/oreilly/cours_python/chap12/rect_carre.py | 1,333 | 3.84375 | 4 | #! /usr/bin/env python
# -*- coding: Latin-1 -*-
####################################
# Programme Python type #
# auteur : G.Swinnen, Lige, 2003 #
# licence : GPL #
####################################
class Point:
"""point mathmatique"""
def __init__(self, x, y):
self.x... |
63ff2ee802221ab83ba85725db660534e3553b60 | kensworth/adv-py | /tree-width.py | 1,208 | 4.125 | 4 | # Given a binary tree calculate its width where width is the length of the longest path in the tree.
def width(node, heights):
if not node.left and not node.right:
return 0
left_height = heights.get(node.left, -1)
right_height = heights.get(node.right, -1)
width_through_root = 2 + left_height +... |
49e0b6ceac268a65e65ad84e30f2e7ec91ec4402 | LizaChelishev/class1010 | /page15_9.py | 153 | 4.0625 | 4 |
number = int(input('Enter a number between 10 and 99: '))
tens = number // 10
units = number % 10
print('The new number is: ' + str(units) + str(tens))
|
0b3f9ea58cabf8fe80ddcbc15198c24127660136 | ClaytonStudent/RL-Go | /Board.py | 1,118 | 4.125 | 4 | class Board(object):
"""
Board for games
"""
def __init__(self,width=8,height=8,n_in_row=5):
self.width = width
self.height = height
self.states = {} # 记录当前棋盘的状态 Key:位置 value:棋子
self.n_in_row = n_in_row
def init_board(self):
if self.width < self.n_in_row or... |
193c26c1bcea1f51f03e27a4cf4f0ec0618233d6 | ahmadreza-smdi/adsem | /branch1.py | 2,118 | 3.78125 | 4 | def bfs(current,goal):
leaf = [[current]]
expanded = []
expanded_nodes=0
while leaf:
i = 0
for j in range(1, len(leaf)):
if len(leaf[i]) > len(leaf[j]):
i = j
path = leaf[i]
leaf = leaf[:i] + leaf[i+1:] #DELETE THE LEAF HAS BEEN SELECTED FRO... |
5eea477c610b1b95b7be92fd30c37a167b39de24 | 1574930549/Python | /test/Python 函数.py | 795 | 3.90625 | 4 | # 定义函数
def printme(str):
"打印任何传入的字符串"
print(str)
return
# 调用函数
printme("我要调用用户自定义函数!")
printme("再次调用同一函数")
# 可写函数说明
def changeme(mylist):
"修改传入的列表"
mylist.append([1, 2, 3, 4])
print("函数内取值: ", mylist)
return
total = 0 # 这是一个全局变量
# 可写函数说明
def sum(arg1, arg2):
... |
a5ece92d0675fd904ca0201a2799d35bf8f9ae5f | mliang810/itp115 | /Labs/Lab 4-1/Practice.py | 1,100 | 4.125 | 4 | '''
num = int(input("give me a number: "))
#any number between 3-5 is winner (including 3 and 5)
if num >= 3 and num <= 5: # or write 3 < num < 5
print("you win")
print("good for you")
elif num<=2 and num >=5:
print("so close")
else:
print("you lose")
'''
'''
num = 10
while num <= 10 and num > 0:
p... |
ec61c0fb3979689617f64741104b7b9f3d95b54e | dedpanda/pyexercises | /guessNumber.py | 529 | 3.921875 | 4 | def guessNumber():
answer = ""
while answer != "q":
list = [4, 21, 45, 69, 99]
answer = input("Guess a number between 1 to 100 (or press \"q\" to quit): ")
if answer == "q":
print("You pressed \"q\" to exit the program")
else:
answer = int(answer)
for i in list:
if answer == i:
pr... |
765bd9b181edcdc60af3aa2d05458208b7035e66 | Luckyaxah/leetcode-python | /树_N叉树的最大深度.py | 835 | 3.75 | 4 |
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def maxDepth(self, root: 'Node') -> int:
def process(root):
if not root:
return 0
max_height = 0
... |
6d6a76f36ee8db5768490522c4ddcb7d18c5487d | LucianaNascimento/CursoPythonGuanabara | /mundo1/29-RadarEletronico.py | 461 | 3.875 | 4 | ''' Escreva um programa que leia a velocidade de um carro
Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado
A multa vai custar R$7,00 por cada Km acima do limite.
'''
velocidade = int(input("Velocidade do carro: "))
if velocidade > 80:
print("Multado!!Você está acima do limite permitido!")... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.