blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9d7aa1fad8d37eef9ccdd622499438b914cebad4 | Mauro-CVO/Python_Programs | /Python_Logic/Segundo_desafio.py | 901 | 4.15625 | 4 | #Creado por MAU
def run():
print("""Hola, ¿quieren saber quien es mayor?""")
num = int(input("Primero necesito saber cuantos son: "))
print("Ahora necesito saber sus nombres y edades...")
#Creamos tuplas vacías para despues usarlas
names = []
ages = []
if num == 1:
print("Error: #40... |
fea720705c7c6a21628ef8efdcf2a176a62478fc | Mauro-CVO/Python_Programs | /Python_POO/aproximacion.py | 441 | 3.953125 | 4 | def aprox():
num = int(input("Escoge un número entero: "))
epsilon = 0.01
paso = epsilon ** 2
ans = 0.0
while abs(ans ** 2 - num) >= epsilon and ans <= num:
print(abs(ans ** 2 - num), ans)
ans += paso
if abs(ans ** 2 - num) >= epsilon:
print(f"No se encontro la raíz cua... |
a6cc83c75fec1f97ea47f5a470ecf53b2bb3d53a | sewei9/Python-Blackjack | /game.py | 6,957 | 4.03125 | 4 |
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven',
'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10,
... |
dc22abc45a7141d0768edeabc56be26daecdf279 | dignakr/sample_digna | /python-IDLE/sum_avg.py | 364 | 3.90625 | 4 | def summ(list1):
s=float(sum(list1))
return s
def avg(list1):
av=summ(list1)/len(list1)
return av
if __name__ == "__main__":
x=raw_input("enter the list elements : ")
list1 =map(int ,x.split(","))
print"the list is : ",list1
print"the sum is : ",summ(lis... |
a5be7fd2dd6e34855430bb5beb16ce9f6e8cafe4 | dignakr/sample_digna | /python-IDLE/student.py | 1,842 | 3.8125 | 4 |
class Student:
def __init__(self, rollno, name, dob, age, mark):
self.rollno=rollno
self.name=name
self.dob=dob
self.age=age
self.mark=mark
def displayStudent(self):
print "Roll No : ",self.rollno
print "Name : ", self.name
print "D... |
5d2dd022fba45dd0e95b4f12069dfcb01118b99f | resharj/MyCaptain-Python | /area.py | 134 | 4.15625 | 4 | import math
r = float(input('Input the radius of a circle: '))
area = 3.14 * r * r
print(" The area Of the Circle = %.10f" %area)
|
3a374f01ba2dccb44fe5f92d8232b36257d9f5f8 | mehringer/codeforces | /cf250d2a.py | 176 | 3.546875 | 4 | a = raw_input()
b = raw_input()
c = raw_input()
d = raw_input()
arr = sorted([a,b,c,d])
if len(arr[0])* 2 < len(arr[1]):
if len(arr[2]) > len(arr[3])*2:
|
d6693cd5269bfe6f8765830f1ff5e4ba2fc21a74 | JackLogan1/SimpleApps | /timeapp.py | 133 | 3.671875 | 4 | print("1.Timer")
print("2.Stopwatch")
choice = input("Choice:")
if choice == '1':
import timer
elif choice == '2':
import stopwatch |
deddb7cb17b2b2070f9902903fb8459e1285f409 | vinayakushakola/Python-Basic-Programs | /Armstrong_num.py | 213 | 3.953125 | 4 | n = input("Enter 3 digits number: ")
sum = 0
for i in n:
m = int(i)**3
sum += m
if sum == int(n):
print("{} is an Armstrong number".format(n))
else:
print("{} is not an Armstrong number".format(n)) |
00fdebbc8dd6a4c56d73a430aba840aa52db513a | georgggg/python-bootcamp | /Day-004/exercise-4-rock-paper-scissors.py | 1,514 | 4.21875 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
_... |
3ea2ea8bf04c1ebef4821e2497fe06aa9780f05a | georgggg/python-bootcamp | /Day-003/exercise-2-BMI-2.0.py | 2,692 | 4.65625 | 5 | # BMI Calculator 2.0
# Instructions
# Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height.
# It should tell them the interpretation of their BMI based on the BMI value.
# Under 18.5 they are underweight
# Over 18.5 but below 25 they have a normal weight
# Over 25 but ... |
f5582fcca20cb94da8e4bf7a1f61432211d469af | Deofex/GETStateChange | /statechanges/graphinfo_shared.py | 598 | 3.5 | 4 | # create a graph class where to store periods and a single value
class GraphInfo():
def __init__(self,periodname,value):
self.periodname = periodname
self.value = value
# Create a graph which can store periods and store two values
class DoubleGraphInfo(GraphInfo):
def __init__(self, periodname,... |
ac3c797db8256a01ab004e48c9fc9c1533a19e3d | DDusa/a3_files | /app.py | 54,374 | 3.546875 | 4 | """
Simple 2d world where the player can interact with the items in the world.
"""
__author__ = "Haoran Jin"
__date__ = ""
__version__ = "1.1.0"
__copyright__ = "The University of Queensland, 2019"
import math
import tkinter as tk
from typing import Tuple, List
from tkinter import filedialog
from tkinter import mes... |
7480103519a8a8f72a22a681b6eeb9e4ea2e1af8 | OhJino/calculator | /Calculator.py | 7,670 | 3.578125 | 4 | from tkinter import *
import operator
def calculate(x, y, operator, get_operator = {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.__truediv__,
'%' : operator.mod,
'^' : operator.xor,
... |
bee9583d9c32374497fc491e30fd488a3598c9cc | vgiabao/a-byte-of-python | /While.py | 595 | 4.15625 | 4 | number = 23
running = True
while running:
guess = int(input('Enter an int: '))
# congratulation and stop the loop whien the number is guessed
if guess == number:
print('congratulation!')
# it causes stop
running = False
# print a hint when the guessed is smaller than the number
... |
29e5d1b19f4092490540ad56702cc1f4be7e9df4 | arunsangar/Sorting-Algorithms | /SortingAlgorithms/insertion_sort.py | 838 | 4.03125 | 4 | def insertion_sort(list, type='iterative'):
if(type == 'iterative'):
insertion_sort_i(list)
else:
insertion_sort_r(list)
def insertion_sort_i(list):
for i in range(len(list)):
current = i
previous = i - 1
while(previous >= 0 and list[current] < list[previous]):
... |
17e8c4291695817b465b831de847c0c89016e40a | HappyGradu/Machine-Learning-Cookbooks | /src/neural_networks/perceptron/multi_layer_perceptron.py | 10,405 | 3.71875 | 4 | """
This python script describes that how to use TensorFlow to implement the Multi-Layer Perceptron (MLP) model for
Multi-class Classification.
Author:
Hailiang Zhao
"""
import tensorflow as tf
import os
from tensorflow.examples.tutorials.mnist import input_data
# ['define' flags for model records]
tf.flags.DEFI... |
53e028cfcd49c0f1b6a797fe4a264f84c6210804 | shubhamkhunt04/Cryptograph-and-network-security | /cy.py | 264 | 4.28125 | 4 | # Conver string into cipher text
str1 = input("Enter a string :\n")
key = int(input("Enter the size of key :\n"))
for i in str1:
if(i.islower()):
print(chr((ord(i)+key-97)%26+97),end="")
else:
print(chr((ord(i)+key-65)%26+65),end="") |
b16ef6d65d33e27d0c57dd3b327d24631f3209aa | Cznielsen/cs | /S5_MachineLearning/dML/handin1/logistic_regression.py | 7,372 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import scipy
from sklearn.metrics import confusion_matrix
from h1_util import numerical_grad_check
def logistic(z):
"""
Computes the logistic function 1/(1+e^{-x}) to each entry in input vector z.
np.exp may come in handy
Args:
z: numpy a... |
ae69575b3cf02bd5adbd3934ffa9ee5c6bf35225 | ThatGuy247/Python_EdX_GoToClass_Solutions | /Quiz-1/Part3.py | 102 | 4 | 4 | age = int(input('Please enter your age: '))
days = age*365
print('You are ' + str(days) +' days old') |
f554f8c100ae8d5ccc476233d5a87e946d6ad958 | ThatGuy247/Python_EdX_GoToClass_Solutions | /Final Exam/Part5 - MY_2D_LIST.py | 497 | 3.890625 | 4 | def MY_2D_LIST(n):
my_list = []
for i in range (1,n+1):
if i == 1:
sublist = [1]
my_list.append (sublist)
elif i == 2:
sublist = [1, 1]
my_list.append (sublist)
else:
sublist = [1]
for j in range(1,i-1):
... |
f4f5bb30be87432e97f98859b728c88b7aaec92a | ThatGuy247/Python_EdX_GoToClass_Solutions | /Homework-1/Part2.py | 394 | 3.546875 | 4 | def remain(principal, annual_interest_rate, duration , number_of_payments):
n = duration*12
if annual_interest_rate != 0:
r = (annual_interest_rate/100)/12
remaining = (principal * (((1+r)**n) - ((1+r)**number_of_payments))) / (((1+r)**n)-1)
return remaining
else:
remaining... |
1490582c576bb76ec7ced5cc80445d0e5867831b | ThatGuy247/Python_EdX_GoToClass_Solutions | /Quiz-2/Part3.py | 127 | 3.859375 | 4 | age = int(input('enter age: '))
if age <= 0:
print('UNBORN')
elif age<= 150:
print('ALIVE')
else:
print('VAMPIRE') |
8c8a2943f3c14ef9ca32bec1983aaeda275fff0f | ThatGuy247/Python_EdX_GoToClass_Solutions | /Quiz-1/Part4.py | 74 | 3.8125 | 4 | x = int(input('Please enter number: '))
y = (x**2) - (12*x) + 11
print(y) |
7e63aec405405ad52f3c44248addc7decced8557 | AlyHuang/python | /first.py | 496 | 3.625 | 4 | a=8
b=0
print(a,type(a))
if a>(-1):
a=a+1
else:
b=4
print (a,b)
sroce={"语文":87,"数学":100,"英语":90,"体育":30}
print (sroce)
print (sroce.keys())
print (sroce.values())
del sroce["语文"]
print (sroce)
f=open("1.txt","r")
f2=open("2.txt","r+")
for line in open("1.txt"):
#line =f.readline()
f2.wr... |
25ee8652b246edfe6fb8e3f58d1f96eca6bca213 | LilZsa/Mision_02 | /velocidad.py | 1,036 | 4 | 4 | # Autor: Roberto Emmanuel González Muñoz A01376803
# La velocidad de un auto puede calcularse con la fórmula v = d/t.
# Elabora un algoritmo y escribe un programa que pregunte al usuario
# la velocidad a la que viaja un auto (km/h, número entero) y calcule el tiempo.
def imprimir(d1,d2,t):
print("___________... |
0c2b399489fd46312dc82f92cf78a2f8f0676c56 | appomsk/docp | /lesson-01-pocker/src2/poker.py | 2,274 | 3.71875 | 4 | def poker(hands):
"Return a list of winning hands: poker([hand,...]) => [hand,...]"
return allmax(hands, key=hand_rank)
def allmax(iterable, key=None):
"Return a list of all items equal to the max of the iterable."
result, maxval = [], None
key = key or (lambda x: x)
for x in iterable:
... |
2c2a7fa290bea8a7e4713c2b9189dd8d561d8c10 | MariaPantone/Python_projects | /08_indice_di_massa.py | 582 | 4.03125 | 4 | print("Questo programma calcola il tuo indice di massa")
weight = float ( input("Digita il tuo peso in Kg (ex. 70.5): ") )
height = float ( input("Digita la tua altezza in metri (ex. 1.70): "))
bmi = weight / (height ** 2)
print("Il tuo BMI è :",round(bmi,2))
if(bmi <= 18.5):
classification = "sottop... |
4c69dc8a4a0aa9b0e6fe3f421d2fcc51f87aecbf | rjipandey/Task_Kunal | /printtowords.py | 1,295 | 4.15625 | 4 | # given the time in numeral and convert it into words
# print time in words.
def printWords(hours, minutes):
nums = ["zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen... |
04750264a11519a001ec51f961f1658f6d8ee470 | salamer/My_OJ_practice | /python/power_of_three.py | 347 | 3.734375 | 4 | class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n==3:
return True
res=0
while(n>0):
res=n%10+res
n=n/10
print res
if(res==9):
return True
else... |
a34da77ab1f21ee5eebd5c4a69beecd062265370 | ian011403/Desafio-Data-Machina | /Veículo Ideal/classes_vec_ide.py | 2,402 | 3.53125 | 4 | # Nesse modulo defino as classes Veiculo, Iten, Plataforma, e Entrega usadas na resolução
# do desafio dos veiculos ideais. O objetivo dessas classes não é implementar necessariamente
# um algoritmo baseado em programação orientada a objeto formal, mas apenas organizar os principais
# elementos do problema
class Ve... |
d355dd77c78ab8f9190ab7dda96f629df0079cb8 | JuliaDer/Fundamentals-of-Python-Programming | /Week 4/Периметр треугольника(Triangle perimeter).py | 394 | 4.0625 | 4 | def perimeter(x1, y1, x2, y2, x3, y3):
dist1 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** (1 / 2)
dist2 = ((x3 - x1) ** 2 + (y3 - y1) ** 2) ** (1 / 2)
dist3 = ((x2 - x3) ** 2 + (y2 - y3) ** 2) ** (1 / 2)
return dist1 + dist2 + dist3
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 ... |
ec7e374375de26cf7a9bc90f8411efad3b6d5643 | hensonm1133/cti110 | /P2T1_SalesPrediction_HensonMonica.py | 371 | 3.625 | 4 | #CTI 120-0902
#P2T1 - Sales Prediction
#Monica Henson
#18 February 2018
#
#Get the projected total sales.
total_sales = float (input ('Enter the projected sales: '))
#Calculate the profit as 23 percent of total sales.
profit = total_sales * 0.23
#Display the profit.
print ('The profit is $', format(profit... |
10b4f6cc6a83081eb08750dc7b22f71f3b7fb431 | Almanova/WebDevelopment-Spring2020 | /week8/CodingBat/List-1/max_end3.py | 131 | 3.625 | 4 | def max_end3(nums):
temp = nums[0]
if nums[0] < nums[len(nums) - 1]:
temp = nums[len(nums) - 1]
return [temp, temp, temp] |
0d1312a123d65196c2566fa9e784c5177f398df7 | Almanova/WebDevelopment-Spring2020 | /week8/informatics/3/2/D.py | 100 | 3.71875 | 4 | n = int(input())
i = 1
while (i < n):
i *= 2
if (i == n):
print("YES")
else:
print("NO") |
47a36c2fade9e5aafca7e6e08925aa87160d2621 | ariv0004/test | /test.py | 1,948 | 3.96875 | 4 | import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
def plot_data(x, y):
fig = plt.figure()
plt.scatter(x, y)
plt.xlabel("Profit in $10,000")
plt.ylabel("Population of City in 10,000s")
plt.show()
print(plot_data(X, Y))
m = Y.size
X = np.stack([np.ones(m), X], axis=1)
prin... |
f0f8cd555519a8711f48daaf55aad14ea421f3b8 | AlexMabry/aoc19 | /day1/part1.py | 512 | 4 | 4 | import math
# Open the file
input_file = open('input.txt', 'r')
# Read every line of the file into a list of strings
lines_in_file = input_file.readlines()
# Turn that list of strings into a list of modules
modules = [int(line) for line in lines_in_file]
def calculate_fuel(module):
return math.floor(module/3)-... |
8053b0ca6c6e3ac56514c89d18c91fdc9f667c1d | cruzemcfarlane/COMP1127_lab5 | /lab05_code.py | 426 | 3.703125 | 4 |
class Polygon:
def __init__(self,nbrsides):
self.nbr_sides = nbrsides
def whoamI(self):
if self.nbr_sides == 3:
return "Triangle"
elif self.nbr_sides == 4:
return "Rectangle"
else: return "Polygon"
def howmanysides(self):
return self.nbr_si... |
db840fb3e01ad0cacc4af0dd3c31d7d87f36d5de | kentka11/hangman | /part2/object_apple.py | 858 | 3.859375 | 4 | import math
class Apple:
def __init__(self, w, s, c, sg):
self.weight = w
self.size = s
self.color = c
self.suger = sg
print("Created!!")
my_apple = Apple(10, 1999, "yellow", 1029)
print(my_apple.weight)
print(my_apple.size)
print(my_apple.color)
print(my_apple.suger)
class Circle:
def __ini... |
232acabb33d4d2b386f8827aaa6cfa1df802b680 | kentka11/hangman | /part1/loop.py | 1,031 | 3.796875 | 4 | # coding: UTF-8
#7-1
lists = ["Waking Dead", "Antradu", "Vampire Diaries", "The Soprano"]
for str1 in lists:
print(str1)
#7-2
#for i in range(25, 51):
# print(i)
#7-3
i = 0
for str1 in lists:
print("index :" + str(i) + " " + str1)
i += 1
#7-4
qs = ["How old is Manami?",
"How much is the glass?"... |
70a474c421db4f785834dc01e6173115ae3c378b | cwdgit/aliyun-backup | /wordpress/haha1/输入输出/文件/wenjian.py | 280 | 3.703125 | 4 | #!/usr/bin/python
#filename test
word='''\
This is a test word
I don't know what i saying
and i don't know everything.
'''
f=file('test.txt','w')
f.write(word)
f.close()
f=file('test.txt')
while True:
line=f.readline()
if len(line) == 0:
break
print line,
f.close()
|
e1eca31e177b17fbdd6e79cac3362c169e395898 | cwdgit/aliyun-backup | /haha1/数据结构/dict/seq.py | 345 | 3.78125 | 4 | #!/usr/bin/python
shoplist=['apple','mango','carrot','banana']
time=len(shoplist)
for i in range(1,time):
print 'Item',i,'is',shoplist[i]
print shoplist[i:i+2]
name= 'swaroop'
print 'characters 1 to 3 is',name[1:3]
print 'characters 2 to end is',name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters s... |
37761787d063ee5f0abab6e42d7dfdb096be9366 | cwdgit/aliyun-backup | /wordpress/haha1/输入输出/文件/using_file2.py | 289 | 3.625 | 4 | #!/usr/bin/python
#filename:testfile
word='''I am a good man,but i am not a good man \
you are a bad man,but you are a bad man.'''
f=file('word.txt','w')
f.write(word)
f.close()
f=file('word.txt')
while True:
line=f.readline()
if len(line) == 0:
break
print line,
f.close()
|
d1b385cdbecf9600639fa458d883e70aeeb5dcc5 | Eddonofuture/python_retake | /exception/ej1.py | 309 | 3.828125 | 4 | class EvenOnly(list):
def append(self, integer):
if not isinstance(integer, int):
raise TypeError("only integers")
if integer % 2:
raise ValueError("Only even numbers")
super().append(integer)
e = EvenOnly()
e.append(2)
#e.append(1)
#e.append("a string")
|
6f389e47a420b8f0dfefcc93dca7439f609ce826 | Eddonofuture/python_retake | /herencia2/ej1.py | 1,059 | 3.890625 | 4 | class ContactList(list):
def search(self, name):
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacs = ContactList() # Se comparte en todas las instancias, ... |
e0857697b3d3391b22ca1867eadf796d442da577 | escorciav/linux-utils | /hacks/fix_name.py | 1,517 | 3.75 | 4 | import os
import shutil
import sys
def fullpath_names(root_dir, file_list):
"""Create a list of fullpath file-name
"""
fullpath_list = []
for i in file_list:
fullpath_list.append(os.path.join(root_dir, i))
return fullpath_list
def get_files_and_subdirs(root_dir):
"""Return a tuple with... |
94b0d36e328a255e1f8dc8b20f90147aa168aa5c | idsc-frazzoli/Control-Systems-I-2018 | /python_tutorials/exercises/scripts/ex3.py | 1,452 | 4.375 | 4 | # Write a binary function which searches an item in a sorted list.
# The function should return the index of element to be searched in the list.
# Binary search works looking at the middle element of the list and takes the left or right half
# if the item is less or greater then the middle element. The procedure is th... |
c0be15b9dd2d1aeff59ad8564461781014bf35b0 | Nada8773/Python-Script | /python crash course/Assigment4/Question1.py | 1,278 | 4.46875 | 4 |
#The format_address function separates out parts of the address string into new strings: house_number and #street_name, and returns: "house number X on street named Y". The format of the input string is: numeric #house number, followed by the street name which may contain numbers, but never by themselves, and could #b... |
6edf2a23a70fb00c1cf7a3d04009a79e19b11328 | SiddharthaPramanik/Py4E | /Assignment_15_02/Assignment_15_02.py | 1,375 | 3.75 | 4 | # This application will read the mailbox data (mbox.txt)
# and count the number of email messages per organization
# (i.e. domain name of the email address) using a database
import sqlite3
# Set connection to DB
connection = sqlite3.connect('Email_DB.sqlite')
cursor = connection.cursor()
# Create fresh tab... |
5e2a31236572ebe1be058082b88bb0e0c7fd30e7 | JDWree/Course_projects | /OReilly_100wordsScenario/100words.py | 3,105 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 16:52:05 2020
@author: Jonatan
O'Reilly course "Python Fundamentals": Top 100 words scenario
"""
import re
def user_input():
"""Asks the user for the path to the textfile and checks if it exists."""
textfile = input("Enter the path to the textfile: ")
im... |
7d9afb11c45b608968d5cf4d563d2ce4bda0bbb5 | YJoe/SpaceShips | /Desktop/Python/space_scroll/Settings.py | 4,505 | 3.625 | 4 | class Settings:
def __init__(self):
# the user can alter new_settings through the settings menu
# writing to the settings file will only occur if the user
# closes the settings function
# create settings options
self.enemy_chance = [300, 250, 200, 150, 100, 50, 10]
s... |
53c9e01e55a8dbda869ee7a9c4702f44ab945eba | arqaDev/Python | /Python/algorithms/bubble_sort/bubble_sort.py | 260 | 3.875 | 4 |
def bubble_sort(mylist): #takes a list of numbers
item = len(mylist)-1
for i in range(0,item):
for y in range(0,item):
if mylist[y]>mylist[y+1]:
mylist[y],mylist[y+1]=mylist[y+1],mylist[y]
return mylist
|
10ff3ff2776b3e19af6c2db2782077bdf16efb36 | NotQuiteHeroes/HackerRank | /Python/Itertools/Itertools_Combinations_with_replacement.py | 582 | 3.921875 | 4 | '''
Task
You are given a string s.
Your task is to print all possible size k replacement combinations of the string in lexicographic sorted order.
Input Format
A single line containing the string s and integer value k separated by a space.
Output Format
Print the combinations with their replacements of string s on sep... |
afbcc924c19a729f0d184309a8f83c0d79231e8f | NotQuiteHeroes/HackerRank | /Python/Itertools/Itertools_Product.py | 677 | 4 | 4 | '''
Task
You are given a two lists A and B. Your task is to compute their cartesian product AXB.
Note: and are sorted lists, and the cartesian product's tuples should be output in sorted order.
Input Format
The first line contains the space separated elements of list A.
The second line contains the space separated e... |
abf0476391372448094862ae4b04b11d50ceb70a | NotQuiteHeroes/HackerRank | /Python/Strings/Merge_the_Tools.py | 1,410 | 3.96875 | 4 | '''
Consider the following:
A string, s, of length n where s = c0c1...cn-1.
An integer, k, where k is a factor of n.
We can split s into n/k subsegments where each subsegment, ti, consists of a contiguous block of k characters in s. Then, use each ti to create string ui such that:
The characters in ui are a subsequence... |
105d6aabf99eb605f553eb26d789f8d532a6a62c | NotQuiteHeroes/HackerRank | /Python/Strings/Text_Wrap.py | 540 | 4.03125 | 4 | '''
Task
You are given a string and width .
Your task is to wrap the string into a paragraph of width .
Input Format
The first line contains a string, s.
The second line contains the width, w.
https://www.hackerrank.com/challenges/text-wrap
'''
import textwrap
if __name__ == '__main__':
string, max_width = raw_... |
24d71c818a3b74e5944e9d52773ca36576fb1e17 | kodmm/Python | /sample14.py | 87 | 3.703125 | 4 | data = [1, 2, 3, 4, 5]
print(data)
ndata = [n*2 for n in data if n != 3]
print(ndata)
|
c2c475f91328c250845bf26cfeb9ae643f934dca | kodmm/Python | /sample11.py | 673 | 3.65625 | 4 | a = 0
def funcB():
b = 1
print("funcBのなかでは、変数aと変数bが使えます")
print("変数aの値は", a, "です。")
print("変数bの値は", b, "です。")
# print("変数cの値は", c, "です。")
def funcC():
c = 2
print("funcCのなかでは、変数aと変数cが使えます。")
print("変数aの値は", a, "です。")
print("変数cの値は", c, "です。")
# print("変数bの値は", b, "です。")
print... |
4fb5ddad4bee34929a02730f257d8b8de7ad94c0 | bensontjohn/pands-problem-set | /secondstring.py | 622 | 4 | 4 | # Benson Thomas John, 2019
# Program that takes a user input string and outputs every second word.
# Prompt user to enter a sentence
user_input = input("Please enter a sentence: ")
# Referenced: # https://stackoverflow.com/a/47085688
# Convert the string to array using split method
arr_input = user_input.split(' ')... |
437891c7895b7d8f0f02de42ae2a4940336fa1ae | RangelCortes45/2-Bachillerato | /bucleinsignialmao2.py | 767 | 3.796875 | 4 | def bucle_insignialmao2():
print "SUMA PARES O IMPARES"
print "Hasta que numero deseas sumar?"
nfinal=input("numero = ")
#Definimos una variable para contar los pares (ACUMULADORA)
suma_pares=0 #inicializamos la variable a cero
#Definimos una variable para contar los impares
suma_impa... |
70b0d3be8e96e102cb5b6c05c5949a4980e06099 | diyaagrawal2041/Python-games | /Number guessing game.py | 835 | 4.15625 | 4 | import random
print("What's your name?")
name=input()
print("Hello",name,", Welcome to the number guessing game!")
print("Here, I will think of a number between 1 to 20 and you have to guessed it correctly in less than 8 guesses.")
number=random.randint(1,20)
i=8
while(i!=0):
print("Take a guess: ")
guess=int(i... |
47bbcacd7a7cf849ce7df4d52a248c09fa608748 | scott-strickland/python3 | /snippets/enumerate-headers.py | 789 | 4.1875 | 4 | #!/usr/bin/env python3
import csv, sys
"""
Quick script in Python3 to enumerate the header row and provide the index
position of each header.
"""
def csv_headers(filename):
"""Enumerate headers of a CSV file."""
try:
with open(filename) as file_object:
reader = csv.reader(file_... |
29a45636cd3954755e1b72133034c98863a38faa | tjlqq/pythoncookbook | /1shujujiegouhesuanfa/yield/yield.py | 213 | 4.03125 | 4 | #!/usr/bin/env python
#coding:utf8
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
nested = [[1,2],[3,4],[5,6]]
for num in flatten(nested):
print num,
|
160061522e91f4b6f6e97b7d34c5e64ac7685a40 | tjlqq/pythoncookbook | /zifuchuanhewenben/re/pythonre.py | 150 | 3.8125 | 4 | #!/usr/bin/env python
#coding:UTF-8
import re
pattern = re.compile(r'hello')
match = pattern.match('hello world!')
if match:
print match.group()
|
e28e86c5ba0004536ea68eba9ba52aab4332c029 | DaOneTwo/Sudoku | /Objects/board.py | 3,523 | 3.84375 | 4 |
class SudokuBoard(object):
"""A Sudoku Board object"""
_col_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
_row_nums = range(1, 10)
_valid_set = {i for i in range(1, 10)}
def __init__(self, data_set=None):
self.rows = None
self.columns = None
self.blocks = None
... |
d577b4d780bb286cd6a945d9451db608bfa4f678 | Gfuqiang/pandas_study | /08_filter/filter.py | 394 | 3.625 | 4 | import pandas as pd
"""
按条件进行过滤
"""
def filter_age(a):
return 20 <= a < 30
df = pd.read_excel('./Students.xlsx', index_col='ID')
s_df = df.loc[df['Age'].apply(lambda a: 20 <= a < 30)].loc[df.Score.apply(lambda s: 90 < s)] # loc定位函数 location的缩写
# df['Age'], df.Age 语法相同都是在获取Series
# apply 在Series上执行函数
print(s_... |
05490c0153317b16cc9fd86678dc45008612213b | Muskanbansal18/hacktoberfest2021-4 | /Python/PhoneNo.py | 892 | 4.09375 | 4 | import random
def generate():
number = ''
for i in range(0,10):
number += str(random.randint(0,9))
return number
def menu():
ch = 'y'
while ch == 'y':
print('\n1)Take phone number')
print('2)delete phone number')
choice = int(input('Enter your choice: '))
if choice == 1:
... |
a4cab39f1fc31674480ef456aba4b4bc080f8fbf | ethframe/aoc_2017 | /day05.py | 454 | 3.6875 | 4 | from adventlib import *
DAY = 5
def main():
inp = store_input(DAY)
if inp is None:
return
lines = list(split_lines(inp))
maze = list(map(int, lines))
pos = 0
steps = 0
while pos != len(maze):
npos = pos + maze[pos]
if maze[pos] >= 3:
maze[pos] -= 1
... |
5bec10abeaf25708567357f9b8b3e388a7dab6db | reddevil1996/Python-DS | /MergeSort.py | 724 | 3.859375 | 4 | def MrgSort(list):
if len(list) > 1:
mid = len(list) // 2
l = list[:mid]
r = list[mid:]
MrgSort(l)
MrgSort(r)
i = j = k = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
list[k] = l[i]
i = i + 1
... |
74f394a78bf9f933042b7f980561cf92f9896568 | sunilmummadi/Greedy-1 | /jumpGame2.py | 1,438 | 3.703125 | 4 | # Leetcode 45. Jump Game II
# Time Complexity : O(n) where n is the size of the array
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: In the current window move i through every index to find the best point for next jump i.e.
# ... |
8f61e997d5112e2f878af6bd3ae12e161890a33e | klauskpm/alura-python | /oo_avancado/model.py | 1,942 | 3.953125 | 4 | from abc import ABC, abstractmethod
class Video(ABC):
def __init__(self, title, year):
self._title = title.title()
self.year = year
self._likes = 0
@abstractmethod
def __str__(self):
return f'Título {self.title} - Ano {self.year} | likes {self.likes}'
@property
de... |
91bf3edd9ed12258e0f4fb30d6a000716fff14ce | klauskpm/alura-python | /testes_python_projeto_inicial/src/leilao/dominio.py | 1,833 | 3.875 | 4 | from testes_python_projeto_inicial.src.leilao.excecoes import LanceInvalido
class Usuario:
def __init__(self, nome, dinheiro=0):
self.__nome = nome
self.__carteira = dinheiro
@property
def nome(self):
return self.__nome
@property
def carteira(self):
return self._... |
7ba5ab0f07d907fd578c7cd8a23c5ffb4efbc1f1 | klauskpm/alura-python | /jogos/forca.py | 5,267 | 3.578125 | 4 | import time
from random import randint
from sys import argv
from helpers import map_positions, normalize, clear
PLACEHOLDER_LETTER = '_'
DEBUG_MODE = 'debug' in argv[1:]
def start_game():
secret_word = get_word()
print_game_start_message()
init_rounds(secret_word)
def get_word():
with open('words.... |
c1097eedb8f0a9431116ed58ba88665ff2c8cbd2 | klauskpm/alura-python | /jogos/adivinhacao_experimentos/adivinhacao_for.py | 1,127 | 3.9375 | 4 | print('*********************************')
print("Bem vindo ao jogo de Adivinhação!")
print('*********************************')
def guess_number():
secret_number = 42
retries = 3
try:
for game_round in range(1, retries + 1):
print('Rodada: {} de {}'.format(game_round, retries))
... |
9278865be96d167f64d243ec9e0294244caa85e4 | yesha9918/comp110-21f-workspace | /exercises/ex05/utils.py | 1,087 | 4.09375 | 4 | """List utility functions part 2."""
__author__ = "730402890"
def only_evens(x: list[int]) -> list[int]:
"""Returning a list of ints with only even number inputs."""
i: int = 0
evens: list[int] = list()
while i < len(x):
if x[i] % 2 == 0:
evens.append(x[i])
i += 1
retu... |
1886ed6280782a3b0e2b24ffc9a2710bb65f351e | Komal97/Python-Exercises | /Regular Expression/String validate.py | 410 | 3.765625 | 4 | import re
# Phone number validation
phn = "412-555-1212"
if re.search("\w{3}-\w{3}-\w{4}", phn):
print("It is a phone number")
# Full name validation
name = "Komal Bansal"
if re.search("\w{2,20}\s\w{2,20}", name):
print("Full name is valid")
# Email validation
email = "sk@aol.com md@.com @seo.co... |
0e5512404f505cd0858fa211e6164020479edd6f | Komal97/Python-Exercises | /Multithreading/calc_sq_and_cube.py | 533 | 3.5 | 4 | import threading
import time
def calculate_square(arr):
print('calculate square...')
for num in arr:
time.sleep(0.2)
print(num*num)
def calculate_cube(arr):
print('calculate cube...')
for num in arr:
time.sleep(0.2)
print(num*num*num)
arr = [2, 3, 4, 5]
t = time... |
1394e2dbc70cea7f999508e03a53f7f9b1a43ffb | karpagaraj21/interview_solution2 | /Program_1_print_FizzBuzz.py | 553 | 4.03125 | 4 | #Print n Number
#Print Multiple of Three means Fizz
#Print Multiple of Five means Buzz
#Print Multiple of Both means FizzBuzz
n=int(input("Please enter the number:")) #n=15
for i in range (1,n+1): #i == 1 to 16
if(i%5==0)&(i%3==0): #if(15%5==0) and (15%3==0)
print("FizzBuzz") #print==>"FizzBuzz"
... |
b97e465a3699162774f17edc372c60940d71bf25 | ChangMM/python3_practice | /threading/ThreadingCond.py | 1,396 | 3.90625 | 4 | import threading
import time
class PeriodicTimer:
def __init__(self, interval):
self._interval = interval
self._flag = 0
self._cv = threading.Condition()
def start(self):
t = threading.Thread(target=self.run)
t.daemon = True
t.start()
def run(self): # Ru... |
c0a23b7374feabd331f3f6f48c16e68ccbd03ccf | emgrebe/python-tutorial-playlist | /lessons/string_format.py | 243 | 3.90625 | 4 | num1=3.1425467389
num2=10.2903948
#PREVIOUS
#print('num 1 is',num1,'and num 2 is',num2)
#FORMAT METHOD
# print('num 1 is {0:.3f} and num 2 is {1:.3f}'.format(num1,num2))
#USING F-STRINGS
print(f'num 1 is {num1:.4f} and num 2 is {num2:.4f}') |
3ea33d9ae78bd5cff653c7a897d15d0066cbefc5 | pinjutien/LeetCode-study | /aux_29_count_sort.py | 670 | 4.0625 | 4 | '''
Given a long length of input array, every element in the array are integers and between 1 and 10.
'''
def count_sort(input_array, k = 10):
count_array = [0] * (k+1)
# populuate count_array:
# i-th element: it means the number of i in input array
for i in input_array:
print(i)
cou... |
0b2625558dc3b1f61f604a7ed0ff267416ad3269 | pinjutien/LeetCode-study | /q3.py | 808 | 3.90625 | 4 | # Given a string, find the length of the longest substring without repeating characters.
#
# Examples:
#
# Given "abcabcbb", the answer is "abc", which the length is 3.
#
# Given "bbbbb", the answer is "b", with the length of 1.
#
# Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer mus... |
c370b5dfa14d4951f874c0e4cfbab02ec4144f9c | maloyan/CMCPython | /18.py | 388 | 3.5 | 4 | a = input()
b = input()
ans = 0
j = 0
test = 0
if len(a) >= len(b):
for i in range(len(a)):
if a[i] == b[j] or b[j] == '@':
ans += 1
j += 1
else:
ans = 0
j = 0
if ans == len(b):
test = 1
print(i - len(b) + 1)
... |
56c7270159837ef383559bb5784ac0c0894dfc4b | mahsamabbas/csvreader | /script.py | 907 | 3.609375 | 4 | #Import Modules
import itertools
from collections import OrderedDict
import csv
def getHeaders(csv_file):
"""
Read the first row and return values in a list
"""
try:
with open(csv_file, 'rt') as csvfile:
file_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
he... |
6c384ef774267c5b8deaf983c897f7d3d771a8ee | jbyers19/CryptoBot | /trade.py | 481 | 3.546875 | 4 | # Imports
from decimal import *
# Buy coins
def buy(capital, price):
print("\n%s of coins bought for %s\n" % (str(Decimal(capital) / Decimal(price)), str(price)))
return Decimal(capital) / Decimal(price)
# Sell coins
def sell(price, amount):
print("\n%s of coins sold for %s\nProfit: %s BTC\n" % (str(amo... |
fbedfd427cb140adeb267de8b8c2f6e0aa41d894 | androshchyk11/Colocvium-2-semester | /56.py | 1,110 | 3.90625 | 4 | '''
Якщо в одновимірному масиві є три поспіль однакових елемента, то
змінній r привласнити значення істина.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
n = int(input("Input quantity of array: ")) # Користувач вводить кількість чисел у масиві
array = [] # Ініціалізуємо масив
for i in range(n): # пр... |
bf9ece5f4fcd1e65e167f3e883b29b3366eb1fac | androshchyk11/Colocvium-2-semester | /17.py | 889 | 3.671875 | 4 | '''
Знайти суму елементів масиву дійсних чисел, що мають непарні номери.
Розмірність масиву - 20. Заповнення масиву здійснити випадковими числами від 100
до 200.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
import random
sum = 0 # Ініціалізуємо змінну сума
a = [random.uniform(100, 200) for i in range(... |
e07b4053ebcdbb17d5ae01c820eafc1a94895c3a | androshchyk11/Colocvium-2-semester | /45.py | 510 | 4.1875 | 4 | '''
Перетин даху має форму півкола з радіусом R м. Сформувати таблицю,
яка містить довжини опор, які встановлюються через кожні R / 5 м.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
import math
radius = int(input("radius: "))
delta = radius / 5
x = 0
i = 0
while x < 2 * radius - delta:
x += delta
... |
18e53b1aaf02acc5fb5f075d18e9120e3291696a | androshchyk11/Colocvium-2-semester | /52.py | 1,465 | 3.8125 | 4 | '''
Знайти найбільший елемент з елементів одновимірного масиву, що мають
парний номер. Визначити, чи є він єдиним.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
n = int(input("Input quantity of array: ")) # Користувач вводить кількість чисел у масиві
array = [] # Ініціалізуємо масив
for i in range(n)... |
cf69e462facca9e812870feaff34fb169f476f4d | androshchyk11/Colocvium-2-semester | /49.py | 1,274 | 3.640625 | 4 | '''
Задано дві таблиці. Одна містить найменування послуг, а інша - розцінки
за ці послуги. Видаліть з обох таблиць все, що передує послузі, ціна якої G гривень.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
a = ['Тату', 'Пірсинг', 'Доставка їжі', 'Буст аккаунта'] # Створюємо масив з назвами послуг
b = [... |
9d7e13486e625af6d3ef33a2e22c75764057b349 | androshchyk11/Colocvium-2-semester | /54.py | 996 | 3.734375 | 4 | '''
Введіть масив з 20 елементів і визначте, чи є в ньому елементи з
однаковими значеннями.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
array = [] # Ініціалізуємо масив
for i in range(20): # проходимо по циклу 20 разів
x = int(input()) # вводимо число з клавіатури
array.append(x) # додаємо ... |
f977ca0ae81c8c7cb9387266ebcc6bfa9f26c6fe | androshchyk11/Colocvium-2-semester | /34.py | 1,225 | 4 | 4 | '''
Дано два лінійних масиву однакової розмірності. Скласти третій масив з
добутку елементів перших двох масивів, що стоять на місцях з однаковим індексом.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''
n = int(input("Input quantity of arrays: ")) # Користувач вводить кількість чисел у масиві
a = []
b =... |
8919dc5ee48de612b7d7ea7fca5fb6ce560e4aba | jerry1210/HWs | /HW5/8.py | 264 | 3.953125 | 4 | '''
• Wirte a custom power function (using recursion)
def my_pow(number, x) -> return number ^ x
'''
def my_pow(number, x):
if x == 0:
return 1
elif x == 1:
return number
return number * my_pow(number, x-1)
print(my_pow(3,3)) |
43539e48a8c7d142905ba8dfbc223b26d5165658 | jerry1210/HWs | /HW5/9.py | 247 | 4.0625 | 4 | '''
• Write a multiplication function (using addition (recursion))
def my_mul(a, b) -> return a times b
'''
def my_mul(a, b):
if b == 0:
return 0
elif b == 1:
return a
return a + my_mul(a, b-1)
print(my_mul(5,4)) |
078f8aca322ce5ec4931225ddeae44a07900832d | untaken0username/flask_simple_lesson | /sort_n_search/searching.py | 1,727 | 3.71875 | 4 | from random import randint
from time import time
def create_rand_array(length):
array = []
for i in range(length):
array.append(randint(0, length))
return array
def linear_search(array, value):
for i in range(len(array)):
if array[i] == value:
return array[i]
def binary... |
7d959d6db13be2a54105d1b13e0ba3c6ef0a910b | summygupta/hackerrank_python | /Lists.py | 680 | 3.734375 | 4 | def command(lst, instruction):
if instruction[0] == 'insert':
lst.insert(int(instruction[1]), int(instruction[2]))
elif instruction[0] == 'print':
print(lst)
elif instruction[0] == 'remove':
lst.remove(int(instruction[1]))
elif instruction[0] == 'append':
lst.append(int(i... |
3e9096f00fc60610202a82bed66c1e925d5975a4 | summygupta/hackerrank_python | /quikSort.py | 701 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 23:40:12 2020
@author: Lenovo
"""
def swap(arr,i,j):
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
def pivot(arr,start,end):
pivot=arr[start]
swapidx=start
for i in range(start+1,len(arr)):
if pivot>arr[i]:
swapidx+=1
... |
e8f38ffa8745d2b3bdd9c765bc5eda91b2d00658 | kevinpau/Bellevue_University_DSC_550 | /DSC550_Paulovici_Exercise_7_3.py | 6,359 | 3.984375 | 4 | #%%[markdown]
# # Week 7:
# File: DSC550_Paulovici_Exercise_7_3.py (.ipynb)<br>
# Name: Kevin Paulovici<br>
# Date: 4/26/2020<br>
# Course: DSC 550 Data Mining (2205-1)<br>
# Assignment: 7.3 Exercise: Original Analysis Case Study Part 1 & 2
#%%[markdown]
# # Part 1
#%%[markdown]
# ## Assignment Tasks
#... |
8619b0483ce9d0d652fe028b9c74b471c6b3356a | alexeyhorkin/Numerical_Methods | /CM Laba Interpol/Main1.py | 6,117 | 3.640625 | 4 | import tkinter as tk
import Functions1 as Func
import matplotlib.pyplot as plt
import math as mt
import Table1 as Tbl
#########################################################
## Some functions
#########################################################
def CreateF(a):
def f(x):
if x >= -1 and x <= 0:
return x ** ... |
3ed2829246b5d3aa2e9148569111dc49a96acaa6 | varsha131/assign9 | /z4.py | 357 | 3.59375 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=[10,20,30,20,10,50,60,40,80,50,40]
dup_items=set()
uniq_items=[]
for x in a:
if x not in dup_items:
uniq_items.append(x)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.