blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b66ec415cb63a9b4e2adaed2608794af9778fecd | jeancochrane/recurse | /lstm/simple_example.py | 572 | 4.21875 | 4 | # Adapted from https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html
import torch
import torch.nn as nn
torch.manual_seed(1)
lstm = nn.LSTM(3, 3) # Input/output dimensions are 3
inputs = [torch.randn(1, 3) for _ in range(5)] # Random sequence
# Hidden state.
hidden = (torch.randn(1, 1, 3), torch.randn(1, 1, 3))
for i in inputs:
# Step through the sequence one element at a time.
out, hidden = lstm(i.view(1, 1, -1), hidden)
print('Input:')
print(inputs)
print()
print('Output:')
print(out)
print()
print('Hidden state:')
print(hidden)
| true |
76d9d94cd88322c5e834695182be4d068e4c1508 | ArielKollross/curso_em_video | /Python/Desafios-proprios/Interactive_calculator.py | 1,354 | 4.125 | 4 | # Interactive calculator, by Ariel Kollross
from math import sqrt
print('Escolha o numéro correspondente da operação que deseja realizar')
print('Soma entre dois numéros: 1')
print('Subtração ente dois numéros: 2')
print('Multiplicação ente dois numeros 3')
print('Divisão entre dois numéros: 4')
print('Potenciação entre dois numeros: 5')
print('Raiz quadrada de um numero: 6')
ope =int(input('Selecione o numéro da operação correspondente:'))
if ope == 6 :
var1 = float(input('entre com o primeiro numéro:'))
raiz = sqrt(var1)
print('A raiz quadrada de {} é {}'.format(var1,raiz))
else :
var1 = float(input('entre com o primeiro numéro:'))
var2 = float(input('entre com o segundo numéro:'))
if ope == 1 :
sum = var1 + var2
print('A soma entre {} e {}, vale: {}'.format(var1,var2,sum))
if ope == 2 :
sub = var1 - var2
print('A subtração entre {} e {}, vale: {}'.format(var1,var2,sub))
if ope == 3 :
mult = var1 * var2
print('A Multiplicação entre {} e {}, vale: {}'.format(var1,var2,mult))
if ope == 4 :
if var2 == 0 :
print('Divisão por zero é impossivel')
else :
div = var1/var2
print('A Divisão entre {} e {}, vale: {}'.format(var1,var2,div))
if ope == 5 :
pot = pow(var1,var2)
print('{} elevado a {}, vale: {}'.format(var1,var2,pot))
| false |
d4c3cdc4fa20107e4df1ad29a3547783f4c91e38 | mukhtarabdirahman/Password-Locker | /account.py | 1,433 | 4.125 | 4 | class Account:
"""
Class that generates new instances of users.
"""
account_list = [] #empty account list
def __init__(self,account_name,user_name,password,email):
self.account_name = account_name
self.user_name = user_name
self.password = password
self.email = email
def save_account(self):
'''
save_account method saves account objects into account_list
'''
Account.account_list.append(self)
def delete_account(self):
'''
delete_account method deletes a saved account from the account_list
'''
Account.account_list.remove(self)
@classmethod
def find_by_name(cls,name):
for account in cls.account_list:
if account.account_name == name:
return account
@classmethod
def account_exist(cls,name):
'''
Method that checks if a account exists from the account list.
Args:
name: Acc name to search if it exists
Returns :
Boolean: True or false depending if the account exists
'''
for account in cls.account_list:
if account.password == name:
return account
return False
@classmethod
def display_accounts(cls):
'''
method that returns the account list
'''
return cls.account_list | true |
ec0cf8164480ab4a009fd67520b9891d3d27f095 | waithope/leetcode-jianzhioffer | /剑指offer/09-用两个栈实现队列.py | 981 | 4.25 | 4 | # -*- coding:utf-8 -*-
'''
用两个栈实现一个队列
=========================
用两个栈实现一个队列。
队列的声明如下:请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部
插入节点和在队列头部删除节点的功能。
'''
class Queue(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def appendTail(self, val):
self.stack1.append(val)
def deleteHead(self):
if self.stack1 == self.stack2 == []:
return
elif self.stack2 == []:
while len(self.stack1) > 0:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
else:
return self.stack2.pop()
if __name__ == '__main__':
queue = Queue()
queue.appendTail(-1)
queue.appendTail(0)
queue.appendTail(3)
queue.appendTail(-9)
queue.appendTail(10)
print(queue.deleteHead())
print(queue.deleteHead())
| false |
fb81b7cb51b0df162ccc3593f450900ff169650c | mimiron8080/python-test | /args.py | 448 | 4.1875 | 4 | #!/usr/bin/python
# Filename: args.py
def powersum(power, *args):
'''Return the sum of each argument raised to specified power.'''
total = 0
for i in args:
total += pow(i, power)
print 'i is %s pow(i, power) = %s' % (i,pow(i, power))
return total
def ff(power, **args):
'''default '''
for key, value in args.items():
print 'key is %s : value is %s' % (key, value)
print powersum(2, 3, 4)
print powersum(2, 10)
ff(1,i=3,j=4,k=5)
| true |
450cd0039e3d988d6650022adf10c87cc7ef4bbd | VikiDinkova/HackBulgaria | /Programming0-1/week2/twin_prime.py | 1,510 | 4.34375 | 4 | from math import sqrt
number = int(input('Enter number: '))
sq_root_number = sqrt(number)
is_prime = True
if number == 1:
is_prime = False
start = 2
while start <= sq_root_number:
if number % start == 0:
is_prime = False
break
start += 1
if is_prime:
before_prime_number = number - 2
sq_root_other_number = sqrt(before_prime_number)
before_number_is_prime = True
if before_prime_number == 1:
before_number_is_prime = False
start_before_prime_number = 2
while start_before_prime_number <= sq_root_other_number:
if before_prime_number % start_before_prime_number == 0:
before_number_is_prime = False
start_before_prime_number += 1
if before_number_is_prime:
print('Twin primes with {0}:\n{1}, {0}'.format(number, before_prime_number))
after_prime_number = number + 2
sq_root_other_number = sqrt(after_prime_number)
after_number_is_prime = True
if after_prime_number == 1:
after_number_is_prime = False
start_after_prime_number = 2
while start_after_prime_number <= sq_root_other_number:
if after_prime_number % start_after_prime_number == 0:
after_number_is_prime = False
start_after_prime_number += 1
if after_number_is_prime:
print('{0}, {1}'.format(number, after_prime_number))
if before_number_is_prime == False and after_number_is_prime == False:
print("{0} is prime but:".format(number))
print("{0} in not".format(before_prime_number))
print("{0} in not".format(after_prime_number))
else:
print('{0} is not prime'.format(number))
| false |
bac1efe9752aa426e4a3822b84211fa8cfe7f361 | VikiDinkova/HackBulgaria | /Programming0-1/week4/program.py | 407 | 4.3125 | 4 | first_name = input('Enter first name: ')
second_name = input('Enter second name: ')
third_name = input('Enter third name: ')
birth_year = int(input('Enter birth year: '))
dictionary = {}
dictionary['first_name'] = first_name
dictionary['second_name'] = second_name
dictionary['third_name'] = third_name
dictionary['birth_year'] = birth_year
dictionary['current_age'] = 2015 - birth_year
print(dictionary) | false |
5916cd381c7af68c266485c4620df85c4ee7e50c | VikiDinkova/HackBulgaria | /Programming0-1/week1/compare.py | 223 | 4.125 | 4 | a = int(input('Enter a: '))
b = int(input('Enter b: '))
if a > b:
print('a(%s) is bigger than b(%s)' %(a,b))
elif a < b:
print('b(%s) iss bigger than a(%s)' %(b,a))
else:
print('a(%s) is equal to b(%s)' %(a,b))
| false |
a10e40baffbc1f239e37d982d86a4e0086ac9ac9 | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World1/Challenge017.py | 217 | 4.15625 | 4 | from math import hypot
co= float(input('Define a value of the Opposite side of a triangle: '))
ca= float(input('Define a value for the adjacent side: '))
print('The hypotenuse length is:{:.2f} '.format(hypot(co,ca))) | true |
892d224474e7f34b12977c10e6657f419518c43c | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World1/Challenge022.py | 333 | 4.125 | 4 | name = str(input('Type your full name:')).strip()
print('Your full name in upper case is {}'.format(name.upper()))
print('Your full name in lower case is {}'.format(name.lower()))
print('Your name excluding spaces has {} characters'.format(len(name)-name.count(" ")))
print('Your first name has {} characters'.format(name.find(' '))) | true |
562129b02f0675c9b1e16274cb2642a49a6ef463 | AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3 | /World 2/Challenge040.py | 602 | 4.125 | 4 | import emoji
grade1 = float(input('What is your first grade in Maths? '))
grade2 = float(input('Now tell me yor second grade in Maths: '))
average = (grade1 + grade2) / 2
print('Lets check how you did this semester!')
if average <= 5.0:
print(emoji.emojize('FAILLED :-1:! You need to repeat this subject next year.',use_aliases=True))
elif average >= 5.0 and average < 7.0:
print(emoji.emojize('You almost get :pray:, need REPEAT the subject!',use_aliases=True))
elif average >= 7.0:
print(emoji.emojize('Congratulations :gift::mortar_board:, you have been APPROVED!!!', use_aliases=True))
| true |
36fc133a282b83813bfb57f4544ba970ff2f5128 | khiladikk/Pandas_Basic_Operations | /Data lib1 (Pandas).py | 2,176 | 4.34375 | 4 | #Import Python Library
import pandas as pd
#Read csv file
data = pd.read_csv("Salaries.csv")
ranks = data["rank"]
#list the column names
data.columns
#return a tuplerepresenting the dimensionality
data.shape
#Check types for all the columns
data.dtypes
#List first 3 records
data.head(3)
#List last 3 records
data.tail(3)
#list the row labelsand column names
data.axes
#number of dimensions
data.ndim
#Numpy representation of the data
aa = data.values
"""
Data Frames: method loc
33
If we need to select a range of rows, using their labels
we can use method loc
"""
data.loc[5:15,["rank","phd","sex"]].values
"""
Data Frames: method iloc
If we need to select a range of rows and/or columns,
using their positions we can use method iloc
"""
data.iloc[5:15,[1,3,5]]
#return max values for all numeric columns
data["salary"].max()
#Return min values for all numeric columns
data.min()
#What are the mean values of the records in the dataset?
data.mean()
#generate descriptive statistics (for numeric columns only)
data.describe()
#returns a random sample of thedata frame
data.sample(5)
#Find how many values in the salarycolumn (use countmethod);
data.salary.count()
"""
Data Frames groupbymethod
Using "group by" method we can:
•Split the data into groups based on some criteria
•Calculate statistics (or apply a function) to each group
"""
a = data.groupby(["rank"])
a.count()
#Counting how many person's salary is more than 150000:
data["sex"][data["salary"]>150000].value_counts()
##Counting how many Phd scholers female's salary is more than 150000:
data["phd"][(data["salary"]>150000) & (data["sex"]=="Female")]
#We can sort the data using 2 or more columns:
data.sort_values(by=["phd",'rank'],ascending=[False,True])
data.sort_values(by=['phd','rank'], ascending = [True,True])
# Select the rows that have at least one missing value
data[data.isnull().any(axis=1)]
#There are a number of methods to deal with missing values in the data frame:
data.dropna()
df = data
# fill all the records having missing values, with mean of that column
for i in ["phd","salary"]:
df[i] = data[i].fillna(data[i].mode()[0])
| true |
84e0620a4699603ba2894ac460809c3f07a9b78d | Spitfire22/PdxCodeGuild | /Python/lab19-PalindromeAnagram.py | 1,181 | 4.25 | 4 | '''
Lab19 - Palindrome and Anagram checker
'''
## palindrome - if the string is equal to the reverse of the same string return true
# def palindrome(a,b):
# if a == b:
# ## if a == (a[::-1]):
# print('\'', word, '\'', 'is a palindrome')
# return
# elif a != b:
# ## elif a != (a[::-1]):
# print('\'', word, '\'', 'is not a palindrome')
# return
# else:
# return
#
# word = input('Palindrome checker - Enter a word: ')
# reverse = (word[::-1])
#
# palindrome(word, reverse)
## anagram Checker - input two words and determine if they are an anagram.
def wordfilter(a, b,):
string1 = a
string2 = b
a = a.lower()
a = a.replace(' ','')
a = sorted(a)
a = ''.join(a)
# print(a)
b = b.lower()
b = b.replace(' ', '')
b = sorted(b)
b = ''.join(b)
# print(b)
if a == b:
print('\'',string1,'\'','and','\'',string2,'\'','are anagrams')
elif a != b:
print('\'',string1,'\'','and','\'',string2,'\'','are not anagrams')
word_one = input('Anagram checker - Enter the first word: ')
word_two = input('Now for the second word: ')
wordfilter(word_one, word_two) | false |
bac947ceca8a2bfb80424c67d73f06440ffa7555 | mbuotte/Bike_shop | /bicycles.py | 1,952 | 4.15625 | 4 | class Bicycle (object):
"""
Bicycles have a model name, a weight, and a cost to produce.
"""
def __init__(self, model_name, weight, cost):
self.model_name = model_name
self.weight = weight
self.cost = cost
def _repr_(self):
return "{0} weighs {1} pounds and costs ${2} to produce.".format(self.model_name, self.weight, self.cost)
def changeName (self, model_name):
self.model_name = model_name
def changeCost (self, cost):
self.cost = cost
def changeWeight (self, weight):
self.weight = weight
# ------------------------------------------------------------------------
class BikeShop(object):
"""
Bike Shops have a name and an inventory.
"""
def __init__(self, shop_name, inventory, sold):
self.shop_name = shop_name
self.inventory = inventory
self.sold = sold
def _repr_ (self):
return "{0} Bike Shop carries: {1}".format(self.shop_name, self.inventory)
def sell_bike(self,model):
for bike in range(len(self.inventory)):
if str(self.inventory[bike].model_name) == str(model):
self.sold.append(self.inventory[bike])
break
return self.inventory[bike].model_name
def get_price (self,model):
for bike in range(len(self.inventory)):
if str(self.inventory[bike].model_name) == str(model):
return (self.inventory[bike].cost)
break
return (-1)
# ------------------------------------------------------------------------
class Customer(object):
"""
Customers have a name and fund of money.
"""
def __init__(self, customer_name, funds):
self.customer_name = customer_name
self.funds = funds
def _repr_ (self):
return "{0} has ${1}.".format(self.customer_name, self.funds)
def buy_bike (self, Bike):
self.funds = self.funds - Bike.cost
| true |
e1b4e3d9451f83c7e1d1e14d7b4fc27b677580c7 | logchi/MIT-6.00.1x | /MITx-6.00.1x/Week_1-_Python_Basics/2.-Core_Elements_of_Programs/Exercise:_for_exercise_2.py | 320 | 4.125 | 4 | # Exercise: for exercise 2
# (5/5 points)
# ESTIMATED TIME TO COMPLETE: 5 minutes
# 2. Convert the following code into code that uses a for loop.
# prints "Hello!"
# prints 10
# prints 8
# prints 6
# prints 4
# prints 2
None
print('Hello!')
for i in range(10, 0, -2):
print(i)
# Correct
| true |
2ddd7b29ab7b2f94140fe01388178f3bafa128b2 | zhanghao19/python | /test1_year.py | 998 | 4.25 | 4 | # -*- coding: utf-8 -*-
# 一年以后来优化此代码
def is_leap_year(year):
"""闰年判定:指定一个年份,判断它是否是闰年"""
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
def get_year_num(year):
"""计算这一年之前有多少天, 不包含这一年"""
days = 0
for i in range(1, year):
days += 366 if is_leap_year(i) else 365
return days
def get_month_num(month, year):
"""计算这个月之前有多少天, 不包含这个月"""
each_month = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # 每个月的天数
days = 0
for m in range(1, month):
days += 29 if m == 2 and is_leap_year(year) else each_month[m]
return days
def sum_days(year, month, day):
"""计算日期之前有多少天"""
return get_year_num(year)+get_month_num(month, year)+day
date1 = [1996, 8, 29]
date2 = [2019, 11, 1]
print(sum_days(*date2) - sum_days(*date1))
| false |
94d541810b89837c3538bfd17027ae1a1bf65115 | CAAC89/CODIGO-CAILIS | /PYTHON/LOGICA/numero factorial y fibonnaci.py | 253 | 4.15625 | 4 | n=8
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print factorial(n)
def fibonacci (n):
if n == 0 or n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print fibonacci(n) | false |
230d75525dfdda7bcd5e3f6ce2fe23b7480ae8e3 | Tekorita/Cursopython | /metodosdestring.py | 669 | 4.28125 | 4 | course = ' Curso de platzi'
my_string = 'Codigo Facilito'
"""Metodos de formato"""
result = '{a} de {b}'.format(a=course, b=my_string)
#result = result.lower()#minusculas
#result = result.upper()#mayusculas
#result = result.title()#titulo
"""Metos de busqueda"""
pos = result.find('Codigo')#busca la posicion en la que se encuentra el caracter
count = result.count('o')#busca cuantas veces se repite un caracter
"""Metodos de sustitucion"""
new_string = result.replace('o','x')#remplace un caracter por otro
new_string = result.split(' ')#combierte el string en una lista apartir de donde haya un espacio
#nuevo = course.split(' ')
print(new_string)
print(course) | false |
215913213bf531a0255ce54cfc0d566bac7ede2f | Hickerd/Jump_to_Python | /PycharmProjects/jump_to_python_02_3/venv/4.py | 385 | 4.1875 | 4 | a=[1,2,3]
a.append([4,5])
b=[1,2,3]
b.extend([4,5])
print(f'append >> {a}, extend >> {b}')
# append는 인자가 list일 때, 인자를 그대로 list에 추가하고 extend의 경우에는, list의 + 연산과 결과가 같다.
# append는 하나의 값을 추가하는 함수이며, extend는 기존 리스트에 입력받은 리스트를 더하는 함수이기에 차이가 있다. | false |
9cbf2519164643ab4d734237b68889c1416eb3e3 | hronorog/Python | /codewars.com/6kyu/WeIrD StRiNg CaSe.py | 1,027 | 4.40625 | 4 | '''Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.
The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').
Examples:
to_weird_case('String'); # => returns 'StRiNg'
to_weird_case('Weird string case') # => returns 'WeIrD StRiNg CaSe'
'''
def to_weird_case(string):
a = string.split(' ')
slovo = []
for i in a:
z = ''
for x in range(len(i)):
if x % 2 == 0:
z += i[x].upper()
else:
z += i[x].lower()
slovo.append(z)
return ' '.join(slovo)
print(to_weird_case('alag fsfsa yusss')) | true |
681e9178267e396948c0c00ad11d4e57557329ee | troyp/project-euler | /q4b.py | 1,387 | 4.1875 | 4 | # Find the largest palindrome made from the product of two 3-digit numbers.
# -------------------------------------------------------------------------
# Note: palindrome must be in range [10000, 998001]
# We have either:
# - a 6-digit palindrome defined by first 3 digits in range [100, 997]; or
# - a 5-digit palindrome defined by first 3 digits in range [100, 999]
seeds6 = xrange(997,99,-1)
seeds5 = xrange(999,99,-1)
def palindromes_in_range():
for seed in seeds6:
yield palindrome6(seed)
for seed in seeds5:
yield palindrome5(seed)
def main():
for candidate in palindromes_in_range():
for factor in xrange(max(100, candidate/999),
min(1000, candidate/100 + 1)):
if candidate%factor == 0:
return candidate
def rdigits(n):
"returns list of digits of an integer in reverse order"
ds = []
while n:
d = n%10
ds.append(d)
n /= 10
return ds
def fromdigits(ds):
"returns integer given list of digits"
n = 0
for d in ds:
n = 10*n + d
return n
def palindrome6(n):
"returns 6-digit palindrome given 3-digit integer"
for d in rdigits(n):
n = n*10 + d
return n
def palindrome5(n):
"returns 5-digit palindrome given 3-digit integer"
for d in rdigits(n)[1:]:
n = n*10 + d
return n
print main()
| true |
a1b58120b9ac81adc7a5a3802b7280aa887e45b4 | dungbachviet/SortingAlgorithms | /SortingAlgorithms/Python/SortAlgorithms/MergeSort.py | 2,293 | 4.125 | 4 | import sys
import functools
# Modify the build-in function print (remove character a default new line
# at the end of a string)
print = functools.partial(print, end="")
sys.setrecursionlimit(1500)# allocate more memory for stack
def mergeSort(unsortedList, left, right) :
if(left < right) :
middle = int((left + right) / 2)
mergeSort(unsortedList, left, middle)
mergeSort(unsortedList, middle + 1, right)
merge(unsortedList, left, middle, right) # should cast to right type before passing parameters (because default type is float)
# Merge two sorted arrays into an root array
def merge(unsortedList, left, middle, right) :
leftListSize = int(middle - left + 1)
rightListSize = int(right - middle)
leftList = leftListSize * [0]
rightList = rightListSize * [0]
for index in range(0, leftListSize) :
leftList[index] = unsortedList[left + index]
for index in range(0, rightListSize) :
rightList[index] = unsortedList[middle + 1 + index]
leftListIndex = 0
rightListIndex = 0
mainListIndex = left
while ((leftListIndex < leftListSize) and (rightListIndex < rightListSize)) :
if(leftList[leftListIndex] < rightList[rightListIndex]) :
unsortedList[mainListIndex] = leftList[leftListIndex]
leftListIndex += 1
else :
unsortedList[mainListIndex] = rightList[rightListIndex]
rightListIndex += 1
mainListIndex += 1
if(leftListIndex < leftListSize) :
for index in range(leftListIndex, leftListSize) :
unsortedList[mainListIndex] = leftList[index]
mainListIndex += 1
if(rightListIndex < rightListSize) :
for index in range(rightListIndex, rightListSize) :
unsortedList[mainListIndex] = rightList[index]
mainListIndex += 1
del leftList[:]
del rightList[:]
# Display the list on the screen
def printList(list) :
size = len(list)
for index in range(0, size) :
print("%f " % list[index])
print("\n")
# Demo the algorithm
unsortedList = [-12.3, 6.5, 27.8, -10, 30.85]
printList(unsortedList)
mergeSort(unsortedList, 0, len(unsortedList) - 1)
printList(unsortedList) | true |
1916b66112590e92bc34487dcabd36f8dc0e917d | mhichen/Patterns | /Sliding_Window/smallest_window_substring.py | 1,732 | 4.125 | 4 | #!/usr/bin/python3
import numpy as np
# Given a string and pattern, find smallest substring
# which has all the characters of the given pattern
# Time Complexity: O(2N) -> O(N) where N is the length of the string
# Space Complexity: O(M) where M is the lenth of the pattern
def smallest_window_substring(st, pattern):
# use hash table to track frequency of
# characters in pattern
freq = {}
for p in pattern:
if p not in freq:
freq[p] = 0
freq[p] += 1
# Keep track of character matches
match = 0
# Keep track of min substring length
min_len = np.inf
min_j = -1
min_i = -1
for j in range(len(st)):
if st[j] in freq:
freq[st[j]] -= 1
if freq[st[j]] == 0:
match += 1
if match == len(freq):
min_len = min(min_len, j + 1)
min_j = j
for i in range(0, len(st) - len(pattern) + 1):
if match == len(freq):
min_len = min(min_len, j - i + 1)
min_i = i
if st[i] in freq:
freq[st[i]] += 1
if freq[st[i]] > 0:
match -= 1
if min_len is not np.inf:
return st[min_i:min_j+1]
else:
return ""
#return min_len
if __name__ == "__main__":
S = "aabdec"
pattern = "abc"
# Expected output: "abdec"
print("Smallest substring", smallest_window_substring(S, pattern))
S = "abdbca"
pattern = "abc"
# Expected output: "bca"
print("Smallest substring", smallest_window_substring(S, pattern))
S = "adcad"
pattern = "abc"
# Expected output: ""
print("Smallest substring", smallest_window_substring(S, pattern))
| true |
3b2915eda707e21c1d009f1ed4b8be0cff420dc4 | chenyike/Practice | /inClassFileExample.py | 740 | 4.21875 | 4 |
def count_lines(list_of_lines):
'''Count number of lines in a list of lines. '''
return len(list_of_lines)
def count_words(list_of_words):
'''count words in a list of lines'''
word_count = 0
for line in list_of_lines:
list_of_words = lines.split()
word_count += len(list_of_words)
return word_count
##def count_characters(list_of_lines):
## for
def main():
# ask for a file name
filename = raw_input('Give me a file name please. \n')
# count characters
# count words
# count lines
f= open(filename)
lines = f.readlines()
print lines
print count_lines(lines)
f.seek(0)
content = f.read()
if __name__ == '__main__':
main()
| true |
ce8f93b931ff6ff456957ea0cbbb38d2066ea7df | JuliaAnten/Exit | /code graveyard/class.py | 824 | 4.15625 | 4 | #!/usr/bin/env python3
###############################################
#
#
#
#
#
#
###############################################
# dimension of the board (so that the car can get out of the area)
dimensions = 6
class Car():
def __init__(self): #(,x,y)
# Each Car has an (x,y) position.
self.x = 0
self.y = 0
def move_verical(self):
# Increment the y-position of the rocket.
if self.y == dimensions:
return print("max y dimensions")
self.y += 1
def move_horizontal(self):
# Increment the x-position of the rocket.
if self.x == dimensions:
return print("max x demensions")
self.x += 1
my_car = Car()
for i in range(7):
my_car.move_verical()
my_car.move_horizontal()
print(my_car.y)
print(my_car.x)
| true |
96855badf23205b8d07541d7d05d5e8aae479407 | thethomasmorris/CSC310 | /ThomasMorrisAssign3/ThomasMorrisAssign3Q3.py | 2,259 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Thomas Morris
Assignment 3
October 17, 2019
Implement a queue using linked lists. You should use your own class with the methods
(enqueue(object), dequeue(), first(), len(), is_empty(), search()) and include a testing.
Note that search(object) returns True (or False) to check if an object is in the Queue
Note:
Pages 264-266 in Data Structures and Algorithms were referenced
"""
class _Node:
def __init__(self, element, enext):
self._element = element
self._next = enext
class LinkedQueue:
def __init__(self):
self._head = None
self._tail = None
self._size = 0
def len(self):
return self._size
def is_empty(self):
return self._size == 0
def first(self):
#return but do not remove first element
if self.is_empty():
raise Exception('Queue is empty')
return self._head._element
def dequeue(self):
#remove first element from queue
if self.is_empty():
raise Exception('Queue is empty')
element = self._head._element
self._head = self._head._next
self._size -= 1
if self.is_empty():
self._tail = None
return element
def enqueue(self, e):
#add element to back of queue
newest = _Node(e, None)
if self.is_empty():
self._head = newest
else:
self._tail._next = newest
self._tail = newest
self._size += 1
def search(self, key):
#search the entire queue for the key element provided
pos = self._head
while pos:
if pos._element == key:
return True
pos = pos._next
return False
if __name__ == '__main__':
l1 = LinkedQueue()
l1.enqueue(5)
l1.enqueue(73)
l1.enqueue(9)
l1.enqueue(8)
l1.enqueue(16)
l1.enqueue(57)
l1.enqueue(95)
print(l1.search(5))
l1.dequeue()
print(l1.search(5))
print(l1.first())
print(l1.len())
print(l1.is_empty())
print(l1.search(73))
| true |
933aca7268dc87bb6a6e930cd847a2c7855d6885 | ande3674/sqlite_db_menu_program | /db_menu.py | 2,203 | 4.3125 | 4 | import sqlite3
import create_db_table_1
import add_row_2
import update_row_3
import delete_row_4
import display_all_rows_5
import display_one_row_6
### DATABASE MENU PROGRAM ###
# Program constants
CREATE_DB_AND_TABLE_CHOICE = 1
ADD_ROW_CHOICE = 2
UPDATE_ROW_CHOICE = 3
DELETE_ROW_CHOICE = 4
DISPLAY_ALL_ROWS_CHOICE = 5
DISPLAY_SINGLE_ROW_CHOICE = 6
QUIT_CHOICE = 7
def main():
choice = 0
while choice != QUIT_CHOICE:
# display menu
display_menu()
try:
# get user choice
choice = int(input('Enter your choice: '))
print('')
except ValueError:
print('ERROR: You must enter a number.')
print('')
if choice == CREATE_DB_AND_TABLE_CHOICE:
print('Creating products database and table...')
print('')
create_db_table_1.create_db_and_table()
elif choice == ADD_ROW_CHOICE:
add_row_2.add_row()
elif choice == UPDATE_ROW_CHOICE:
update_row_3.update_row()
elif choice == DELETE_ROW_CHOICE:
delete_row_4.delete_row()
elif choice == DISPLAY_ALL_ROWS_CHOICE:
display_all_rows_5.display_rows()
elif choice == DISPLAY_SINGLE_ROW_CHOICE:
display_one_row_6.display_one_row()
elif choice == QUIT_CHOICE:
break
else:
try:
choice = int(input('Invalid menu number. Select a menu option by entering the menu number: '))
print('')
except ValueError:
print('ERROR: You must enter a number.')
print('')
print('Thanks for using the products database program')
# display menu function
def display_menu():
print('***** DATABASE MENU OPTIONS *****')
print('1. Create database and database table')
print('2. Add a row of data to the table')
print('3. Update a row in the table')
print('4. Delete a row of data from the table')
print('5. Display all rows in the table')
print('6. Display a row of data based on an input value')
print('7. Quit program')
print('**********************************')
print()
main() | false |
d5c5af50726462e946b4654448ed58c64d354ff6 | furqanelahi/Student-Management-System | /stu.py | 1,638 | 4.125 | 4 | students=[]
while True:
print("Press 1 to Add Student")
print("Press 2 to Edit Student")
print("press 3 to student search")
print("press 4 to delete student")
print("press 6 to display all students")
print("press 5 to exit")
choice=int(input("Enter choice 1 to 6: "))
if choice==1:
student={}
student['Name']=input('Enter student name: ')
student['Age']=int(input('Enter student age: '))
student['Class']=input('Enter student class: ')
students.append(student)
if choice==5:
break
if choice==6:
print(students)
if choice==2:
id=input("Enter student name to update the data: ")
for fu in students:
if id ==fu['Name']:
fu['Name']=input("Enter name: ")
fu['Age']=int(input("Enter age: "))
fu['Class']=input("Enter class: ")
print("Record edited successfully.")
if choice==3:
stid =input("Enter Student Name to search the data.")
for fu in students:
if stid==fu['Name']:
print("Name:" +fu['Name'])
print("Age:" +str(fu['Age']))
print("Class:" +fu['Class'])
if choice==4:
sid=input("Enter Student Name to delete the data of that student.")
for fu in students:
if sid ==fu['Name']:
students.remove(fu)
print("Record Deleted Successfully.")
# del fu['Name']
# del fu['Age']
# del fu['Class']
else:
print("Please Enter a valid choice.") | true |
4c1a023abcdff8d6b1b58d9acfe2305c80a2d8eb | JonDevOps/pythonW3schoolsWork | /regex/findall-function.py | 204 | 4.40625 | 4 | # The findall() Function
# The findall() function returns a list containing all matches.
# Example
# Print a list of all matches.
import re
str = "The rain in Spain"
x = re.findall("ai", str)
print(x) | true |
5a2e1deb5223fd0d37b58eda53f97bb7f403734c | JonDevOps/pythonW3schoolsWork | /inheritance/1-create-a-parent-class.py | 2,802 | 4.65625 | 5 |
#Inheritance allows us to define a class that inherits all the methods and properties from another class.
#Parent class is the class being inherited from, also called base class.
#Child class is the class that inherits from another class, also called derived class.
# Create a parent class
# Any class can be a parent class, so the syntax is the same as creating any other class:
#Example
#Create a class named Person with firstname and lastname properties, and a printname method
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
# Create a child class
# To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class
# Example
# Create a class named Student, which will inherit the properties and methods from the Person class:
class Student(Person):
pass
# Note: Use the pass keyword when you do not want to add any other properties or methods to the class.
# Now the Student class has the same properties and methods as the Person class.
#Example
# Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
# Add the __init__() function
# So far we have cteated a child class that inherits the properties and methods from its parent.
# We want to add the __init__() function to the child class (instead of the pass keyword).
# Note: The __init__() function is called automacically every time the class is being used to create a new object.
# Example
# Add the __init__() function to the Student class:
"""
class Student(Person):
def __init__(self, fname, lname):
# add properties etc.
"""
# When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.
# Note: The child's __init__() function overides the inheritance of the parent's __init__() function.
# To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:
# Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
# Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality to the __init__() function.
# Add properties
# Example
# Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear) | true |
8594fa63c4516f544814273981a08da3f9bac06d | skoter87/testanketapython3 | /anketa.py | 753 | 4.15625 | 4 | name = input('Введите ваше имя: ')
surname = input('Введите вашу фамилию: ')
age = int(input('Введите ваш возраст: '))
weight = int(input('Введите ваш вес: '))
if age < 30 and (weight > 50 or weight < 120):
print('Вы в отличном состоянии!')
elif age >= 40 and (weight <= 50 or weight >= 120):
print('Вам стоит пойти к врачу!')
elif age <= 20 and (weight > 35 or weight < 70):
print('Здоровье студента в хорошем состоянии')
print('Имя пациента:'+ name)
print('Фамилия пациента:' + surname)
print('Возраст пациента:' + str(age))
print('Вес пациента:' + str(weight)) | false |
ebe6b231de399b2fac345cfe9a94b45d834f87a4 | jimmyblaszkiewicz/CMPSC132 | /Midterm/question2.py | 2,260 | 4.4375 | 4 | '''
James Blaszkiewicz
CMPSC 132 Midterm
Question 2
Create a Point2D class to emulate a point with 2 coordinates in x and y
Create a Point3D class to emulate a point with 3 coordinates in x, y, z
Create a Line class which has 2 end points,
each instances of either Point2D or Point3D
Create property methods of Line class distance and midpoint
that return the length of the line and the midpoint of the line, respectively
'''
# need sqrt from math
from math import sqrt
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
# 2 dimensional points have z=0, no matter what
# this makes calculations for midpoint and distance easier
self.z = 0
def __repr__(self):
# because z is 0, no need to display in the return
return "({}, {})".format(self.x, self.y)
class Point3D:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
# return 3 coords
return "({}, {}, {})".format(self.x, self.y, self.z)
class Line:
def __init__(self, point1, point2):
self.point1 = point1
self.point2 = point2
@property
def midpoint(self):
# the two points will have x and y values regardless of whether or not
# they are 3d
midX = round((self.point1.x + self.point2.x)/2, 3)
midY = round((self.point1.y + self.point2.y)/2, 3)
# keeping this calculation inside an if makes sure if both are 2D
# no wasted calculation for z1 = 0, z2 = 0
if isinstance(self.point1, Point3D) or isinstance(self.point2, Point3D):
midZ = round((self.point1.z + self.point2.z)/2, 3)
return Point3D(midX, midY, midZ)
return Point2D(midX, midY)
@property
def distance(self):
# if either point is 3D, do 3D calculations
if isinstance(self.point1, Point3D) or isinstance(self.point2, Point3D):
distance = sqrt((self.point1.x - self.point2.x)**2 + (self.point1.y - self.point2.y)**2 + (self.point1.z - self.point2.z)**2)
# otherwise, ignore z
else:
distance = sqrt((self.point1.x - self.point2.x)**2 + (self.point1.y - self.point2.y)**2)
return round(distance, 3)
| true |
34fb2c6903c2dd75db08081be54bb5a26cbbf303 | PM-Inno/analysepackage | /analysepackage/sorting.py | 1,896 | 4.46875 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order
Args:
items: a list of items
Returns:
array/list that is sorted in order
Examples
>>>bubble_sort([7,11,2,8,9,])
[2,7,8,9,11]
>>>bubble_sort([
'''
for i in range(0,len(items)-1):
for j in range(0,len(items)-1-i):
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j]
return items
def merge_sort(items):
'''Return array of items, sorted in ascending order'''
len_i = len(items)
# Base case. A list of size 1 is sorted.
# Cae returns, so if reached then function will terminate after line 8
if len_i == 1:
return items
# Recursive case. Find midpoint of list
mid_point = int(len_i / 2)
# divide list into two halves
i1 = merge_sort(items[:mid_point])
i2 = merge_sort(items[mid_point:])
# call merge_sort function on each half of list
return merge(i1, i2)
# Merge function.
def merge(A, B):
new_list = []
while len(A) > 0 and len(B) > 0:
if A[0] < B[0]:
new_list.append(A[0])
A.pop(0)
else:
new_list.append(B[0])
B.pop(0)
if len(A) == 0:
new_list = new_list + B
if len(B) == 0:
new_list = new_list + A
return new_list
def quick_sort(items):
if len(items) == 1 or len(items) == 0:
return items
else:
pivot = items[0]
i = 0
for j in range(len(items)-1):
if items[j+1] < pivot:
items[j+1],items[i+1] = items[i+1], items[j+1]
i += 1
items[0],items[i] = items[i],items[0]
first_part = quick_sort(items[:i])
second_part = quick_sort(items[i+1:])
first_part.append(items[i])
return first_part + second_part
| true |
0308f7268051b362e49f90792076272f2a78e99c | JgtL13/programming-languages | /questions/QuestionDemo.py | 1,666 | 4.28125 | 4 | ##
# This program shows a simple quiz with two question types.
#
import os
from questions import Question, ChoiceQuestion, NumericQuestion, FillInQuestion, MultiChoiceQuestion
def main() :
first = Question()
first.setText("Who was the inventor of Python?")
first.setAnswer("Guido van Rossum")
second = ChoiceQuestion()
second.setText("In which country was the inventor of Python born?")
second.addChoice("Australia", False)
second.addChoice("Canada", False)
second.addChoice("Netherlands", True)
second.addChoice("United States", False)
third = NumericQuestion()
third.setText("This is a test question for Q3, 10 + 0.1 = ?")
third.setAnswer(10)
fourth = FillInQuestion()
fourth.setAnswer("Guido van Rossum")
fourth.setText("The inventor of Python was", fourth._answer)
fifth = MultiChoiceQuestion()
fifth.setText("Which of the answers are true: (Please separate your answers with a space)")
fifth.addChoice("true", True)
fifth.addChoice("true", True)
fifth.addChoice("false", False)
fifth.addChoice("true", True)
fifth.addChoice("false", False)
presentQuestion(first)
print()
presentQuestion(second)
print()
presentQuestion(third)
print()
presentQuestion(fourth)
print()
presentQuestion(fifth)
print()
os.system("pause")
## Presents a question to the user and checks the response.
# @param q the question
#
def presentQuestion(q) :
q.display() # Uses dynamic method lookup.
response = input("Your answer: ")
print(q.checkAnswer(response)) # checkAnswer uses dynamic method lookup.
# Start the program.
main()
| true |
4cd1d9c92ed953f0017ed9d2c0fd5ac10d21da4a | Conor-Fennell/Application-Challenge | /task1.py | 1,575 | 4.28125 | 4 |
#I am assuming that the array may or not be ordered, and it may take positive and negative integers
def mostFreq(array):
#Checking if the array is empty or is of type None
if(array == None):
return None
if(len(array) < 1):
return None
frequency = {} #Create a dictionary/hash table and store the pair (number: frequency)
#Looping through the input array
for num in array:
if(num in frequency): #If out number has already been encountered, iterate its frequency by 1
frequency[num] = frequency[num] + 1
else: #Else the number is being encountered for the first time, add it to the dictionary with frequency of 1
frequency.update({num: 1})
print("Number: Frequency")
print(frequency)
#This gives us the list containing the integer which appeared most frequently
#If multiple integers appear most frequenctly we return a list containing each of those numbers
mostFreq = [num for (num, freq) in frequency.items() if freq == max(frequency.values())]
#If instead we assume that only a single integer will have the highest frequency,
#or we assume we can just return the 1st integer we encounter with the highest frequency:
#mostFreq = max(frequency, key=frequency.get)
#^^^This is good because its quicker than making a list of max frequency values
#But not so good because we are missing the other elements which appeared just as frequenctly
print("The most frequent integer(s) in the array is: "+str(mostFreq))
return mostFreq
| true |
116968cb6649f406434c79b1078dd2766ce24708 | facelli/geek_lessons | /second_lesson/3-d_task.py | 701 | 4.21875 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
seasons = {
(12, 1, 2): "зима",
(3, 4, 5): "весна",
(6, 7, 8): "лето",
(9, 10, 11): "осень"
}
month = int(input("Введите номер месяца:\n").lower())
for value in seasons.keys():
for digits in value:
digits = int(digits)
if digits == month:
value=tuple(value)
print(f"это {seasons.get(value)}") | false |
d98129dad826570f594c14f7cbc17543c70fd52d | tanvidongre/Coding-Test | /flatten.py | 494 | 4.21875 | 4 | """to flatten the array from the nested array"""
def flatten_array(input_array):
result_array = []
for item in input_array:
# for levels (nested list) in array
if type(item) is list:
result_array.extend(flatten_array(item))
# appending the element from the list
else:
result_array.append(item)
return result_array
if __name__ == '__main__':
input_array = input()
print(flatten_array(input_array))
| true |
638f081a8747bcdb499a03c4d911919e23589ca7 | chapman-cpsc-230/hw2-agust105 | /sum_powers.py | 715 | 4.15625 | 4 | """
File: sum_power.py
Copyright (c) 2016 Francis Agustin
License: MIT
* Queries the user for a floating point number, which we will call `b` (should not be equal to `1.0`),
and a natural number, which we will call `n`.
* Computes the sum `1 + b + b^2 + ... + b^n`.
* Prints the result of this computation
* Prints the `b^(n+1)/(b-1)`
"""
user_input = raw_input ("Enter value for b: ")
b = float (user_input)
while b == 1:
user_input = raw_input ("Value cannot be 1. Enter value for b: ")
b = float (user_input)
user_input2 = raw_input ("Enter value for n: ")
n = int (user_input2)
i = 0.0
sum_power = 0
while i <= n:
sum_power += b**i
i += 1
print sum_power
eq = ((b**(n+1)) - 1)/(b-1)
print eq
| true |
581f5d32ac1fa47c5da8ae68160851b8505dd0ef | AbaddooN/JornadaByLearn | /calculadora.py | 639 | 4.25 | 4 | while True:
operacao = input('Escolha uma das operacoes (+,-,*,/) que deseja fazer ou \'q\' para sair: ')
if operacao == 'q' or operacao == 'Q':
break
elif operacao == '+' or operacao == '-' or operacao == '*' or operacao == '/':
num1 = int(input('Digite o primeiro numero: '))
num2 = int(input('Digite o segundo numero: '))
else:
print('Operacao Invalida')
if operacao == '+':
total = num1 + num2
print(total)
elif operacao == '*':
total = num1 * num2
print(total)
elif operacao == '/':
total = num1 / num2
print(total)
elif operacao == '-':
total = num1 - num2
print:(total)
| false |
817f937c36e7eb2026c1e2689704e53e6e88addb | AndyMcMagadan/my_algoritms | /lesson_4/task_3.py | 2,815 | 4.25 | 4 | """
Задание 3.
Приведен код, формирующий из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Сделайте профилировку каждого алгоритма через cProfile и через timeit.
Обязательно предложите еще свой вариант решения и также запрофилируйте!
Сделайте вывод, какая из четырех реализаций эффективнее и почему!!!
Без аналитики задание считается не принятым
"""
from timeit import timeit
from random import randint
from cProfile import run
num_1 = randint(10000000000, 10000000000000000)
def revers_1(enter_num, revers_num=0): # -> Рекурсия, самое большое время выполнения. Сложность О(n!)
if enter_num == 0:
return revers_num
else:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return int(revers_1(enter_num, revers_num))
def revers_2(enter_num, revers_num=0): # -> Цикл с условием while - второй по медленности. Сложность О(n)
while enter_num != 0:
num = enter_num % 10
revers_num = (revers_num + num / 10) * 10
enter_num //= 10
return int(revers_num)
def revers_3(enter_num): # -> Преобразование числа в строку и взятие обратного среза. Самый быстрый. Сложность О(1)
enter_num = str(enter_num)
revers_num = enter_num[::-1]
return int(revers_num)
def my_revers(enter_num):
"""
Двойное преобразование числа в строку и список и получение обратного списка. Второй по скорости. Сложность О(n),
но за счет того, что функция reverse() - встроенная, работает быстрее, чем цикл while.
"""
my_list = list(str(enter_num))
my_list.reverse()
return int(''.join(my_list))
print(revers_1(num_1))
print(timeit("revers_1(num_1)", setup='from __main__ import revers_1, num_1', number=100000))
run('revers_1(num_1)')
print(revers_2(num_1))
print(timeit("revers_2(num_1)", setup='from __main__ import revers_2, num_1', number=100000))
run('revers_2(num_1)')
print(revers_3(num_1))
print(timeit("revers_3(num_1)", setup='from __main__ import revers_3, num_1', number=100000))
run('revers_3(num_1)')
print(my_revers(num_1))
print(timeit('my_revers(num_1)', setup='from __main__ import my_revers, num_1', number=100000))
run('my_revers(num_1)')
| false |
7d36bede61254aa5db45c5d1274bfc8f2911dede | AndyMcMagadan/my_algoritms | /lesson_4/task_1.py | 2,307 | 4.15625 | 4 | """
Задание 1.
Приведен код, который позволяет сохранить в массиве индексы четных элементов другого массива
Сделайте замеры времени выполнения кода с помощью модуля timeit
Оптимизируйте, чтобы снизить время выполнения. Проведите повторные замеры.
Добавьте аналитику: что вы сделали и почему!!!
Без аналитики задание не принимается
"""
from timeit import timeit
from random import randint
def func_1(nums):
new_arr = []
for i in range(len(nums)):
if nums[i] % 2 == 0:
new_arr.append(i)
return new_arr
def func_2(nums):
new_arr = [i for i in range(0, len(nums)) if nums[i] % 2 == 0]
return new_arr
def func_3(nums):
new_arr = [i for i, num in enumerate(nums) if num % 2 == 0]
return new_arr
my_nums = [randint(0, n * 33) for n in range(0, 100)]
print(timeit("func_1(my_nums)", setup='from __main__ import func_1, my_nums', number=100000))
print(func_1(my_nums))
print(timeit("func_2(my_nums)", setup='from __main__ import func_2, my_nums', number=100000))
print(func_2(my_nums))
print(timeit("func_3(my_nums)", setup='from __main__ import func_3, my_nums', number=100000))
print(func_3(my_nums))
"""
ИМХО, способ оптимизации заполнения второго массива индексами четных чисел из первого по сравнению с циклом for - сразу
вспомнил из своего небольшого опыта про list comprehension. Реализовал, замерил время выполнения с разными размерами
массивов - работает на 20-25% быстрее, чем через цикл for. Применение enumerate() вместо for внутри list comprehension
позволило выиграть еще около от 1% до 5% скорости. С увеличением исходного массива на порядок и более разница в
скорости работы (эффективность) снижается.
"""
| false |
fbb25c5b98d7622f7ce835ed604347e246cbc1ae | gaolu9595/HelloGithub | /simpleclass.py | 1,925 | 4.25 | 4 | #用class关键字来创建类
#类变量和对象变量:前者是各个对象所共享的,一旦有改变,该变动在其他所有实例中都能体现
#后者是每个实例对象都拥有其自己的副本,不是共享的
#coding = UTF-8
class Person:
'''表示一个带有名字和年龄的人的信息'''
#pass #表示一个空的代码块
population = 0 #population是一个类变量,不论被哪个对象改变,其变动都会永久存在
#__init__方法:对任何你想要进行操作的目标对象初始化,但是并不
def __init__(self,name,age=16):
self.name = name
self.age = age
print("(Initializing {}......)".format(self.name))
Person.population += 1
def sayhello(self):
print("Greetings, you can call me {0}, and I am {1} years old!"\
.format(self.name,self.age))
def die(self):
"""我挂了"""
print("{} died......".format(self.name))
Person.population -= 1
if Person.population == 0:
print("Unfortunately! I was the last survived person...")
else:
print("Congratulation! There are still {} person alive!".format(Person.population))
@classmethod
def how_many(cls):
'''打印当前人口数量'''
print("We have {} person alive now!".format(Person.population))
#创建带有初始化字段的实例对象
p1 = Person("Jack",34)
p2 = Person("Rebecca",32)
p3 = Person("Kate")
p4 = Person("Kevin")
p5 = Person("Randall")
for person in [p1,p2,p3,p4,p5]:
person.sayhello()
person.die()
Person.how_many()
print(Person.__doc__)
#'r表示内部的字符串默认不转义
print(r"I'm \"OK\"!")
print("I'm \"OK\"!")
print('''
i
am
a
student
'''
)
print(r'''hello,\n
world''')
print("中文测试正常")
#字符串是不可变对象
a = "abc"
print(a.replace("a","A"))
print(a)
b = a.replace("a","A")
print(b)
| false |
5d482366a342dd72a633f95b314c66001da0f354 | mangabhi/Python | /factorial_module.py | 314 | 4.21875 | 4 | #Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
import math
n=int(input("Enter a number: "))
p=math.palindrome(n)
print(p)
| true |
222d23794b503f870b3d381fcd6ad22b94cc73f1 | mangabhi/Python | /deci_to_bin.py | 288 | 4.25 | 4 | # Python3 program to convert a
# decimal number to binary number
def decToBinary(n):
binaryNum = [0] * n;
i = 0;
while (n > 0):
binaryNum[i] = n % 2;
n = int(n / 2);
i += 1;
for j in range(i - 1, -1, -1):
print(binaryNum[j], end = "");
n = 17;
decToBinary(n)
| false |
cbf91615fb03f1b97b381f20d5f0115c8a0b417e | gaofubao/algorithm019 | /Week_02/144_binary-tree-preorder-traversal.py | 1,631 | 4.125 | 4 | # 给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
# https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
class Solution1:
"""
递归法
"""
def preorderTraversal(self, root):
if not root:
return None
print(root.val)
self.preorderTraversal(root.left)
self.preorderTraversal(root.right)
class Solution2:
"""
递归法
"""
def preorderTraversal(self, root):
def preorder(root):
if not root: return None
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = []
preorder(root)
return res
class Solution3:
"""
迭代法
"""
def preorderTraversal(self, root):
res = list()
if not root:
return None
stack = []
node = root
while stack or node:
while node:
res.append(node.val)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
return res
if __name__ == "__main__":
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
e = TreeNode(5)
f = TreeNode(6)
g = TreeNode(7)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
s1 = Solution2()
result = s1.preorderTraversal(a)
print(result)
| false |
0585f74bed134869501429d28289319773e2cc69 | privateOmega/coding101 | /geeksforgeeks/find-rotation-count-rotated-sorted-array.py | 1,061 | 4.15625 | 4 | from typing import Optional, List
""" def count_rotations(array: Optional[List[int]] = None) -> Optional[int]:
if array is None:
return
minimum_element = array[0]
minimum_index = 0
for index, element in enumerate(array):
if minimum_element > element:
minimum_element = element
minimum_index = index
return minimum_index """
def count_rotations(low: int, high: int, array: Optional[List[int]] = None) -> Optional[int]:
if array is None:
return
if high < low:
return 0
if high == low:
return low
mid = low + (high - low) // 2
if mid < high and array[mid + 1] < array[mid]:
return mid + 1
if mid > low and array[mid] < array[mid - 1]:
return mid
if array[high] > array[mid]:
return count_rotations(array, low, mid - 1)
return count_rotations(array, mid + 1, high)
if __name__ == "__main__":
array = [15, 18, 2, 3, 6, 12]
array_length = len(array)
print(count_rotations(0, array_length - 1, array))
| true |
0a161c3a851096bc97c47bf15cdc1e181d3954e6 | fanghuicocacola/Fanghui-Lang | /python/PythonApplication1/PythonApplication1.py | 219 | 4.15625 | 4 | """用python设计第一个游戏"""
temp=input("please guess what number I am thinking")
guess=int(temp)
if guess==8:
print("right")
print("right is nothing")
else:
print("false")
print("game is over")
| true |
36d5421b1f5f6ec087db166da2bff3c065b98530 | umberleigh/py4e-exercises | /chapter_02_variables/ex_02-03_pay_calculator.py | 238 | 4.1875 | 4 | # Prompt user for hours worked and hourly rate of pay.
# multiply the two together as float and display the result
hours = input('Enter Hours: ')
rate = input('Enter rate: ')
gross_pay = float(hours) * float(rate)
print('Pay:', gross_pay) | true |
a4035d27fff819089fba55d576fef792a392296b | mutakubwa/python_practice | /mergesort.py | 1,520 | 4.28125 | 4 | def sort(unsorted):
'''
merge sort function to recursively sort using merge sort
'''
l1 = unsorted
a = 0
b = len(l1)-1
k = (a + b) // 2 #middle index
sorted = []
if (a == b):
sorted.append(l1[0])
elif ( len(l1) == 2 ):
array1 = l1[:a+1]
array2 = l1[b:]
if (array1[0] > array2[0]):
sorted.append( array2[0] )
sorted.append( array1[0] )
else:
sorted.append( array1[0] )
sorted.append( array2[0] )
else:
array1 = l1[:k]
array2 = l1[k:]
q1 = sort(array1)
q2 = sort(array2)
q3 = merge(q1, q2)
sorted += q3
return sorted
def merge(left, right):
'''
merge two arrays while sorting them
'''
result=[]
in_left = in_right = 0
if len(left) == 0:
return right
elif len(right) == 0:
return left
else:
while len(result) <= ( len(left) + len(right) ):
if left[in_left] <= right[in_right]:
result.append( left[in_left] )
in_left += 1
else:
result.append( right[in_right] )
in_right += 1
#if at the ned just add either array
if in_right == len(right):
result += left[in_left:]
break
if in_left == len(left):
result += right[in_right:]
break
return result
| false |
fb2b9d919a8c87974614be7b0117c287e84d09ff | jacob-dowdy/Intro-to-Python-Course | /19 - str_analysis.py | 395 | 4.125 | 4 | # function that takes an argument and determines if alpha, small or big number
def str_analysis(arg):
if str(arg).isdigit():
if int(arg) > 99:
print("That's a big number")
else:
print("That's a small number")
elif arg.isalpha():
print("Entry is alpha")
else:
print("Entry is neither all alpha nor all digit")
str_analysis(80)
| true |
49496d352ba62ff65bb016cb8f06cba76b61781c | katonamac/CSES-7960 | /day5.py | 1,556 | 4.375 | 4 | #Opening and writing to files
fileName = open('practiceTextFile.txt', 'r')
print(fileName)
for line in fileName:
print(line)
print(type(fileName))
fileName.close()
#Because it is an object of a specific type, we know that there are attributes
#and methods associated with that type
#We will be using dot notation, see below methods:
fileName.read()
#This one prints the whole file as one string.
fileName.readline()
#This one goes through the lines one at a time.
fileName.readlines()
#This one puts all the lines into a list.
#How can we find the number of sequences in a FASTA file?
fasta = open('shortFasta.fasta', 'r')
counter = 0
for line in fasta:
if line.startswith('>'):
counter +=1
print counter
fasta.close()
#Writing to a file
ids = open('identifiers.txt','w')
fasta = open('shortFasta.fasta', 'r')
for line in fasta:
if line.startswith('>'):
ids.write(str(line) + '\n')
fasta.close()
ids.close()
ids = open('identifiers.txt','r')
for line in ids:
print(line)
ids.close()
#Now make it a function
def getIdentifiers(readinfile, writeoutfile):
ids = open(writeoutfile, 'w')
fasta = open(readinfile, 'r')
for line in fasta:
if line.startswith('>'):
ids.write(str(line) + '\n')
fasta.close()
ids.close()
#Homework - go to Project Gutenberg, pull up the 1997 index,
#and write all the Shakespeare books to a file called Shakespeare.txt
#Also, do Practice 3 from Opening, Reading, and Writing to Docs | true |
848c2fc62a51f9f699cce0db45164fb67c33c54f | marysiuniq/advent_of_code_2020 | /22/puzzle_22_1.py | 1,795 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 05:41:38 2020
@author: Marysia
Puzzle 22 part 1 from https://adventofcode.com/2020/day/22
--- Day 22: Crab Combat ---
Before the game starts, split the cards so each player has their own deck (your
puzzle input). Then, the game consists of a series of rounds: both players draw
their top card, and the player with the higher-valued card wins the round. The
winner keeps both cards, placing them on the bottom of their own deck so that
the winner's card is above the other card. If this causes a player to have all
of the cards, they win, and the game ends.
Once the game ends, you can calculate the winning player's score. The bottom card
in their deck is worth the value of the card multiplied by 1, the
second-from-the-bottom card is worth the value of the card multiplied by 2, and so on.
Play the small crab in a game of Combat using the two decks you just dealt.
What is the winning player's score?
"""
def get_data():
with open('input.txt', 'r') as in_file:
data_str = in_file.read()
return data_str.split('\n')
def play_game(p1, p2):
while bool(p1) and bool(p2):
card1 = p1.pop(0)
card2 = p2.pop(0)
if card1 > card2:
p1 += [card1, card2]
else:
p2 += [card2, card1]
return p1, p2
def determine_score(p1, p2):
if p1 > p2:
score = 0
for i, card in enumerate(p1):
score += card * (len(p1)-i)
else:
score = 0
for i, card in enumerate(p2):
score += card * (len(p2)-i)
return score
INPUT = get_data()
PLAYER1, PLAYER2 = play_game([int(_) for _ in INPUT[1:INPUT.index('')]],
[int(_) for _ in INPUT[INPUT.index('')+2:]])
print(determine_score(PLAYER1, PLAYER2))
| true |
6c90b39cc1c55970601591709730099292f3c4fa | adamthurtell/crash_course_python | /Chapter_7/sandwich_orders_no_pastrami.py | 987 | 4.1875 | 4 | # Start with two lists, one with the list of sandwiches to be made,
# another empty list with finished sandwiches:
sandwich_orders = ['pastrami','poor boy', 'rueben', 'pastrami', 'philly cheesesteak',
'pastrami', 'roast beef']
finished_sandwiches = []
print("Sorry! We have run out of pastrami!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
# While there are sandwiches in sandwich_orders, pop off a sandwich and hold it
# in the variable current_sandwich
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
# Print each sandwich as it's made, then append it onto the list of finished
# sandwiches:
print("\nMaking your " + current_sandwich.title() + " right now.")
finished_sandwiches.append(current_sandwich)
# Finally, print all the finished sandwiches:
print("\nThe following sandwiches have been made: ")
for finished_sandwich in finished_sandwiches:
print("\t" + finished_sandwich.title()) | true |
538d12f1aa47a441ef4490f0b484ca5dcba4fb17 | adamthurtell/crash_course_python | /Chapter_8/make_album_input.py | 659 | 4.15625 | 4 | def make_album(album_title, artist_name, tracks=''):
"""Return a dictionary about an album"""
album = {'artist': artist_name, 'album': album_title}
if tracks:
album['tracks'] = tracks
return album
while True:
print("\nEnter the album information")
print("(enter 'q' at any time to quit)")
analbum = input("Album name: ")
if analbum == 'q':
break
artist = input("Artist name: ")
if artist == 'q':
break
track_nmbr = input("How many tracks ('return' to leave blank): ")
if track_nmbr == 'q':
break
album_info = make_album(analbum, artist, track_nmbr)
print(album_info) | true |
98ce2d58feb379fc3fb2cad3a0655a50d2163e19 | adamthurtell/crash_course_python | /Chap_4-7/cities.py | 824 | 4.125 | 4 | cities = {
'kathmandu': {
'country': 'nepal',
'population': 1081845,
'fact': 'people poop in each other\'s mouths',
},
'detroit': {
'country': 'united state',
'population': 'popdetroit',
'fact': 'factdetroit',
},
'london': {
'country': 'england',
'population': 'poplondon',
'fact': 'factlondon',
},
}
for city_name, city_info in cities.items():
print("\nHere is some information about " + city_name.title() + ":")
country_name = city_info['country']
city_pop = city_info['population']
fun_fact = city_info['fact']
print(city_name.title() + " is in " + country_name.title() +
" and has a population of " + str(city_pop) + ". A fun fact about " +
city_name.title() + ": " + fun_fact + ".") | false |
011e46ff8fab03085bb66af4021b7bea9fd6adad | aciorra83/quick_python_projects | /password_generator.py | 952 | 4.25 | 4 | # random module is going to be used to generate random passwords
import random
print('Welcome to your password generator')
print('=' * 35)
# all possible characters for a strong and unique password
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*().,?0123456789'
# user defined input for number of passwords to create, it needs to be a number and not a string
number = int(input('Number of passwords to generate: '))
# user defined password character length, must be a number and not a string
length = int(input('Number of characters in your password: '))
print('\nHere are your password(s):')
# nested for loop, creates number of user defined passwords and password length
for pwd in range(number):
passwords = ''
for i in range(length):
# imported random module. choice() method takes the arg of chars and randomly selects the characters of the string
passwords += random.choice(chars)
print(passwords)
| true |
8c2d6ac34b659a3a83d9354cb418cc6c2bc28559 | AndrewXiong2097/Python | /inputExerciseANS.py | 1,197 | 4.25 | 4 | '''
This is an exercise drill that you can try if you want to practice making
more input functions.
'''
#1) Get input from the user to the question "What is your friends name?"
#and store their answer in a variable called friend.
friend = input("What is your friend's name?")
#2) Get input from the user to the question "What month is it(number form)?"
#and store their answer in a variable called month. Convert month from a
#string variable to a int variable.
month = int(input("What month is it(number form)?"))
#3) Get input from the user to the question "What is the name of the city you
#grew up in?" and store their answer in a variable called city.
city = input("What is the name of the city you grew up in?")
#4) Get input from the user to the question "What brand of laptop do you have
#(Dell, Mac, etc.)?" and store their answer in a variable called laptop.
laptop = input("What brand of laptop do you have (Dell, Mac, etc.)?")
#5) Get input from the user to the question "What is your GPA(no decimal)?"
#and store their answer in a variable called gpa. Convert gpa from a string
#variable to a int variable.
gpa = int(input("What is your GPA"))
| true |
a102d8b5dca04449692737f08d1333188777e000 | nickshears/python | /student_marks.py | 1,079 | 4.3125 | 4 | # create a list of acceptable numbers
acceptable_range = range(0, 100)
# define an empty list
numbers = []
# define a random acceptable number so the loop can start
number = 0
# keep asking the user for a number and appending it as long as they do not enter "-1"
while number != -1:
number = int(input("please enter a number"))
if number in acceptable_range:
numbers.append(number)
else:
# not sure why this is neccesary :s
if number != -1:
print("Number is not within the range of 0-100")
# if the program made it this far, then its time to do some calculations
# calculate the lowest and highest numbers entered
lowest_number = 100
highest_number = 0
total_value = 0
for number in numbers:
if number < lowest_number:
lowest_number = number
if number > highest_number:
highest_number = number
total_value = total_value+number
# calculate mean value, average of all numbers entered
mean_value = total_value/len(numbers)
print("Exiting. Mean value is "+str(mean_value)+", Minimum is "+str(lowest_number)+", Maximum is "+str(highest_number))
| true |
d227dd27b391e056dad0488abef184c71866af9e | rwalker152/COVID19_tracker_data_extraction | /workflow/python/covid19_scrapers/utils/parse.py | 1,376 | 4.28125 | 4 | def raw_string_to_int(s, error='raise', default=None):
"""Some parsed strings have additional elements attached to them such
as `\n` or `,`. This function filters those elements out and
casts the string to an int.
Params:
s: the string to be parsed
error: either 'raise' or 'return_default'. 'raise' will raise an error on an empty parsed string.
'return_default' will return the value of `default` on an empty parsed string
default: if error is set to `return_default,` this value will be returns on an empty parsed string
"""
if error not in ['raise', 'return_default']:
raise ValueError(f'raw_string_to_int: error param must be "raise" or "return_default", not "{error}"')
nums = [c for c in s if c.isnumeric()]
if nums:
return int(''.join(nums))
if error == 'raise':
raise ValueError(f'Unable to parse "{s}" as int')
else:
return default
def maybe_convert(val):
"""Remove certain characters from the input string, then tries
to convert it to an integer, falling back to a float, falling back
to the modified string.
"""
val = val.replace(',', '').replace('%', '').replace('NA', 'nan').strip()
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
return val
| true |
cef1946c3e9cbaa83a4b06a37864f4ea22efaf04 | pollyyao/CodingBatSolution-Python | /Logic-1/cigar_party.py | 648 | 4.25 | 4 | """
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when
the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper
bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise.
cigar_party(30, False) → False
cigar_party(50, False) → True
cigar_party(70, True) → True
"""
def cigar_party(cigars, is_weekend):
if is_weekend:
if cigars>=40:
return True
else:
return False
else:
if cigars>=40 and cigars<=60:
return True
else:
return False
| true |
5cc731b83795a121f90952e6e473ddd9d5a72829 | pranavarora1895/Python_DSA | /insertion_sort.py | 396 | 4.34375 | 4 | def insertionSort(unsorted_array):
"""Sort list of comparable elements into ascending order."""
for k in range(len(unsorted_array)):
curr = unsorted_array[k]
j = k
while j > 0 and unsorted_array[j - 1] > curr:
unsorted_array[j] = unsorted_array[j - 1]
j -= 1
unsorted_array[j] = curr
a = [5, 4, 7, 3, 1]
insertionSort(a)
print(a)
| false |
aba800dfeef7b00595b557f1c9f513d4f2a6f822 | Seizen91/pythonCode | /hello/src/test_list.py | 2,065 | 4.3125 | 4 | # python3 列表 list
# 访问列表中的值
list1 = ["Google", "Runoob", 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
print("list1[0]: ", list1[0])
print("list[1:5]: ", list2[1:5])
print()
# 更新列表
print("第三个元素为:", list1[2])
list1[2] = 2001
print("更新后的第三个元素为:", list1[2])
print()
# 删除列表元素
print(list1)
del list1[2]
print("删除第三个元素:", list1)
print()
# 添加列表元素
list1.append("hello python")
print(list1)
print()
# python列表脚本操作符
print(len([1, 2, 3])) # 列表长度
print([1, 2, 3] + [4, 5, 6]) #列表组合
print(['Hi!']*4) # 列表重复
print(3 in [1, 2, 3]) # 判断元素是否存在列表中
for x in [1, 2, 3]: print(x, end=" ") # 列表迭代
print()
# python列表截取与拼接
L = ['Google', 'Runoob', 'Taobao']
print(L[2])
print(L[-2])
print(L[1:])
# print(L[3]) 超出列表下标会报错
print(L + ["Hello", 2, 3])
print()
# 嵌套列表
a = ['a', 'b', 'c']
n = [1, 2]
x = [a, n]
print(x)
print(x[0][1])
print(x[1][1]) # 下标越界都会报错
print()
# python列表函数
list1 = ['Google', 'Runoob', 'Taobao']
print(len(list1))
print(max(list1))
print(min(list1))
tuple1 = ("hell0", "Python", 1)
print(list(tuple1)) # 将元组转换为列表
print()
# python列表方法
list1.append("hello")
print(list1)
list1.append("hello")
print(list1.count("hello"))
list1.extend([1, 2, 3])
print(list1)
print(list1.index("hello"))
list1.insert(2, "python")
print(list1)
print(list1.pop()) # 默认移除最后一个
print(list1)
print(list1.pop(3))
print(list1)
print(list1.remove("hello")) # 移除列表中某个值的第一个匹配项
print(list1)
list1.reverse()
print(list1)
vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort(reverse=True)
print("降序输出:", vowels)
def take_second(elem):
return elem[1]
# define a list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=take_second)
print("排序列表:", random)
list2 = list1.copy()
print(list2)
list1.clear()
print(list1)
print(list2)
print()
| false |
916eac842137f8252d6c3416693c5477fdd43c08 | Seizen91/pythonCode | /hello/src/test_function.py | 2,043 | 4.5 | 4 | # python3 函数
"""
参数:
1、必须参数
2、关键字参数
3、默认参数
4、不定长参数
"""
# 必须参数
def printme(str):
"打印任何输入的字符串"
print(str)
return
printme("hello python") # 调用函数时必须输入参数,否则会报错
# 关键字参数
printme(str="菜鸟教程")
def printinfo(name, age):
"打印任何传入的字符串"
print("名字:", name)
print("年龄:", age)
return
printinfo(age=50, name="runoob")
# 默认参数
def printinfo1(name, age=34):
print("名字:", name)
print("年龄:", age)
return
printinfo1(age=50, name="runoob")
print("===============")
printinfo1(name="runoob")
# 不定长参数
def printinfo2(arg1, *vartuple):
print("输出:")
print(arg1)
for var in vartuple:
print("var= ", var)
return
printinfo2(10)
printinfo2(50, 23, 12)
# 声明函数时,参数中星号(*)可以单独出现
# 用法:星号(*)后的参数必须用关键字传入
def f(a, b, *, c):
return a + b + c
print(f(1, 2, c=3))
# 匿名函数
sum = lambda agr1, arg2: agr1 + arg2
print("相加后的值为:", sum(10, 20))
print("相加后的值为:", sum(20, 20))
# return语句
def sum(arg1, arg2):
total = arg1 + arg2
print("函数内:", total)
return total
total = sum(10, 20)
print("函数外:", total)
# 全局变量和局部变量,变量访问顺序由内而外
# global和nonlocal关键字
# 当内部作用域想修改外部作用域的变量是,就要用到global和nonlocal关键字
num = 1
def fun1():
global num # 需要使用global关键字声明
print(num)
num = 123
print(num)
fun1()
print(num)
# 如果要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量则需要nonlocal关键字
def outer():
num1 = 10
def inner():
nonlocal num1 # nonlocal关键字
num1 = 100
print(num1)
inner()
print(num1)
outer()
| false |
dee71d4734413387e9fa93b5e296eb66908611b1 | awelsh615/Election_Analysis | /grade_practice.py | 677 | 4.25 | 4 | #What is the grade?
score=int(input("What is your test score?"))
#Determine the grade
#if score>=90:
# print('Your grade is an A.')
#else:
# if score>=80:
# print('Your grade is a B.')
# else:
# if score>=70:
# print('Your grade is a C')
# else:
# if score>=60:
# print('Your grade is a D.')
# else:
# print('Your grade is an F.')
#Refactor with elif
if score>=90:
print('Your grade is an A.')
elif score>=80:
print ('Your grade is a B.')
elif score>=70:
print('Your grade is a C.')
elif score>=60:
print('Your grade is a D.')
else:
print('Your grade is an F.') | true |
b3ac93329a7976f21e80cb9f8796a7ca760ac603 | manufebie/computer_science_assignmet_2 | /exercise_12.py | 1,682 | 4.3125 | 4 | '''
Exersice 12
In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. A simple set of heuristic rules can be given as follows:
a) If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.)
b) If the verb ends in ie, change ie to y and add ing
c) For words consisting of consonant-vowel-consonant, double the final letter before adding ing
d) By default just add ing
Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form returns its present participle form. Test your function with words such as lie, see, move and hug. However, you must not expect such simple rules to work for all cases.
'''
# if verb end in e, slice e and add ing
# if verb ends in ie, change ie to y and add ing
# be default add 'ing' to end of string
def make_ing_form(verb):
extension1 = 'ying'
extension2 = 'ing'
exceptions = ['be', 'see', 'flee', 'knee']
split_verb = list(verb)
# words ending with 'ie' into 'ying'
if verb.endswith('ie'):
# delete last 2 chars (ie)
del split_verb[-2:] # delete last 2 chars from list
split_verb.append(extension1) # append new form
present_verb = ''.join(split_verb) # set present_verb to string form of split_verb
return present_verb
elif verb.endswith('e'):
if verb not in exceptions:
del split_verb[-1:]
split_verb.append(extension2)
present_verb = ''.join(split_verb)
return present_verb
print(make_ing_form('be'))
print(make_ing_form('see'))
print(make_ing_form('die'))
print(make_ing_form('lie')) | true |
d9035948ee46ff130edc2e11b21694bb046b7b56 | geewillits/aws_restart | /searching_and_splitting_strings_lists.py | 403 | 4.15625 | 4 | fname = input("Enter file name: ")
#fname = "mbox-short.txt"
fh = open(fname)
count = 0
#for loop to iterate through the file
for line in fh:
if line.startswith('From '):
final_form = line.split()
count += 1
print(final_form[1]) #this calls on the 2nd item in the list using 1 (0,1,2...)
print("There were", count, "lines in the file with From as the first word")
| true |
50797fb55da7a7042763ba10137bc389f7d0db57 | hampusrosvall/data-structures-algorithms | /sorting algortihms/insertionsort.py | 367 | 4.28125 | 4 | def insertion_sort(array):
for i in range(1, len(array)):
j = i
while j > 0 and array[j] < array[j - 1]:
swap(j, j -1, array)
j -= 1
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
array = [8, 5, 2, 9, 5, 6, 3]
array_c = ['e', 'f', 'g', 'a', 'z', 'w']
print(insertion_sort(array_c)) | false |
1bf41ba2f373b45d3dfe59fd2a618f8123db3eed | Samruddhivvk/IP-LP3-SUBMISSION-PYTHON | /IP_LP3_PYTHON_SAMRUDDHI_KULKARNI_1388/LP3_Code1.py | 474 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
'''
Code 1:
Read two integers from STDIN and print three lines where
● The first line contains the sum of the two numbers.
● The second line contains the difference between the two numbers (first -
second).
● The third line contains the product of the two numbers.
'''
num1=int(input())
num2=int(input())
print(num1+num2)
print(num1-num2)
print(num1*num2)
'''OUTPUT:
12
6
18
6
72
'''
| true |
7367328b5221bcf5e2337c9f68606f9c1f300ff8 | casanas10/practice_python | /Strings/remove_vowels.py | 537 | 4.1875 | 4 | '''
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
'''
def removeVowels(str):
output = []
vowels = set(["a", "e", "i", "o", "u"])
for char in str:
if char not in vowels:
output.append(char)
return "".join(output)
str = "leetcodeisacommunityforcoders"
print(removeVowels(str))
assert removeVowels(str) == "ltcdscmmntyfrcdrs" | true |
835974f74cdfa13eb0d9cda159abea3d62719899 | casanas10/practice_python | /Sorting and Searching/bubble_sort.py | 1,201 | 4.15625 | 4 | def bubble_sort(nums):
#let's use a flag that tells us when the array is sorted
isSorted = False
#keep looping until the array is sorted
while not isSorted:
#lets assume the array is sorted to begin with
isSorted = True
#walk through the array checking neighboring elements
for i in range(len(nums) - 1):
#if element to the right is bigger than elem on left, swap them
if nums[i] > nums[i+1]:
temp = nums[i]
nums[i] = nums[i+1]
nums[i+1] = temp
#set the flag to False because is not sorted
isSorted = False
return nums
def countSwaps(nums):
isSorted = False
swaps = 0
while not isSorted:
isSorted = True
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
temp = nums[i]
nums[i] = nums[i + 1]
nums[i + 1] = temp
swaps += 1
isSorted = False
return swaps
def main():
nums = [5,1,4,2,8]
print(bubble_sort(nums))
nums = [4,2,3,1]
print(countSwaps(nums))
if __name__ == "__main__":
main() | true |
b2458ea25c15f1179e954e01e0a078adda8019f7 | veronicabaker/Introduction-to-Computer-Programming | /Computer Programming/is_palindrome.py | 1,487 | 4.25 | 4 | """
is_palindrome.py (4 points)
=====
Determine whether or not a string is a palindrome.
http://en.wikipedia.org/wiki/Palindrome
For our purposes, strings that are palindromes are strings that are the same
backwards and forwards. Some examples of palindromes include:
"racecar"
"straw warts"
"ABBA"
For this assignment, write two functions:
1. reverse(s)
a. reverses the order of the characters in a string...
b. takes a string as an argument
c. returns a new string with the letters of the original reversed
d. "hello" would return "olleh"
e. "" returns ""
f. write at least two assertions for this
2. is_palindrome(s)
a. determines whether or not the supplied string is a palindrome
b. takes a string as an argument
c. returns a boolean value: True if the string is a palindrome, False
otherwise
d. use the above reverse function to help determine whether it is a
palindrome or not
e. write at least two asssertions (one for a True case and one for a False
case)
"""
def reverse(s):
new_s = ""
for c in s:
new_s = c + new_s
return new_s
assert "olleh" == reverse("hello"), "return olleh for hello"
assert "tac" == reverse("cat"), "return tac for cat"
def is_palindrome(s):
reverse_s = reverse(s)
if reverse_s == s:
return True
return False
assert True == is_palindrome("ABBA"), "return true for palindrome"
assert False == is_palindrome("cat"), "returns false for non-palindrome"
| true |
65db94db28d82872612e747442551b4eb45a5c0d | veronicabaker/Introduction-to-Computer-Programming | /Computer Programming/questions_ch_5.py | 2,057 | 4.375 | 4 | """
questions_ch_5.py - 5 points
=====
* the questions in the comments below can be found in the required textbook,
Starting Out with Python
* type out the answers to each question within the comment, underneath the
dashed line: -----
"""
"""
Starting Out with Python - Chapter 5 - Multiple Choice (page 225)
7. (1/2 point) A _____ is a variable that is created inside a function.
a. global variable
b. local variable
c. hidden variable
d. none of the above; you cannot create a variable inside a function
-----
b. local variable
8. (1/2 point) A(n) _____ is the part of a program in which a variable may be accessed.
a. declaration space
b. area of visibility
c. scope
d. mode
-----
c. scope
9. (1/2 point) A(n) _____ is a piece of data that is sent into a function.
a. argument
b. parameter
c. header
d. packet
-----
a. argument
10.(1/2 point) A(n) _____ is a special variable that receives a piece of data when a function is called.
-----
a. argument
b. parameter
c. header
d. packet
b. parameter
11.(1/2 point) A variable that is visible to every function in a program file is a _____.
a. local variable
b. universal variable
c. program-wide variable
d. global variable
-----
d. global variable
12.(1/2 point) When possible, you should avoid using _____ variables in a program.
a. local
b. global
c. reference
d. parameter
-----
b. global
"""
"""
Starting Out with Python - Chapter 5 - Short Answer (page 113)
5. (1/2 point) What is a local variable's scope?
-----
If a variable is only named in a nested block or a nested function then it's scope is
that block or function
6. (1/2 point) Why do global variables make a program difficult to debug?
-----
any statement in a program has the ability to change the value of a global variable
to find an error you would have to look at every single statement using the global variable
8. (1/2 point) What statement do you have to have in a value-returning function?
-----
return
9. (1/2 point) What three things are listed on an IPO chart?
-----
input, processing, output
"""
| true |
1935d8276b4ba328255696a8cbf43cdb5b9f5794 | veronicabaker/Introduction-to-Computer-Programming | /Computer Programming/sort_words.py | 2,637 | 4.46875 | 4 | """
sort_words.py (6 points)
=====
Create a function called sort_words, that splits up a single string into two
lists nested in one larger list. One list will have words that have a length
less than or equal to a specified partion number, and the other list will
have words that are longer than that partition.
For example: "An awkard aardvark ate an apple!", with a partition of 3, would
give back [["an", "ate", 'an"],["awkard", "aardvark", "apple"]]
* it should have two parameters, a sentence and a partition length
* it will assume that the words in the sentence are separated by a space
* it will extract individual words from a sentence by:
* collecting every character in the sentence into a word
* ignoring punctuation marks
* until the character is a space
* at which point, the word is placed in the appropriate list
* if the word is smaller than the partition, place it in the first list
* if the word is larger than the partiion, place in in the second list
* then start collecting the next word
* hint: don't forget to collect the last word!
* both lists should be placed in another list (small words first, large
words second.
* the function should return the resulting list of lists
* call your function on the following sentence:
* "Holly hesitated, having hurled her hamburgers high."
* use a partiion of 5
* save the result into a variable
* print out the last element of the last list
"""
def driver_roll_up_the_partition_please(string, partition):
small_words = []
big_words = []
for c in string:
new_string = ""
word = ""
if c == " ":
place = string.find(" ")
new_string = string[:place]
word = ""
elif " " not in string:
for c in string:
if c.isalpha() == True:
word += c
if len(word) <= partition:
small_words.append(word)
elif len(word) > partition:
big_words.append(word)
return [small_words, big_words]
else:
continue
for c in new_string:
if c.isalpha() == True:
word += c
if len(word) <= partition:
small_words.append(word)
elif len(word) > partition:
big_words.append(word)
string = string[place + 1:]
assert [["An", "ate", "an"],["awkard", "aardvark", "apple"]] == driver_roll_up_the_partition_please("An awkard aardvark ate an apple!", 3)
result = driver_roll_up_the_partition_please("Holly hesitated, having hurled her hamburgers high.", 5)
print(result)
| true |
7ce4f95def4cfea05afe59a3d1e738a5a168f8d2 | veronicabaker/Introduction-to-Computer-Programming | /Computer Programming/multiples_of_seven.py | 927 | 4.40625 | 4 | """
multiples_of_seven.py (3 points)
=====
* create a function called multiples_of_seven
* it should take a list of numbers as an argument (don't worry about lists
with non-numeric data)
* it should return a *new* list with only numbers that are multiples of 7
* if there are no multiples of seven, return an empty list ([])
* come up with two assertions to test this
Example Output:
-----
print(multiples_of_seven([80, 49, 70, 125]))
[49, 70]
Hint:
Create a new list... and use a method called append to add elements to it!
my_list.append(number)
"""
def multiples_of_seven(numbers):
new_list = []
for i in numbers:
if i % 7 == 0:
new_list.append(i)
return new_list
assert [] == multiples_of_seven([1, 2, 3]), "return empty list if no multiples of 7"
assert [49, 70] == multiples_of_seven([80, 49, 70, 125]), "returns list of multiples of 7"
print(multiples_of_seven([80, 49, 70, 125])) | true |
5894fc4cf54b9fe451760854545f4eada6f8c0a1 | TareqMonwer/python_algoritms | /sorting/bubble/bubbleSort.py | 546 | 4.25 | 4 | def bubble_it(arr):
''' Sort an array/list by small '''
for i in range(len(arr)-1, 0, -1):
''' accessing 2nd item to last item '''
for j in range(i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# apply
mylist = [7,5,1,4,3]
bubble_it(mylist)
print(mylist)
''' Test This Code For Better Understanding '''
arr = [10,9,7,8,4,6]
for check_item in range(len(arr)-1, 0, -1):
# here arr[check_item] will be 9, 7,...
for j in range(check_item):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
| false |
4d50c564a5d741b529273353ddf1ae80b3d343cf | shubham1706/30-days-of-code | /python/regex/redemo.py | 1,834 | 4.375 | 4 | '''
Author: Shubham Dwivedi
Created on: January 13th 2019
'''
import re
str1 = "We are just creatures with skin and bones"
# The search method returns a single matched string ie the first string it matches
result = re.search(r'a\w\w', str1)
print(result.group())
# The findall method returns the list of the strings that are matched
result = re.findall(r'a\w\w', str1)
print(result)
# The match method checks if the pattern is at the begining of the string, if not it returns none
result = re.match(r'W\w', str1)
print(result.group())
str2 = "We are 124 just creatures with 567 skin and bones"
# The split method returns the list after spliting the string from the sequence
result = re.split(r'\d+', str2)
print(result)
# The sub method substitutes the string with the given sequence and the replacement
result = re.sub(r'and',"&", str1)
print(result)
# The quantifiers are used to tell us how many more characters we need in a pattern to be searched
# '+' quantifier means one or more characters of the sequence
result = re.findall(r'a\w+', str1)
print(result)
# '*' quantifer means zero or more characters in the sequence
result = re.findall(r'a\w*', str1)
print(result)
# '?' quantifer means zero or one characters in the sequence
result = re.findall(r'a\w?', str1)
print(result)
# {m} quantifer can be used to specify exact number of occurences in the sequence
result = re.findall(r'a\w{2}', str1)
print(result)
# {m,n} quantifer can be used to specify the lower limit and upper limit of the sequence
result = re.findall(r'a\w{1,2}', str1)
print(result)
str3 = " My date of birth is: 22/6/1998"
result = re.findall(r'\d{1,2}/\d{1,2}/\d{4}', str3)
print(result)
# "^" symbol is used to specify if the sequence is at the begining of the string, else returns none
result = re.search(r'^W\w*', str1)
print(result.group()) | true |
cded701f5039e22221141013f45c3b4ad1d756e3 | chamannarved/Faulty-Calculater | /faulty-calculater.py | 757 | 4.15625 | 4 | #Faulty Calculator
#faulty values: 45*3=555, 56+9=77,56/6=4
print("\n\t---Welcome to Faulty Calculator---")
num1=int(input("Enter first value: "))
num2=int(input("Enter second value: "))
op=input("Enter operetor: ")
if num1==45 and num2==3 and op=="*":
print("Result: 555")
elif num1==56 and num2==9 and op=="+":
print("Result: 77")
elif num1==56 and num2==6 and op=="/":
print("Result: 4")
else:
if op == "+":
print("Result: ", num1 + num2)
elif (op == "-"):
print("Result: ", num1 - num2)
elif (op == "*"):
print("Result: ", num1 * num2)
elif (op == "/"):
print("Result: ", num1 / num2)
elif (op == "%"):
print("Result: ", num1 % num2)
else:
print("invalid operetor")
| false |
191ccf58f32bfb4262481dddff313eec195931f8 | Robert12354z/Class-Labs | /PROGRAMMING PARADIGMS/First Functional Programs/question01.py | 812 | 4.15625 | 4 | #Roberto Reyes
#CIN:305807806
#Course: CS-3035-01
#Description: This py file is the recurssion file that uses the process_digits function to
# recursively go through an integer until the integer reaches a single digit place
def main():
number = int(input("Enter a integer: "))
print(process_digits(number,add))
print(process_digits(number,mult))
# Addition method that adds two integers
def add(x,y):
return x+y
# Multiplication function that multiplies two integers
def mult(x,y):
return x*y
# The process digits function takes any integer and uses whichever operation
def process_digits(n, operation):
if n >= 10:
x = operation(n%10 , process_digits(n//10, operation))
return x
else:
return n
if __name__ == "__main__":
main() | true |
ee0af66f5f043adcf872e82484b07f40d631fa3a | bubbletea93/learning-python | /python-fundamentals/list.py | 715 | 4.375 | 4 | friends = ["Bob", "Zoey", "Hank", "Bri", "Allen"]
numbers = [2, 4, 6, 8]
# Friend at index 0
print(friends[0])
# Access the last index
print(friends[-1])
# Indexes 1 and greater
print(friends[1:])
# Indexes from 1 up to but not including 3
print(friends[1:3])
# Add a list to the end of a list
# List can have different datatypes in it
friends.extend(numbers)
print(friends)
# Insert will add an element to the list at a specific index. Previous and all elements will be pushed up 1 accordingly.
friends.insert(1, "Jay")
print(friends)
# Count occurences of value in list
print(friends.count("Jay"))
# Sorting with list
# Will throw error if list contains different datatypes in a single list
print(friends) | true |
6c4e4f610790ba204a35d366233d029167d986ab | KronosOceanus/python | /元组/main.py | 719 | 4.15625 | 4 | # 元组是不可更改的,调用函数时可使用元组传参
x = (3,)
x = tuple(range(5))
print(x)
x = ([3, 5], 2)
x[0][0] = 7
x[0].append(8)
print(x)
# 生成器推导式,生成器对象遍历完之后就没了
g = (i for i in range(10))
x = tuple(g)
print(x)
print(list(g))
g = (i for i in range(3))
print(g.__next__()) #遍历
print(g.__next__())
print(g.__next__())
# 生成斐波那契数列
def f(): #创建可迭代的生成器对象
a, b = 1, 1 #初始值
while True:
yield a
a, b = b, a+b
a = f() #创建
for i in range(10):
print(a.__next__(), end=' ')
print()
for i in f(): #第一个 > 100 的数
if i>100:
print(i, end=' ')
break
| false |
f1618f35f9547acee88ce96148720f77328c7bfa | rng1234/lpthy_script | /ex31_self.py | 599 | 4.1875 | 4 | print """
_________________________________________
Bingo Game
_________________________________________
"""
input = "> "
name = raw_input("What's your name?")
print "You wake up in a room with no door, a light shaking on the ceiling. What will you do?"
print """
A. Look around
B. Scream
C. Knock the wall
D. Jeck off
"""
answer1 = raw_input(input)
if answer1 == "A":
print "You got a key. But where's the door?"
elif answer1 == "B":
print "Nothing happen."
elif answer1 == "C":
print "Walls so hard."
elif answer1 == "D":
print "You saved."
else:
print "You doomed." | true |
be3e623e895ef49428103aaa3511afce501cf9b1 | xiaolao/algorithm | /leetcode/python/206_reverse_linked_list.py | 1,562 | 4.3125 | 4 | # Reverse a singly linked list.
# Example:
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
# Follow up:
# A linked list can be reversed either iteratively or recursively. Could you implement both?
# Definition for singly-linked list.
class ListNode:
"""单链表节点"""
def __init__(self, x):
self.val = x
self.next = None
class ListIterator:
"""链表迭代器"""
def __init__(self, node: ListNode):
self.current = node
def __iter__(self):
return self
def __next__(self) -> int:
if self.current is None:
raise StopIteration
result = self.current.val
self.current = self.current.next
return result
class LinkList:
"""单链表"""
def __init__(self, val: int):
self.head = self.tail = ListNode(val)
def append(self, val: int):
"""添加节点到尾部"""
node = ListNode(val)
self.tail.next = node
self.tail = node
def __iter__(self) -> ListIterator:
"""返回列表迭代器对象"""
return ListIterator(self.head)
def __str__(self):
return "".join(str(i) for i in self)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev, cur = None, head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
if __name__ == "__main__":
link_list = LinkList(1)
link_list.append(2)
link_list.append(3)
link_list.append(4)
link_list.append(5)
print(str(link_list))
| true |
dee92729b8fe7451f82f169932cc0d9b3ea4db2e | Machin-Learning/Exercises | /invert_dict.py | 205 | 4.3125 | 4 | def invert_dict(input_dict):
output_dict = {}
for key,value in input_dict.items():
output_dict[value] = key
return output_dict
d = {'Box1':'Apple','Box2':'Mango'}
print(invert_dict(d)) | false |
5493354977fcf817a24d2800a6723ab385dc850a | elitan/euler | /004/index.py | 615 | 4.125 | 4 | #!/bin/py
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import math as m
def isPalindromic(n):
ret = False
n = str(n)
i = 0
if len(n)%2 == 0 and len(n) >= 2:
ret = True
while i < len(n)/2 and ret:
if n[0 + i] != n[len(n) - 1 - i]:
ret = False
i += 1
return ret
largest = 0
for i in range(100, 999):
for j in range(100, 999):
k = i * j
if isPalindromic(k):
if k > largest:
largest = k
print(largest) | true |
e209e424e20dd44ce22b2a540ceff1fd67063e18 | elitan/euler | /112/main.py | 1,331 | 4.1875 | 4 | """
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
"""
import sys
sys.path.append("../")
sys.stdout.flush()
import functions as f
def bouncy(nr):
pd = False
ud = 0;
if len(str(nr)) <= 2:
return False
for d in str(nr):
if pd != False:
if ud == 0:
if d > pd:
ud = 1;
elif d < pd:
ud = -1;
else:
if ud == 1 and d < pd:
return True;
elif ud == -1 and d > pd:
return True;
pd = d;
return False;
i = 0;
b = float(0);
while(True):
if bouncy(i):
b += 1
print(i)
if (b/i) == 0.99:
sys.exit()
i += 1
| true |
ed1dc2f502e61463cc00963e9d0d5b9a06fc2592 | elitan/euler | /055/main.py | 1,589 | 4.125 | 4 | #!/bin/py
"""
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?
"""
import sys
sys.path.append("../")
import functions as f
def revAdd(n):
return n + int(str(n)[::-1])
answer = 0
for n in range(1, 10000):
found = False
nn = n
for i in range(0,49):
nn = revAdd(nn)
print("Checking nr: %d" % nn)
if f.isPalindromic(nn):
found = True
print(i,n, nn)
break
if not found:
print("NOT FOUND FOR: %d" % n)
answer += 1
print(answer) | true |
fe78cd4da54c46aa4502e6c00611355c8a2675af | fegie8319/50BiginnerProjects | /Beginner Ideas/Prime Finder.py | 568 | 4.21875 | 4 | # # Code a script which finds the nth prime number for you. You just enter a number and it gives you the respective prime number. Example: Input an 11 and get a 31.
user_input = input("請輸入想找第幾個質數: ")
cal = int(user_input)
init_num = 2
listx = [2]
while True:
if len(listx) == cal:
ans = listx[-1]
print(ans)
break
init_num += 1
for i in range(2, init_num):
if init_num % i == 0:
break
if i == init_num -1:
listx.append(init_num)
break
| true |
058f831f72ed72099ec63c52c6ad9f584ed1438a | einstein2001/tutorials | /python_the_hard_way/ex3.py | 642 | 4.15625 | 4 | print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "I will now count the eggs:"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7?"
print 3+2<5-7
print "What is 3+2?",3+2
print "What is 5-7?",5-7
print "Oh, that's why it's false."
print "How about some more."
print "Is it greater?",5>-2
print "Is it greater or equal?", 5>=-2
print "Is it less or equal?", 5<=-2
print "Time to figure out what the hell the % does."
print 50 % 5.0
print 5%10
print 10.0%5.0
print 5.0%10.0
print 7.0 % 5.0
print "I guess the % is a modulo for the remainder of division. Whatever that means!"
| true |
41e9599800ecb45b33b0916d2400a7bc610da3f3 | Ecleptic/SHSU | /SHSU_Fall_2017/Special_Topics_2347/Notes/Codes/ch11_code/polymorphism_demo3.py | 847 | 4.28125 | 4 | # This program demonstrates polymorphism.
import animalsdefaultconstructor
def main():
# Create a Mammal object, a Dog object, and
# a Cat object.
mammal = animalsdefaultconstructor.Mammal('regular animal')
dog = animalsdefaultconstructor.Dog('Dog2')
cat = animalsdefaultconstructor.Cat()
# Display information about each one.
print('Here are some animals and')
print('the sounds they make.')
print('--------------------------')
show_mammal_info(mammal)
print()
show_mammal_info(dog)
print()
show_mammal_info(cat)
# The show_mammal_info function accepts an object
# as an argument, and calls its show_species
# and make_sound methods.
def show_mammal_info(creature):
creature.show_species()
creature.make_sound()
# Call the main function.
main()
| true |
f1f437ff129bfa8a2ec00308af6288469d14dc14 | Ecleptic/SHSU | /SHSU_Fall_2017/Special_Topics_2347/Notes/Codes/ch4_code/flower.py | 952 | 4.46875 | 4 | # This program draws a design using repeated circles.
import turtle
# Named constants
NUM_CIRCLES = 36 # Number of circles to draw
RADIUS = 25 # Radius of each circle
ANGLE = 10 # Angle to turn
ANIMATION_SPEED = 0 # Animation speed
# Set the animation speed.
turtle.speed(ANIMATION_SPEED)
# Draw the center of the flower as 36 circles, with the
# turtle tilted by 10 degrees after each circle is drawn.
for x in range(NUM_CIRCLES):
turtle.circle(RADIUS)
turtle.left(ANGLE)
# Reposition the turtle.
turtle.penup()
turtle.goto(0,0)
turtle.setheading(0)
# Draw the petals.
for x in range(36):
turtle.forward(RADIUS * 2)
turtle.pendown()
turtle.left(25)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.penup()
turtle.goto(0,0)
turtle.left(10)
| true |
6d3270d83c3bf27817462b70ce110bd94b155795 | jschrom311/codechallenges | /Python challenges/firstletter.py | 205 | 4.15625 | 4 | #Use a List Comprehension to create a list of the first
#letters of ever word in the string below.
#
st = 'Create a list of the first letters of ever word in this string'
[word[0] for word in st.split()] | true |
13437f67bd801d3352158ba24c62310a60e5b74b | ToddSmall/python-algorithms | /python_algorithms/dynamic_programming.py | 2,812 | 4.28125 | 4 | """Solving a few dynamic programming problems"""
from functools import lru_cache
import sys
from typing import List, Tuple
def cut_rod(prices: List[float], rod_length: int) -> float:
@lru_cache(maxsize=None)
def _cut_rod(rod_length):
if rod_length == 0:
return 0
revenue = -sys.maxsize
for i in range(1, rod_length + 1):
revenue = max(revenue, prices[i - 1] + _cut_rod(rod_length - i))
return revenue
return _cut_rod(rod_length)
def dice_rolls(num_rolls: int, sum_rolls: int) -> int:
"""How many ways can sum_rolls be achieved in num_rolls of a six-sided die?
https://codereview.stackexchange.com/a/161016
"""
@lru_cache(maxsize=None)
def _dice_rolls(num_rolls, sum_rolls):
if num_rolls == 0 and sum_rolls == 0:
return 1
if sum_rolls < num_rolls or sum_rolls > num_rolls * 6:
return 0
return sum(
_dice_rolls(num_rolls - 1, sum_rolls - value) for value in range(1, 7)
)
return _dice_rolls(num_rolls, sum_rolls)
def knapsack(
items: List[Tuple[int, int]], max_weight: int
) -> Tuple[int, List[Tuple[int, int]]]:
"""The classic 0/1 knapsack problem.
https://en.wikipedia.org/wiki/Knapsack_problem#0.2F1_knapsack_problem
http://codereview.stackexchange.com/a/20581
"""
@lru_cache(maxsize=None)
def best_value(i: int, w: int) -> int:
"""Return the best value that can be attained using the
first i items with weight <= w.
"""
if i == 0:
return 0
value, weight = items[i - 1]
if weight > w:
return best_value(i - 1, w)
return max(best_value(i - 1, w), best_value(i - 1, w - weight) + value)
# This code block is only necessary for listing the items.
# The best value can be, and is, computed without this
# code block.
w = max_weight
result = []
for i in range(len(items), 0, -1):
if best_value(i, w) != best_value(i - 1, w):
result.append(items[i - 1])
w -= items[i - 1][1]
result.reverse()
return best_value(len(items), max_weight), result
def min_remainder(i: int, j: int, total: int, G: List[List[int]]) -> int:
"""Google Foobar: Save Beta Rabbit
https://codereview.stackexchange.com/a/91593
"""
@lru_cache(maxsize=None)
def _min_remainder(i, j, total):
if total < 0 or i < 1 or j < 1:
return sys.maxsize
if i == 1 and j == 1:
return total
return min(
_min_remainder(i - 1, j, total - G[i - 1][j - 1]),
_min_remainder(i, j - 1, total - G[i - 1][j - 1]),
)
smallest = _min_remainder(i, j, total)
return smallest if smallest != sys.maxsize else -1
| true |
f260b3a2e28fb2242f233e5228f724da1e706933 | aksaann/proddec-coding | /task1.py | 827 | 4.375 | 4 | ''' Program to find the roots of a quadratic equation.'''
import math #importing math module
#accepting the coefficients from the user
a=int(input("Enter coefficient a: "))
b=int(input("Enter coefficient b: "))
c=int(input("Enter coefficient c: "))
d = b * b - 4 * a * c #calculating the discriminant
sqrt_val = math.sqrt(abs(d))
if a == 0:
print("Invalid") #If a is 0, then equation is not quadratic, but linear
elif d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else: #d<0
print("Roots are complex")
print(- b / (2*a) , " + i", sqrt_val)
print(- b / (2*a) , " - i", sqrt_val) | false |
54c25f725369260a7830d116c544306023adcac0 | SwarupDebnath/guess_the_number | /main.py | 870 | 4.125 | 4 | ans = 18
guess = 0
print("Guess a number from 1 to 60\nLevel 1 : 10 attempts, level 2 : 8 attempts, level 3 : 5 attempts")
lev = int(input("Choose level (1 or 2 or 3) : "))
if lev == 1:
guess = 10
elif lev == 2:
guess = 8
elif lev == 3:
guess = 5
attempt = guess
while guess > 0:
user = int(input("guess the number : "))
guess = guess - 1
if user == ans:
print("\nCongratulations you guessed it right and you took", attempt - guess, "attempts")
break
elif guess == 0:
print("\nGame over the secret number was", ans)
elif user > ans:
print("\nAttempts left :", guess)
print("The number is less than", user, end=", ")
continue
elif user < ans:
print("\nAttempts left :", guess)
print("The number is greater than", user, end=", ")
continue | true |
39465a08d026f9d97575dc8eefeb0904a15134ff | yashvesikar/pymoo | /pymoo/model/selection.py | 945 | 4.34375 | 4 | from abc import abstractmethod
class Selection:
"""
This class represents the selection of individuals for the mating.
"""
@abstractmethod
def set_population(self, pop, data):
"""
Set the population to be selected from.
Parameters
----------
pop: class
An object that stores the current population to be selected from.
data: class
Any other additional data that might be needed for the selection procedure.
"""
pass
@abstractmethod
def next(self, n_select):
"""
Choose from the population new individuals to be selected.
Parameters
----------
n_select: int
How many individuals that should be selected.
Returns
-------
select: vector
A vector that contains the result indices of selected individuals.
"""
pass
| true |
fcb92a2a269c8a9c1d2e6aa726bb01f8ae2d8210 | hhhhjjj/leetcode | /用队列实现栈.py | 1,270 | 4.21875 | 4 | # -*- coding: utf-8 -*-
from queue import Queue
# 直接调用个基本的fifo队列出来
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.my_queue = Queue()
# 一个是肯定不能完成的,需要两个
# 出栈其实也没啥技巧,就是循环一遍倒过来而已
# put插入,get直接出来一个最先进去的
self.top_num = None
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.my_queue.put(x)
self.top_num = x
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
length = self.my_queue.qsize()
# 这个不支持len,需要用自带的得到长度的
cur = 1
while cur <= length - 1:
self.top_num = self.my_queue.get()
self.my_queue.put(self.top_num)
cur += 1
return self.my_queue.get()
def top(self) -> int:
"""
Get the top element.
"""
return self.top_num
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return self.my_queue.empty() | false |
3ae976aeb5a22dafbac1a4ca572fa4f56ee883a4 | aymankazi9/Playground | /Labs/numbylab.py | 499 | 4.125 | 4 | # Arithmetic
# Addition
first = int(input("Enter a number: "))
second = int(input("Enter a 2nd number: "))
print("first + second = ", first + second)
# Subtraction (-)
# Repeat the last program, but this time make it subtract
# Multiplication (*)
# Division (/)
# Calculate remainder of Division (%)
# Square
# Try one input and square it
# Order of Operations use ()'s'
# Input the number (7), 7 * 3 + 4
# Input the number (7), do everything backwards, 4 + 3 * 7, did you get what you expect? | true |
42b0feda15d8f87826afb3730f152778dee5044b | RajatGarg1311/Python | /factorialRecursiveFunc.py | 379 | 4.40625 | 4 | #factorial using recursive function
def factorial(ip_no):
if ip_no == 0:
return 1;
else:
return (factorial(ip_no-1)*ip_no);
test_ip=int(input("Enter a number for getting its factorial value: "));
if test_ip >= 0:
test_op = factorial(test_ip);
print("The factorial of given Number ",test_ip," is ",test_op);
else:
print("The invalid number!");
| true |
bd550a265fc114e5a196ba372f44d7a65ca6ce75 | rid47/python_basic_book | /python_lynda/list_of_vowels.py | 215 | 4.375 | 4 | vowels = ['a', 'e', 'i', 'o', 'u']
vowels_in_word = []
for char in 'serendiptous':
# print(char)
if char in vowels and char not in vowels_in_word:
vowels_in_word.append(char)
print(vowels_in_word)
| false |
9d3968d01c2bc8fb7c44871d52baad8b700c81a8 | rid47/python_basic_book | /chapter18/review_exercise/page573/3.py | 364 | 4.40625 | 4 | '''
Write a program that displays an Entry widget that is forty text
units wide and has a white background and black text. Use
.insert() to display text in the Entry widget that reads "What is
your name?"
'''
import tkinter as tk
window = tk.Tk()
ent = tk.Entry(width=40, bg='white',fg='black')
ent.pack()
ent.insert(0,'What is your name?')
window.mainloop() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.