blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
2d7eb20c2f6eb18f3a8e7524df6decdceafb3cd7
|
1505069266/python-
|
/面向对象/公有,私有成员.py
| 1,202
| 4.125
| 4
|
class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
__score = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:' + name)
# print("我是:" + self.name)
# 行为与特征
def marking(self, score):
if score < 0:
score = 0
self.__score = score
# 这是一个私有方法
def __myName(self):
print(self.name)
# 模板
student1 = Student('zhuxiaole', 23)
student1.marking(95)
student1.__score = -1 # 为什么不会报错 这里是给student1新添加了一个__score属性 所有不会报错
print(student1.__score)
print(student1._Student__score) # 还是可以读取,但是不建议这样操作
print(student1.__dict__) # 保存着student1中的所有变量
print(Student.__dict__) # 保存着Student中的所有变量和方法
# 公开的 public 私有的 private
# python私有方法 __方法名
# python私有属性 __属性名
| false
|
7ac0ace8b17c80af072aa80be36b1831684c91da
|
1505069266/python-
|
/面向对象/静态方法.py
| 1,015
| 4.125
| 4
|
class Student:
name = ''
age = 0
# 一个班级里所有学生的总数
sum1 = 0
# 实例方法
def __init__(self, name, age):
# 构造函数 实例化的时候会运行这里的代码
self.name = name
self.age = age
self.__class__.sum1 += 1
print("当前班级人数:" + str(self.__class__.sum1))
# print('我是:' + name)
# print("我是:" + self.name)
# 行为与特征
def myNameAge(self):
print(self.name)
print(self.age)
@classmethod # 类方法 下面方法的参数为cls
def plus_sum(cls):
cls.sum1 += 1
print(cls.sum1)
@staticmethod # 静态方法
def add(x, y):
# print(self.sum1) # 报错
print('这是静态方法!')
# 模板
student1 = Student('zhuxiaole', 23)
Student.plus_sum()
Student.add(1, 2)
print(student1.__dict__) # 保存着student1中的所有变量
print(Student.__dict__) # 保存着Student中的所有变量和方法
| false
|
5ff753d7ac3265f5e88dfa88ee11742f85499e8d
|
ArtZubkov/pyDev
|
/lab1.py
| 2,463
| 4.28125
| 4
|
'''
Программа, вычисляющая уравнение прямой, которая пересекает
заданную окружность и расстояние между точками пересечения
которой минимальны.
'''
#Ввод данных и инициализация
print('Уравнение окружности: (x-x0)^2+(y-y0)^2=r^2 ')
x0=float(input('Введите x0 для уравнения окружности: '))
y0=float(input('Введите y0 для уравнения окружности: '))
r=float(input('Введите радиус окружности: '))
n=int(input('Введите кол-во заданных точек: '))
X=[]
Y=[]
vmin=2*r+1
xmin=0
for i in range(n):
x=float(input('Введите координату x точки: '))
y=float(input('Введите координату y точки: '))
X.append(x)
Y.append(y)
#Вычисление k и b для каждой прямой
for i in range(n):
for j in range(n-1):
q=True
if X[i]!=X[j+1]:
k=(Y[j+1]-Y[i])/(X[j+1]-X[i])
b=-k*X[i]+Y[i]
d=(2*k*(b-y0)-2*x0)**2-4*(k**2+1)*((b-y0)**2+x0**2-r**2)
if X[i]==X[j+1]:
xq=X[i]
dy=4*(r**2-xq**2+2*x0*xq-x0**2)
yq1=(2*y0+dy**(1/2))/2
yq2=(2*y0-dy**(1/2))/2
v=((yq2-yq1)**2)**(1/2)
q=False
d=-1
#Проверка на пересечение прямой и окружности
if d>0:
x1=(-2*k*(b-y0)-2*x0-d**(1/2))/(2*(k**2+1))
x2=(-2*k*(b-y0)-2*x0+d**(1/2))/(2*(k**2+1))
y1=k*x1+b
y2=k*x2+b
v=((x2-x1)**2+(y2-y1)**2)**(1/2)
#Проверка на минимум расстояния между точками пересечения
if v<vmin:
if q:
vmin=v
kmin=k
bmin=b
else:
vmin=v
xmin=xq
if vmin==2*r+1:
print('Такой прямой не существует')
else:
if xmin==0:
print('k и b этой прямой соответсвенно равны: ','{:1g} {:1g}'.format(kmin,bmin))
else:
print('Уравнение прямой x=',xmin)
| false
|
4c28efd8124035ef404c5cdabf8279a25ffdead2
|
nasingfaund/Yeppp-Mirror
|
/codegen/common/Argument.py
| 1,926
| 4.4375
| 4
|
class Argument:
"""
Represents an argument to a function.
Used to generate declarations and default implementations
"""
def __init__(self, arg_type, name, is_pointer, is_const):
self.arg_type = arg_type
self.name = name
self.is_pointer = is_pointer
self.is_const = is_const
@property
def arg_type(self):
"""
This is the type of the argument with no qualifiers,
and if it is a pointer, it is the type pointed to
e.g const Yep8s *x -> Yep8s
"""
return self.arg_type
@property
def full_arg_type(self):
"""
This is the type of the argument including qualifiers
like const, pointers etc.
"""
ret = ""
if self.is_const:
ret += "const "
ret += self.arg_type + " "
if self.is_pointer:
ret += "*YEP_RESTRICT "
return ret
@property
def name(self):
return self.name
@property
def is_pointer(self):
return self.is_pointer
@property
def is_const(self):
return self.is_const
@property
def declaration(self):
"""
Returns the declaration needed in a C function
"""
ret = ""
if self.is_const:
ret += "const "
ret += self.arg_type + " "
if self.is_pointer:
ret += "*YEP_RESTRICT "
ret += self.name
return ret
@property
def size(self):
"""
Get the size of the argument, e.g Yep8s -> 8.
This is needed to generate the right alignment checks
"""
ret = ""
for c in self.arg_type:
if c.isdigit():
ret += c
return ret
@property
def data_type_letter(self):
"""
Returns s if signed, u if unsigned, f if floating-point
"""
return self.arg_type[-1]
| true
|
7432e574d515aadac24d93b6aa1568d3add65fc6
|
johnpospisil/LearningPython
|
/try_except.py
| 873
| 4.21875
| 4
|
# A Try-Except block can help prevent crashes by
# catching errors/exceptions
# types of exceptions: https://docs.python.org/3/library/exceptions.html
try:
num = int(input("Enter an integer: "))
print(num)
except ValueError as err:
print("Error: " + str(err))
else: # runs if there are no errors
print('No errors.')
finally: # runs always, whether there is an exception or not
print('Finally clause.')
# make your own exceptions classes
class ValueTooHighError(Exception):
pass
def test_value(x):
if x > 100:
raise ValueTooHighError('value is too high')
print(test_value(200))
# exceptions can be raised at will too
x = -5
if x < 0:
raise Exception('exception: x should be positive')
# assert statements - below, assert than x is gretaer than or equal to 0, raise an assert error if False
assert (x >= 0), 'x is negative'
| true
|
d78585044147f77090dc54494e1a3c24b36c5b37
|
johnpospisil/LearningPython
|
/while_loops.py
| 592
| 4.21875
| 4
|
# Use While Loops when you want to repeat an action until a certain condition is met
i = 1
while i <= 10:
print(i, end=' ')
i += 1
print("\nDone with loop")
# Guessing Game
secret_word = "forge"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("\nGUESSING GAME")
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter the secret word: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses. You lose.")
else:
print("You guessed it!")
| true
|
7a1bae5b1b9bedf34e6b2f2623024b98a6c25348
|
johnpospisil/LearningPython
|
/variables.py
| 420
| 4.3125
| 4
|
char_name = "John"
char_age = 50
is_male = True
print("There once was a man named " + char_name + ".")
print("He was " + str(char_age) + " years old.")
print("He liked the name " + char_name + ".")
print("But he did not like being " + str(char_age) + " years old.")
print("Is " + char_name + " male? " + str(is_male))
print("")
# Formatted Strings - easier to understand
print(f"Is {char_name} male? {str(is_male)}")
| false
|
c0520b4031b569268c84a81d38616af2b39b8d26
|
hansrajdas/random
|
/practice/loop_starting_in_linked_list.py
| 2,003
| 4.15625
| 4
|
class Node:
def __init__(self, k):
self.k = k
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_begin(self, k):
if self.head is None:
self.head = Node(k)
return
n = Node(k)
n.next = self.head
self.head = n
def traverse(self):
if self.head is None:
return
p = self.head
while p:
print(p.k, end=' ')
p = p.next
print()
def find_loop_begining(self):
slow = self.head
fast = self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
print('Loop is detected')
break
if fast is None:
return None
slow = self.head
while fast:
if slow is fast:
return slow
slow = slow.next
fast = fast.next
def main():
linked_list = LinkedList()
loop_start = Node(4)
linked_list.head = Node(1)
linked_list.head.next = Node(2)
linked_list.head.next.next = Node(3)
linked_list.head.next.next.next = loop_start
linked_list.head.next.next.next.next = Node(5)
linked_list.head.next.next.next.next.next = Node(6)
linked_list.head.next.next.next.next.next.next = Node(7)
linked_list.head.next.next.next.next.next.next.next = Node(8)
linked_list.head.next.next.next.next.next.next.next.next = Node(9)
linked_list.head.next.next.next.next.next.next.next.next.next = Node(10)
linked_list.head.next.next.next.next.next.next.next.next.next.next = Node(11)
linked_list.head.next.next.next.next.next.next.next.next.next.next.next = loop_start
loop_start = linked_list.find_loop_begining()
if loop_start:
print('Loop starting node: data[%d], id[%d]' % (
loop_start.k, id(loop_start)))
else:
print('Loop not found in linked list')
if __name__ == '__main__':
main()
| false
|
a9286b6aa0e4185915bebea4888bc79d7c27bc3b
|
yeasellllllllll/bioinfo-lecture-2021-07
|
/basic_python/210701_70_.py
| 763
| 4.25
| 4
|
#! /usr/bin/env python
print(list(range(5)))
# [0, 1, 2, 3, 4]
print('hello'[::-1])
# olleh
print('0123456789'[0:5:1])
#위의 숫자 위치 찾는 것은 원하는 위치를 설정할수없다.
print(list(range(2, 5, 1)))
# [2, 3, 4] 2~5사이의 1차이나게끔 올려서 리스트 보여줘
totalSum = 0
for i in range(3):
totalSum += i
print(i)
print('totalSum:', totalSum)
'''
0
1
2
totalSum: 3
'''
for i in range(3):
if i == 2:
print(i)
else:
pass
print('totalSum:', totalSum)
totalSum = 0
for i in range(3):
if i == 2:
print(i)
else:
continue
print('totalSum:', totalSum)
totalSum = 0
for i in range(3):
if i == 2:
print(i)
else:
break
print('totalSum:', totalSum)
| false
|
9fc9df1a3b6028dffaae5efdfacc2b5577929ce2
|
lihaoyang411/My-projects
|
/Encryption-Bros-master/Main.py
| 1,947
| 4.15625
| 4
|
import sys
typeChosen = 0
def choose(choice):
while True:
if choice.find(".") >= 0 or choice.find("-") >= 0:
choice = input("You didn't type in a positive integer. Please try again: ")
else:
try:
choice = int(choice)
dummyNum = 2/choice
if choice == 1 or choice == 2 or choice == 3:
break
else:
choice = input("You didn't type a valid choice. Please try again: ")
except ValueError:
choice = input("You didn't type in a positive integer. Please try again: ")
except ArithmeticError:
choice = input("You didn't type in a positive integer. Please try again: ")
print("")
return choice
def main():
morseCount = 0
pigCount = 0
imageCount = 0
while(1):
choice = input("What would you like to do? Please select an option below:\n1. Edit a text file\n2. Edit an image\n3. Exit Program\n\nEnter your choice: ")
choice = choose(choice)
if choice == 1:
choice = input("Would you like to encrypt a text file into Morse/Vig Cypher or Pig Latin/Hashing?\n1. Morse/Vig Cypher\n2. Pig Latin/Hashing\n\nEnter your choice: ")
choice = choose(choice)
if choice == 1:
if morseCount == 0:
import morse
morseCount += 1
else:
morse.main()
else:
if pigCount == 0:
import piglatin
pigCount += 1
else:
piglatin.main()
elif choice == 2:
if imageCount == 0:
import EncryptImage
imageCount += 1
else:
EncryptImage.main()
else:
print("Exiting program...\n")
sys.exit()
main()
| true
|
23334bd9745a107a337460c8cd4a2b8dcfa6a52d
|
Shiliangwu/python_work
|
/hello_world.py
| 1,037
| 4.21875
| 4
|
# this is comment text
# string operation examples
message="hello python world"
print(message)
message="hello python crash course world!"
print(message)
message='this is a string'
message2="this is also a string"
print(message)
print(message2)
longString='I told my friend, "Python is my favorite language!"'
print(longString)
name="ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
print(name.lower().upper())
fullString=message2+" AND "+longString
print(fullString)
print("hello,"+fullString.title()+"!")
# tab
print("Python")
print("\tPython")
print("Language:\n\tPython\n\t\tJavaScripy")
# delete extra spaces.
favorite_language=' Python with blanks '
print(favorite_language)
print(favorite_language.rstrip())
print(favorite_language.lstrip())
print(favorite_language)
message = "One of Python's strengths is its diverse community."
print(message)
message = 'One of Python"s strengths is its diverse community.'
print(message)
def yourchoice():
print("my choice")
yourchoice()
| true
|
bde6d52ed8e8578510e2e3ed47ca03fd13172c33
|
anindo78/Udacity_Python
|
/Lesson 3 Q2.py
| 698
| 4.15625
| 4
|
# Define a procedure, greatest,
# that takes as input a list
# of positive numbers, and
# returns the greatest number
# in that list. If the input
# list is empty, the output
# should be 0.
def greatest(list_of_numbers):
if len(list_of_numbers) == 0:
return 0
else:
maximum = list_of_numbers[0]
if len(list_of_numbers) > 0:
for i in list_of_numbers:
maximum = max(maximum, i)
return maximum
print greatest([4,23,1])
#>>> 23
print greatest([])
#>>> 0
#More elegant solution
def greatest(list_of_numbers):
maximum = 0
for i in list_of_numbers:
if i > maximum:
maximum = i
return maximum
| true
|
0fc6e1ae13fecbc47013ddecc2b29ef71f13b8c6
|
hamsemare/sqlpractice
|
/291projectReview.py
| 2,985
| 4.28125
| 4
|
import sqlite3
connection = None
cursor = None
name= None
# Connect to the database
def connect(path):
global connection, cursor
connection=sqlite3.connect(path)
cursor=connection.cursor()
def quit():
exit(0)
def findName():
global name
studentName= input("Enter Student Name: ")
if(studentName=="q" or studentName=="Q"):
quit()
cursor.execute('''
select *
from students
where studentName==?
''', (studentName,))
num=cursor.fetchall()
for i in num:
j=''.join(i)
name= studentName
if(num==[]):
return True
return False
def login():
print("\n"*10)
print("LOGIN")
print("--"*5)
print("\n")
while True:
check= findName()
if(check):
print("Name does not Exist!!!")
l=input("Do you want to Create an Account, enter y if Yes: ")
if(l=="q" or l=="Q"):
return
elif(l=="y" or l=="Y"):
create()
return
else:
print("\n")
else:
# Login
print("Successful Login !!!")
return
def create():
global connection, cursor
print("\n"*10)
print("CREATE AN ACCOUNT")
print("--"*10)
print("\n")
while True:
check= findName()
if(check):
# Good create an account
cursor.execute('''
insert into students
values (?)''', (name,))
connection.commit()
print("Account Created!!!!!")
login()
return
else:
print("Name is Taken!!!")
l=input("Do you want to login, enter y if Yes: ")
if(l=="q" or l=="Q"):
return
elif(l=="y" or l=="Y"):
login()
return
else:
print("\n")
def vCourses():
global connection, cursor, name
print("\n"*10)
print("View Courses")
print("--"*10)
print("\n")
cursor.execute('''
select courseName
from Courses
where studentName=(?)''', (name,))
aCourse=[]
courses= cursor.fetchall()
for i in courses:
course=''.join(i)
aCourse.append(course)
print("COURSES")
print("--"*10)
if(len(aCourse)==0):
print("NONE")
else:
for i,j in enumerate(aCourse):
num=i+1
print("Course", num, ": "+ j)
print("\n")
def aCourses():
global connection, cursor, name
print("\n"*10)
print("Add Courses")
print("--"*10)
print("\n")
courseName= input("Enter Course Name: ")
if(courseName=="q" or courseName=="Q"):
quit()
else:
cursor.execute('''
insert into courses
values (?,?,?)''', (courseName, 3, name )
)
connection.commit()
# Main client/User interface
def main():
global connection, cursor
path= "./291database.db"
connect(path)
print("Welcome:")
print("--"*5)
print("\n")
print("To quit enter q. ")
log= input("To Login enter l, or to Create an Account enter anything else: ")
# Validate login or create account info
if(log=="q" or log=="Q"):
quit()
elif(log=="l" or log=="L"):
login()
else:
create()
# Courses
while True:
print("To quit, enter 'q' or 'Q'")
c= input("To view courses enter 'v' , enter anything else to add courses: ")
if(c=="Q" or c=="q"):
quit()
if(c=="v" or c=="V"):
vCourses()
else:
aCourses()
main()
| true
|
3f30bad898e7fbaa90495f3f609f6f6c3d43ba78
|
HunterOreair/Portflio
|
/RollDie.py
| 942
| 4.1875
| 4
|
#A simple python program that rolls die and returns the number that has been rolled. Made by Hunter Oreair.
from random import randint # imports randint. duh.
min = 1 #sets the minimum value on the dice that you can roll
max = 6 #sets the maximum value
def die(): # Creates a method called die
rollDie = randint(min, max) # sets what number you rolled
print("You rolled a", rollDie) # prints the number you rolled
def rollAgain():
again = True
while again: #while 'again' is True, do the following:
die() # calls the die method.
print("Would you like to roll again? y/n") #asks if you would like to roll again.
ans = input() #takes your input
if ans == "y": #if your input equals 'y' then run the while loop again
again = True
else: #anything will end the program
again = False
rollAgain() # calls rollAgain method, running the program.
| true
|
464d00436d9c90def53af9f7b1717e16f1031b23
|
JerryCodes-dev/hacktoberfest
|
/1st Assignment.py
| 884
| 4.15625
| 4
|
# NAME : YUSUF JERRY MUSAGA
# MATRIC NUMBER : BHU/19/04/05/0056
# program to find the sum of numbers between 1-100 in step 2
for a in range(1,100,2):
print(a)
num = 1
while num < 100:
print(num)
num += 2
# program to find all even numbers between 1-100
for b in range(2,100,2):
print (b)
numb = 2
while numb < 100:
print(numb)
numb += 2
# program to find the solution to this equation 2x + 3y + 1
x = float(input('Enter a number for x:'))
y = float(input('Enter a number for y:'))
c = 2*(x) + 3*(y) + 1
print(c)
def equation(x,y):
c = 2*(x) + 3*(y) + 1
return c
# print in any value for x and y
print(equation(2,3))
# average age of students in class
age = float(input('Enter Age: '))
totalAge = age
sum = 0
while age > 0:
sum += age
age -= 1
print('Sum of the ages:', sum)
averageAge = sum / totalAge
print('Average age is: ' , averageAge)
| true
|
5cc890b202f98bb88b5d614c43745cf2b427b0e4
|
CoffeePlatypus/Python
|
/Class/class09/exercise1.py
| 893
| 4.6875
| 5
|
#
# Code example demonstrating list comprehensions
#
# author: David Mathias
#
from os import listdir
from random import randint
from math import sqrt
print
# create a list of temps in deg F from list of temps in deg C
# first we create a list of temps in deg C
print('Create a list of deg F from a list of deg C temperatures:')
print
dC = [-40, 0, 10, 20, 30, 40, 100]
dF = [1.8 * c + 32 for c in dC]
print('dC: {}'.format(dC))
print('dF: {}'.format(dF))
print
# in this version, we use a list comprehension to create the
# list of degrees C -- a comprehension inside a comprehension
print('Create a list of deg F from a list of degC temperatures.')
print('deg C temps generated randomly by list comprehenstion')
print('within the conversion list comprehension:')
print
dF = [int(1.8 * c + 32) for c in [randint(0, 100) for i in range(8)]]
print('deg F for random deg C: {}'.format(dF))
print
| true
|
7185ccd8e4a6913a24efb58ee17692112564b4d7
|
CoffeePlatypus/Python
|
/Class/class03/variables.py
| 804
| 4.125
| 4
|
#
# Various examples related to the use of variables.
#
# author: David Mathias
#
x = 20
print type(x)
print
y = 20.0
print type(y)
print
s = "a"
print type(s)
print
c = 'a'
print type(c)
print
b = True
print type(b)
print
print('8/11 = {}'.format(8/11))
print
print('8.0/11 = {}'.format(8.0/11))
print
print('float(8)/11 = {}'.format(float(8)/11))
print
s = '12'
print('int(s) = '.format(int(s)))
print('int(s) + 10 = {}'.format(int(s) + 10))
# the next line would give an error
# print('s + 10 = {}'.format(s+10))
print
pi = 3.14159
print('int(pi) = {}'.format(int(pi)))
print
s1 = 'This is '
s2 = 'a test.'
print 's1 = ' + s1
print 's2 = ' + s2
print('s1 + s2 = {}'.format(s1 + s2))
print
s3 = s1 + s2
print('s3 = s1 + s2. s3 = ' + s3)
print
s = 'Spam '
print('s = Spam. s*4 = ' + s*4)
print
| true
|
884f3d8864db1f221e5ff8b3f06fc87a20fc6882
|
shabazaktar/Excellence-Test
|
/Question2.py
| 304
| 4.21875
| 4
|
# 2 Question
def maxValue(d2):
key = max(d2, key=d2.get)
d3={key : d2[key]}
return d3
d1= {
"1" : "Shahbaz",
"2" : "Kamran",
"3" : "Tayyab"
}
d2= {
"1" : 50,
"2" : 60,
"3" :70
}
print(maxValue(d2))
| false
|
3e8ea3989cf216ab53e9a493b07ea974dbe17091
|
rp927/Portfolio
|
/Python Scripts/string_finder.py
| 585
| 4.125
| 4
|
'''
In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left.
'''
def count_substring(string, sub_string):
ls = []
o = 0
count = 0
l = len(sub_string)
sub_ls = [sub_string]
while l <= len(string):
ls.append(string[o:l])
o += 1
l += 1
for _ in ls:
if _ in sub_ls:
count += 1
return count
'''
Sample input:
ABCDCDC
CDC
Sample output:
2
'''
| true
|
0fa7471aa14fec407c4b491a338ffaf70f530183
|
lherrada/LeetCode
|
/stacks/problem1.py
| 741
| 4.28125
| 4
|
# Check for balanced parentheses in Python
# Given an expression string, write a python program to find whether a given string has balanced parentheses or not.
#
# Examples:
#
# Input : {[]{()}}
# Output : Balanced
#
# Input : [{}{}(]
# Output : Unbalanced
from stack import Stack
H = {'{': '}', '[': ']', '(': ')'}
def checkifbalanced(myinput):
stack = Stack()
for i in myinput:
if i in H.keys():
stack.push(i)
else:
if len(stack) > 0 and H[stack.pop()] == i:
continue
else:
return False
return False if len(stack) > 0 else True
myinput = '([[[{}]]]('
if checkifbalanced(myinput):
print("Balanced")
else:
print("Unbalanced")
| true
|
4c4cbbf75cd598226f55a08b967597dde477e7a3
|
odemeniuk/twitch-challenges
|
/interview/test_palindrome.py
| 336
| 4.40625
| 4
|
# write a function that tells us if a string is a palindrome
def is_palindrome(string):
""" Compare original string with its reverse."""
# [::-1] reverses a string
reverse = string[::-1]
return string == reverse
def test_is_palindrome():
assert is_palindrome('banana') is False
assert is_palindrome('foof')
| true
|
d8f9c69874ca0ab5da4dac704f88fedb77b1b30d
|
dragonRath/PythonBasics
|
/stringformatting.py
| 2,162
| 4.53125
| 5
|
#The following will illustrate the basic string formatting techniques used in python
age = 24
#print("My age is " + str(age) + " years\n")
print("My age is {0} years".format(age)) #{} Replacement brackets
print("There are {0} days in {1}, {2}, {3}, {4}, {5}, {6} and {7}".format(31, "January", "March", "May", "July", "August", "October", "December"))
print("""January: {2}
Feburary: {0}
March: {2}
April: {1}
May: {2}
June: {1}
July: {2}
August: {2}
Septemeber: {1}
October: {2}
November: {1}
December: {2}""". format(28, 30, 31))
print("\nGrael Knight said: 'Hello'" + " Avi")
print("\nMy age is %d years" %age)
print("\nMy age is %d %s, %d %s" %(age, "years", 6, "months")) #%d is int, %s is string; this replacement stands for all the variables
for i in range(1, 12): # ** means to the power of. %d = integer, %s = String, %f = Float
print("Number %2d squared is %4d and cubed is %4d" %(i, i ** 2, i ** 3)) #The 2 or 4 before the %d is for allocating space. String formating.
print ("Pi is approximately %12f" %(22 / 7)) #Default float precision
print ("Pi is approximately %12.50f" %(22 / 7)) #50 decimal point precision
print ("Pi is approximately %0.50f" %(22 / 7)) #50 decimal point precision without giving extra space to the float.
for i in range(1, 12): #In {:}, the first no. is the replacement field whereas the second one is the width of the field. Don't put space between the colons. Gives an error.
print("Number {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i ** 3)) #Don't put space between the colons. Gives an error.
for i in range(1, 12): #The < symbol justifies the left hand side, ie, it starts from the left instead of allocation from the right.
print("Number {0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3))
print ("Pi is approximately {0:12.50}".format(22 / 7)) #Using replacement fields syntax
print("January: {2}, Feburary: {0}, March: {2}, April: {1}, May: {2}, June: {1}, July: {2}, August: {2}, Septemeber: {1}, October: {2}, November: {1}, December: {2}".format(28, 30, 31))
for i in range(1, 12):
print("No. {} squared is {} and cubed is {:4}".format(i, i ** 2, i ** 3))
| true
|
c603d6ab0955cfc0100daa3a9c4c37cceb58876c
|
loweryk/CTI110
|
/p3Lab2a_lowerykasey.py
| 1,026
| 4.46875
| 4
|
#Using Turtle in Python
#CTI-110 P3LAB2a_LoweryKasey
import turtle #Allows us to use turtles
wn = turtle.Screen() #Creates a playground for turtles
alex = turtle.Turtle() #Creatles a turtle, assign to alex
#commands from here to the last line can be replaced
alex.hideturtle() #Hides the turtle in icon
#For the loop that iterates 4 times to draws a square
#Tell alex to draw a square
alex.right(90) #Tell alex to move right by 90 units
alex.forward(50) #Tell alex to move forward by 50 units
alex.left(90) #Tell alex to move left by 90 units
alex.forward(100) #Tell alex to move forward by 100 units
alex.left(90)
alex.forward(100)
alex.left(90)
alex.forward(100)
alex.left(90)
alex.forward(50)
alex.forward(80) #Tells alex to draw a specific triangle
alex.left(120)
alex.forward(80)
alex.left(120)
alex.forward(80)
alex.left(120)
#ends commands
wn.mainloop() #wait for user to close window
| true
|
676b4eb2f036c5379c5367528429cd124facc5b0
|
CBGO2/Mision-04
|
/Triangulos.py
| 1,086
| 4.25
| 4
|
# Carlos Badillo García
# Programa que lee el valor de cada uno de los lados de un triangulo e indica el tipo de triángulo que es
def indicarTipoTriangulo(lado1, lado2, lado3): #Indicar que tipo de triángulo es dependiendo el valor de sus lados
if lado1 == lado2 == lado3:
return "El triángulo es equilátero"
elif lado1 == lado2 and lado1 != lado3 or lado1 == lado3 and lado1 != lado2 or lado2 == lado3 and lado2 != lado1:
return "El triángulo es isósceles"
elif lado1**2 == lado2**2 + lado3**2 or lado2**2 == lado1**2 + lado3**2 or lado3**2 == lado1**2 + lado2**2:
return "El triángulo es rectángulo"
else:
return "Estos lados no corresponden a un triángulo"
def main(): # El usuario introduc el valor de lado 1, lado 2 y lado 3, luego imprime que tipo de triángulo
lado1 = int(input("Teclea valor del lado1: "))
lado2 = int(input("Teclea valor del lado2: "))
lado3 = int(input("Teclea valor del lado3: "))
tipoTriangulo = indicarTipoTriangulo(lado1, lado2, lado3)
print (tipoTriangulo)
main()
| false
|
2ea9f7ee2ecaf30a0678c566a6492d3c2f75a290
|
DrOuissem/useful_programs
|
/code_python2/chapter1_oop/4_video_abstract_class/video4_AbstractClass.py
| 1,054
| 4.15625
| 4
|
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self,name,age):
self.name = name
self.age = age
def print_name(self):
print("name: ",self.name)
def print_age(self):
print("age: ",self.age)
@abstractmethod
def print_info(self):
pass
class Student(Person):
def __init__(self,name,age,id):
Person.__init__(self,name,age)
self.id=id
def print_id(self):
print("id: ",self.id)
def print_info(self):
print("Student:\n________")
Person.print_info(self)
self.print_id()
class Teacher(Person):
def __init__(self,name,age,salary):
super().__init__(name,age)
self.salary=salary
def print_salary(self):
print("salary: ",self.salary)
def print_info(self):
print("Teacher:\n________")
Person.print_info(self)
super().print_info()
self.print_salary()
#P=Person("Ahmad",20)
S=Student("Ahmad",20,1234)
T=Teacher("Omer",35,20.000)
S.print_info()
T.print_info()
| false
|
f643f39546ae35916bf1147df22e1bdfddfd4972
|
sheriaravind/Python-ICP4
|
/Source/Code/Num-Py -CP4.py
| 359
| 4.28125
| 4
|
import numpy as np
no=np.random.randint(0,1000,(10,10)) # Creating the array of 10*10 size with random number using random.randint method
print(no)
min,max = no.min(axis=1),no.max(axis=1) # Finding the minimum and maximum in each row using min and max methods
print("Minimum elements of 10 size Array is",min)
print("Maximum elements of 10 size Array is",max)
| true
|
3fb3edce524850dfdc618bc407b47c3f57d89978
|
TENorbert/Python_Learning
|
/learn_python.py
| 637
| 4.125
| 4
|
#!/usr/bin/python
"""
python
"""
'''
first_name = input("Enter a ur first name: ")
last_name = input("Enter your last name: ")
initial = input("Enter your initial: ")
person = initial + " " + first_name + " " + last_name
print("Ur name is %s" %person)
print("Ur name is %s%s%s" %initial %first_name %last_name)
'''
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
'(or enter Nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] ##Append indirectly using list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
| true
|
2c23e549b3f04c9d776a698348039ef1e8eba4a3
|
diegoasanch/Fundamentos-de-Progra-2019
|
/TP3 Estructura alternativa/TP3.10 Clasificador de triangulos.py
| 1,441
| 4.28125
| 4
|
#Desarrollar un programa para leer las longitudes de los tres lados de un triángulo
# L1, L2, L3 y determinar qué tipo de triángulo es según la siguiente clasificación:
# · Si A >= B + C no se trata de un triángulo.
# · Si A² = B² + C² se trata de un triángulo rectángulo.
# · Si A² > B² + C² se trata de un triángulo obtusángulo.
# · Si A² < B² + C² se trata de un triángulo acutángulo.
# Tener en cuenta que A denota el mayor de los lados L1, L2 y L3, mientras que B
# y C corresponden a los dos lados restantes.
op=1
print()
print('Clasificador de triangulos')
while op==1:
print()
L1=float(input('Ingrese el primer lado del triangulo: '))
L2=float(input('Ingrese el segundo lado del triangulo: '))
L3=float(input('Ingrese el tercer lado del triangulo: '))
if L1>L2 and L1>L3:
A=L1
B=L2
C=L3
elif L1<L2 and L2>L3:
A=L2
B=L1
C=L3
else: #L1<L3and L2<L3:
A=L3
B=L1
C=L2
print()
print('El lado A=',A,'el lado B=',B,'y el lado C=',C)
print()
if A>=B+C:
print('Los datos ingresados no coinciden con un triangulo :(')
elif A**2==B**2+C**2:
print('El triangulo ingresado es uno Rectangulo')
elif A**2>B**2+C**2:
print('Es un triangulo Obtusangulo')
else:
print('Es un triangulo acutangulo')
op=int(input('1 O 0?:'))
while op==0:
print('Adios')
op=2
| false
|
2bc83bf2c084a7baba788f047d97427d57d7eb3c
|
diegoasanch/Fundamentos-de-Progra-2019
|
/TP5 Funciones/TP5.12 Extraer un digito de un entero.py
| 1,705
| 4.15625
| 4
|
# Extraer un dígito de un número entero. La función recibe como parámetros dos
# números enteros, uno será del que se extraiga el dígito y el otro indica qué cifra
# se desea obtener. La cifra de la derecha se considera la número 0. Retornar el
# valor -1 si no existe el dígito solicitado. Ejemplo: extraerdigito(12345,1) devuelve 4,
# y extraerdigito(12345,8) devuelve -1.
#funcion extraer digito
def extraerdigito(entero,extraer,longitud):
if extraer>(longitud-1): #si se quiere sacar un numero en una posicion mayor a la longitud
digito = -1 #del entero, deuelve -1
else:
cont=0
while cont <= extraer:
digito = entero % 10 #se extrae uno por uno el ultimo digito, hasta llegar al deseado
entero = entero // 10 #y se le quita el ultimo digito al entero para repetir el ciclo
cont = cont + 1
return digito
#funcion determina longitud del numero
def longitudentero(entero):
cont=0
while entero>0:
cont = cont + 1
entero = entero // 10
return cont
#verificador de positividad de un numero
def verifnum(tipo):
print('>>> Ingrese',tipo,': ',end='')
n=int(input())
while n<0:
print('\nNo ingreso un numero valido!!!')
print('>>> Ingrese',tipo,': ',end='')
n=int(input())
return n
#programa principal
print('Ingrese un numero entero y extraiga el numero que este en la posicion del segundo')
print('numero ingresado, contando desde 0, de derecha a izquierda')
A=verifnum('un numero') #primer numero
B=verifnum('la posicion a extraer') #digito a extraer
largo=longitudentero(A)
extraido=extraerdigito(A,B,largo)
print(extraido)
| false
|
4d2e57dbc334cb1ba9f22efbdbac4fd5f38d95a8
|
diegoasanch/Fundamentos-de-Progra-2019
|
/TP4 Estructura iterativa/TP4.2 Imprimir primer y ultimo valor.py
| 504
| 4.15625
| 4
|
#Realizar un programa para ingresar desde el teclado un conjunto de números. Al
#finalizar mostrar por pantalla el primer y último elemento ingresado. Finalizar la
#lectura con el valor -1.
print('Ingrese numeros, para finalizar ingrese -1')
print()
n=int(input('Ingrese un valor: '))
if n!=-1:
primero=n
while n!=-1:
ultimo=n
n=int(input('Ingrese un valor: '))
print('El primer valor ingresado es',primero,'y el ultimo',ultimo)
else:
print('Ningun valor fue ingresado')
| false
|
25b1a46a621054c7d04da0e02ce0acc6181c46eb
|
keithrpotempa/python-book1
|
/sets/cars.py
| 1,539
| 4.21875
| 4
|
# Create an empty set named showroom.
showroom = set()
# Add four of your favorite car model names to the set.
showroom.update(["Car1", "Car2", "Car3", "Car4"])
# Print the length of your set.
print("Showroom length", len(showroom))
# Pick one of the items in your show room and add it to the set again.
showroom.update(["Car1"])
# Print your showroom. Notice how there's still only one instance of that model in there.
print(showroom)
# Using update(), add two more car models to your showroom with another set.
showroom.update({"Car5", "Car6"})
print(showroom)
# You've sold one of your cars. Remove it from the set with the discard() method.
showroom.discard("Car1")
print(showroom)
# Now create another set of cars in a variable junkyard. Someone who owns a junkyard full of old cars has approached you about buying the entire inventory. In the new set, add some different cars, but also add a few that are the same as in the showroom set.
junkyard = set()
junkyard.update(["Car2", "Junk1", "Junk2", "Junk3"])
print(junkyard)
# Use the intersection method to see which cars exist in both the showroom and that junkyard.
print("Intersection", showroom.intersection(junkyard))
# Now you're ready to buy the cars in the junkyard. Use the union method to combine the junkyard into your showroom.
new_showroom = showroom.union(junkyard)
print(new_showroom)
# Use the discard() method to remove any cars that you acquired from the junkyard that you do not want in your showroom.
new_showroom.discard("Junk1")
print(new_showroom)
| true
|
d4a524ea19b19afd811e32a9f0c58916b4cabb8f
|
BrutalCoding/INFDEV01-1_0912652
|
/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b/DEV_01_1___Assignment_4___Exercise_1.b.py
| 227
| 4.25
| 4
|
celcius = -273.15 #This is the default value to trigger the while loop here below
while celcius <= -273.15:
celcius = input("Enter Celcius to convert it to Kelvin:\n")
print "Celcius:", celcius, "Kelvin = ", celcius+273.15
| true
|
b0985c06edbb8bc0ff8d86e3f7b5772d204954a3
|
olivepeace/ASSIGNMENT-TO-DETERMINE-DAYOF-BIRTH
|
/ASSIGNMENT TO DETERMINE DAY OF BIRTH.py
| 1,960
| 4.375
| 4
|
"""
NAME: NABUUMA OLIVIA PEACE
COURSE:BSC BIOMEDICAL ENGINEERING
REG NO: 16/U/8238/PS
"""
import calendar
print("This Program is intended to determine the exact day of the week you were born")
print(".....................................................")
day = month = year = None
#Next code ensures that only and only integers input
while(day == None):
try:
day = int(input("PLEASE TYPE IN YOUR DAY OF YOUR BIRTH:"))
while(day not in range(1, 32)):
print("this is not a day")
day = int(input("PLEASE TYPE IN YOUR DAY OF BIRTH:"))
except:
print("Please type in numbers only")
print()
while(month == None):
try:
month = int(input("PLEASE TYPE IN YOUR MONTH OF BIRTH:"))
while(month not in range(1, 13)):
print("Mr or Lady, months move from Jan, To December. thats twelve, not %d or whatever you've input" % month)
month = int(input("PLEASE TYPE IN YOUR MONTH OF BIRTH AGAIN: "))
except:
print("Please type in numbers only")
print()
while(year == None):
try:
year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH: "))
while(year not in range(1000, 2500)):
if(year >= 2500):
print("No offense but by %d, you'll be dead, ALREADY. So please, type in " % year)
year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH "))
if(year < 1000):
print("By then you were not born. Unless you are immortal")
year = int(input("PLEASE TYPE IN YOUR YEAR OF BIRTH: "))
except:
print("Please type in numbers only")
print()
#this outputs the day in form of numbers from 0 - 6
date = calendar.weekday(year, month, day)
exact = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print("You were born on ", exact[date])
input("press Enter to exit")
| true
|
c08a6b31684f0d20fd1c7ef9b64e8db0168e7ff5
|
NDjust/python_data_structure
|
/sort_search/search.py
| 1,413
| 4.21875
| 4
|
from random import randint
import time
def linear_search(L, x):
'''
using linear search algorithms
time complexity
-> O(n)
parmas:
L: list
x: target num
'''
for i in range(len(L)):
if x == L[i]:
return i
return -1
def binary_search(L, x):
'''
using binary search algorithms
time complexity
-> O(log n)
parmas:
L: list
x: target num
'''
lower = 0
upper = len(L) - 1
idx = -1
while lower <= upper:
middle = (lower + upper) // 2
if L[middle] == x:
return middle
if L[middle] < x:
lower = middle + 1
else:
upper = middle - 1
return idx
if __name__ == "__main__":
num = int(input("Enter a number: "))
target = int(input("Enter the number of targets: "))
num_list = sorted([randint(0, num) for i in range(num)]) # create Random numbers list.
target_list = [randint(0, num) for i in range(target)] # create Random target num list.
start_time = time.time()
result = [binary_search(num_list, target) for target in target_list]
print("Binary search found target number time: {}".format(time.time() -start_time))
start_time = time.time()
result = [linear_search(num_list, target) for target in target_list]
print("linear search found target number time: {}".format(time.time() -start_time))
| false
|
afad2695aa4dff1ce100cfaf65cbdcca9b6c37d4
|
RaazeshP96/Python_assignment1
|
/function12.py
| 305
| 4.3125
| 4
|
'''
Write a Python program to create a function that takes one argument, and
that argument will be multiplied with an unknown given number.
'''
def multi(n):
a = int(input("Enter the number:"))
return f"The required result is { n * a }"
n = int(input("Enter the integer:"))
print(multi(n))
| true
|
8c225b5b0ac4648cfa8e555b9aaf74312d89484f
|
RaazeshP96/Python_assignment1
|
/function16.py
| 237
| 4.25
| 4
|
'''
Write a Python program to square and cube every number in a given list of
integers using Lambda.
'''
sq=lambda x:x*x
cub=lambda x:x*x*x
n=int(input("Enter the integer:"))
print(f"Square -> {sq(n)}")
print(f"Cube -> {cub(n)}")
| true
|
0ac4c15f04bf3e49e1ca36ac3bb67e81ed9a0200
|
Rogersamacedo/calc
|
/calc.py
| 1,279
| 4.28125
| 4
|
def calculadora():
print("Qual operação deseja efetuar? : ")
print( "Para soma digite 1")
print( "Para subtração digite 2")
print( "Para divisão digite 3")
print( "Para mutiplicação digite 4")
print( "Para potencia digite 5")
print( "Para porcentagem digite 6")
print( "Para raiz quadrada digite 7")
#operacao = 7
#num = float(input("Inofrme o numero que vc quer saber a raiz quadrada: "))
#print(float(num) ** 0.5)
operacao = int(input("Digite a sua opção: "))
while operacao < 1 or operacao > 7:
print("DIGITE A OPÇÃO ENTRE 1 E 7")
break;
num1 = float(input("Informe o primeiro numero: "))
num2 = float(input("Informe o segundo numero: "))
if operacao == 1 :
print(num1 + num2)
elif operacao == 2 :
print(num1 - num2)
elif operacao == 3 :
print(num1 / num2)
elif operacao == 4 :
print(num1 * num2)
elif operacao == 5 :
print(num1 ** num2)
elif operacao == 6 :
p = (num1/100)
print(p, "%", "de", num2, "é", (num1/100) * num2)
elif operacao == 7:
num = float(input("Inofrme o numero que vc quer saber a raiz quadrada: "))
print(float(num) ** 0.5)
calculadora()
| false
|
d7a0eaf524bd36baf8ef17e6aab4147e32e61e9b
|
DeepuDevadas97/-t2021-2-1
|
/Problem-1.py
| 1,046
| 4.21875
| 4
|
class Calculator():
def __init__(self,a,b):
self.a=a
self.b=b
def addition(self):
return self.a+self.b
def subtraction(self):
return self.a-self.b
def multiplication(self):
return self.a*self.b
def division(self):
return self.a/self.b
repeat = 1
while repeat != 0:
print("_____________________CALCULATOR_______________________________")
a=float(input("Enter 1st number : "))
b=float(input("Enter 2nd number : "))
obj=Calculator(a,b)
operator = input("Enter type of operation [+] [-] [*] [/] : ")
if operator == "+":
print("Result : ",obj.addition())
elif operator == "-":
print("Result : ",obj.subtraction())
elif operator == "*":
print("Result : ",obj.multiplication())
elif operator == "/":
print("Result : ",obj.division())
else:
print("Invalid Operator !!")
| true
|
22b5e71d891a902473213c464125bea0ca1526c6
|
kelpasa/Code_Wars_Python
|
/5 кю/RGB To Hex Conversion.py
| 971
| 4.21875
| 4
|
'''
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3'''
def rgb(*color):
arr = []
for i in color:
if i < 0:
arr.append(hex(0).replace('0x',''))
elif i > 255:
arr.append(hex(255).replace('0x',''))
else:
arr.append(hex(i).replace('0x',''))
res = []
for i in arr:
if len(i) == 1:
res.append('0'+i)
else:
res.append(i)
return ''.join(res).upper()
| true
|
efe2f3dd96140dfb7ca59d5a5571e6c031491273
|
kelpasa/Code_Wars_Python
|
/5 кю/Scramblies.py
| 430
| 4.15625
| 4
|
'''
Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included.
Performance needs to be considered
'''
def scramble(s1,s2):
for letter in set(s2):
if s1.count(letter) < s2.count(letter):
return False
return True
| true
|
4d26fc6d60a59ad20aec5456cf32bc6588018139
|
kelpasa/Code_Wars_Python
|
/6 кю/String transformer.py
| 489
| 4.40625
| 4
|
'''
Given a string, return a new string that has transformed based on the input:
Change case of every character, ie. lower case to upper case, upper case to lower case.
Reverse the order of words from the input.
Note: You will have to handle multiple spaces, and leading/trailing spaces.
For example:
"Example Input" ==> "iNPUT eXAMPLE"
You may assume the input only contain English alphabet and spaces.
'''
def string_transformer(s):
return ' '.join(s.swapcase().split(' ')[::-1])
| true
|
a62713c957216d00edf4dbb925e5f561f94c4cf2
|
kelpasa/Code_Wars_Python
|
/6 кю/Sort sentence pseudo-alphabetically.py
| 1,238
| 4.3125
| 4
|
'''
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it:
All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted in ascending order.
All words that begin with an upper case letter should come after that, and should be sorted in descending order.
If a word appears multiple times in the sentence, it should be returned multiple times in the sorted sentence. Any punctuation must be discarded.
Example
For example, given the input string "Land of the Old Thirteen! Massachusetts land! land of Vermont and Connecticut!", your method should return "and land land of of the Vermont Thirteen Old Massachusetts Land Connecticut". Lower case letters are sorted a -> l -> l -> o -> o -> t and upper case letters are sorted V -> T -> O -> M -> L -> C.'''
import re
def pseudo_sort(st):
st, upper, lower = re.sub(r'[^ \w]','',st).split(), [], []
for i in st:
if i[0].islower():
lower.append(i)
else:
upper.append(i)
return ' '.join(sorted(lower) + sorted(upper)[::-1])
| true
|
4804ed7aa18e361bf99084a6d1f2390b18d8bb8a
|
kelpasa/Code_Wars_Python
|
/5 кю/Emirps.py
| 1,045
| 4.3125
| 4
|
'''
If you reverse the word "emirp" you will have the word "prime". That idea is related with the purpose of this kata: we should select all the primes that when reversed are a different prime (so palindromic primes should be discarded).
For example: 13, 17 are prime numbers and the reversed respectively are 31, 71 which are also primes, so 13 and 17 are "emirps". But primes 757, 787, 797 are palindromic primes, meaning that the reversed number is the same as the original, so they are not considered as "emirps" and should be discarded.
'''
from math import log, ceil
def makeSieveEmirp(n):
sieve, setPrimes = [0]*n, set()
for i in range(2, n):
if not sieve[i]:
setPrimes.add(i)
for j in range(i**2, n, i): sieve[j] = 1
return { n for n in setPrimes if n != int(str(n)[::-1]) and int(str(n)[::-1]) in setPrimes }
def find_emirp(n):
setEmirp = makeSieveEmirp( 10**(int(ceil(log(n,10)))) )
crunchL = [p for p in setEmirp if p <= n]
return [len(crunchL), max(crunchL), sum(crunchL)]
| true
|
3f821ad7f3538a1066e56a6c8737932fcbda94b0
|
kelpasa/Code_Wars_Python
|
/6 кю/Parity bit - Error detecting code.py
| 1,118
| 4.21875
| 4
|
'''
In telecomunications we use information coding to detect and prevent errors while sending data.
A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit error.
In this case we are using even parity: the parity bit is set to 0 if the number of 1-bits is even, and is set to 1 if odd.
We are using them for the transfer of ASCII characters in binary (7-bit strings): the parity is added to the end of the 7-bit string, forming the 8th bit.
In this Kata you are to test for 1-bit errors and return a new string consisting of all of the correct ASCII caracters in 7 bit format (removing the parity bit), or "error" in place of ASCII characters in which errors were detected.
'''
def parity_bit(binary):
lst = []
for i in binary.split():
if (i.count('1') % 2 == 0 and i[-1] == '0') or (i.count('1') % 2 == 0 and i[-1] == '1'):
lst.append(i[:-1])
else:
lst.append('error')
return ' '.join(lst)
| true
|
ab10772302efd8e44c5b0d5a157587cbeea7ce62
|
kelpasa/Code_Wars_Python
|
/6 кю/Multiplication table.py
| 424
| 4.15625
| 4
|
'''
our task, is to create NxN multiplication table, of size provided in parameter.
for example, when given size is 3:
1 2 3
2 4 6
3 6 9
for given example, the return value should be: [[1,2,3],[2,4,6],[3,6,9]]
'''
def multiplicationTable(n):
table = []
for num in range(1, n+ 1):
row = []
for colum in range(1, n + 1):
row.append(num * colum)
table.append(row)
return table
| true
|
9180bd22fb2a47c8276454dda65caa58fd5116ce
|
kelpasa/Code_Wars_Python
|
/6 кю/Matrix Trace.py
| 1,236
| 4.34375
| 4
|
'''
Calculate the trace of a square matrix. A square matrix has n rows and n columns, where n is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or nil/None if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).
The trace of an n-by-n square matrix A is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of A.
A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.
For example, the following code...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
represents the matrix
|1 2 3|
|4 5 6|
|7 8 9|
which has a trace of 1 + 5 + 9 = 15.'''
from itertools import chain
def trace(matrix):
try:
if matrix == []:
return None
elif len(list(chain(*matrix)))// len(matrix[0]) != len(matrix[0]):
return None
else:
diagonal = []
for i in range(len(matrix)):
diagonal.append(matrix[i][i])
return sum(diagonal)
except ZeroDivisionError:
return None
| true
|
deb7b21d9a08444b3681c1fce4ce1f82e38a6192
|
kelpasa/Code_Wars_Python
|
/6 кю/Selective Array Reversing.py
| 893
| 4.46875
| 4
|
'''
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse.
E.g
selReverse([1,2,3,4,5,6], 2)
//=> [2,1, 4,3, 6,5]
if after reversing some portions of the array and the length of the remaining portion in the array is not up to the length argument, just reverse them.
selReverse([2,4,6,8,10,12,14,16], 3)
//=> [6,4,2, 12,10,8, 16,14]
selReverse(array, length)
array - array to reverse
length - length of each portion to reverse
Note : if the length argument exceeds the array length, reverse all of them, if the length argument is zero do not reverse at all.
'''
def sel_reverse(arr,n):
if n == 0:
return arr
else:
return sum([i[::-1] for i in [arr[i:i+n] for i in range(0, len(arr), n)]],[])
| true
|
2b6315a9c117156389761fb6d25ec1d375ed9d1b
|
kelpasa/Code_Wars_Python
|
/5 кю/Human Readable Time.py
| 690
| 4.15625
| 4
|
'''
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (99:59:59)
You can find some examples in the test fixtures.
'''
def make_readable(seconds):
H = seconds // 3600
M = (seconds-H*3600) // 60
S = ((seconds-H*3600)+(seconds-M*60))-seconds
if len(str(H)) == 1:
H = '0'+str(H)
if len(str(M)) == 1:
M = '0'+str(M)
if len(str(S)) == 1:
S = '0'+str(S)
return f"{H}:{M}:{S}"
| true
|
f67afbb5da9f57dd033101e6b219a495e466b392
|
kelpasa/Code_Wars_Python
|
/6 кю/Duplicate Arguments.py
| 584
| 4.25
| 4
|
'''
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function.
The array values passed in will only be strings or numbers. The only valid return values are true and false.
Examples:
solution(1, 2, 3) --> false
solution(1, 2, 3, 2) --> true
solution('1', '2', '3', '2') --> true
'''
def solution(*args):
arr = []
for i in args:
if i not in arr:
arr.append(i)
if tuple(arr) == args:
return False
else:
return True
| true
|
2d40bf4dba925bf5a846e7fd859f390fe5046b07
|
eligiuz/Curso_Python
|
/practica_for.py
| 1,217
| 4.1875
| 4
|
# for i in ["primavera","verano","otoño","invierno"]:
# print(i)
#-- imprime en una linea con un espacio por pase de for
# for i in ["Pildoras", "Informativas", 3]:
# print("Hola",end=" ")
#-- Revisa si se encuentra la @ en el email --
# contador=0
# miEmail=input("Introduce tu dirección de email: ")
# for i in miEmail:
# if (i=="@" or i=="."):
# contador=contador+1
# if contador==2:
# print("email es correcto")
# else:
# print("el email no es correcto")
#-- Range --
# for i in range(5):
# # f nos sirve para concatenar un string y un número
# print(f"Valor de la varianle {i}")
# #-- Cuenta a partir del 5 y hasta el 9 ---
# for i in range(5,9):
# # f nos sirve para concatenar un string y un número
# print(f"Valor de la varianle {i}")
# #-- Cuenta a partir del 5 hasta el 50 y va brincando de 3 en 3 ---
# for i in range(5,50,3):
# # f nos sirve para concatenar un string y un número
# print(f"Valor de la varianle {i}")
#-- Función len() ---
valido=False
email=input("Introduce tu email: ")
for i in range(len(email)):
if email[i]=="@":
valido=True
if valido:
print("Email correcto")
else:
print("Email incorrecto")
| false
|
421b1232a36a6718cce0560efee1260a906f84fb
|
miguel-nascimento/coding-challenges-stuffs
|
/project-euler/004 - Largest palindrome product.py
| 375
| 4.1875
| 4
|
# Find the largest palindrome made from the product of two 3-digit numbers.
# A palindromic number reads the same both ways
def three_digits_palindome():
answer = max(i * j
for i in range(100, 1000)
for j in range(100, 1000)
if str(i * j) == str(i * j)[:: -1])
return str(answer)
print(three_digits_palindome())
| true
|
4aef3e9c439bc78c0de034650e260cf98b6b5ee3
|
evelyn-pardo/actividad-de-clases
|
/condicion.py
| 1,372
| 4.1875
| 4
|
class Condicion:
def _init_(self,num1,num2):
self.numero1=num1
self.numero2=num2
numero = self.numero1+self.numero2
self.numero3=numero
def __init__(self,num1,num2):
self.numero1=num1
self.numero2=num2
numero = self.numero1+self.numero2
self.numero3=numero
def usoif (self):
if self.numero1==self.numero2:
print("numero1:{} y numero2:{} son iguales".format(self.numero1,self.numero2))
elif self.numero1 < self.numero3:
print("numero1:{} es menor numero3:{}".format(self.numero1,self.numero3))
else:
print("no es igual")
print("fin del metodo")
condi1 = Condicion(8,18)
print(condi1.numero3)
class ciclo:
def _init_(self,numero=10):
self.numero=numero
def usowhile (self):
print("dentro de clase",self.numero)
LETRA=""
while LETRA not in ("a","e","i","o","u"):
LETRA =input("ingrese una vocal: ").lower()
#caracter= caracter.lower()
print("Exelente, es la letra correcta:{} si es vocal".format(LETRA))
ciclo1= ciclo()
print(ciclo1.usowhile())
print("fuera de la clase",ciclo1.numero)
| false
|
50e6dc86d6a2dcec1df9cac643815c3e9c3a7f06
|
ArnoBali/python-onsite
|
/week_01/03_basics_variables/08_trip_cost.py
| 402
| 4.46875
| 4
|
'''
Receive the following arguments from the user:
- miles to drive
- MPG of the car
- Price per gallon of fuel
Display the cost of the trip in the console.
'''
miles = int(input("please input miles to drive:" ))
mpg = int(input("please input MPG of the car:" ))
p_gallon = int(input("please input Price per gallon of fuel:" ))
cost_trip = (miles / mpg) * p_gallon
print(cost_trip)
_
| true
|
1bdcfa5db635cbba8f5f54f3d651187ee1865810
|
ArnoBali/python-onsite
|
/week_02/07_conditionals_loops/Exercise_05.py
| 532
| 4.375
| 4
|
'''
Take two numbers from the user, an upper and lower bound. Using a loop, calculate the sum
of numbers from the lower bound to the upper bound. Also, calculate the average of numbers.
Print the results to the console.
For example, if a user enters 1 and 100, the output should be:
The sum is: 5050
The average is: 50.5
'''
input1 = 1 + int(input("Upper bound: "))
input2 = int(input("Lower bound: "))
sum = 0
for i in range(input2, input1):
sum += i
print(sum)
average = sum / (input1 - input2)
print(average)
| true
|
d2dd93a12035f03644a19898b5e8356a16320a02
|
ArnoBali/python-onsite
|
/week_02/07_conditionals_loops/Exercise_01.py
| 382
| 4.5625
| 5
|
'''
Write a program that gets a number between 1 and 1,000,000,000
from the user and determines whether it is odd or even using an if statement.
Print the result.
NOTE: We will be using the input() function. This is demonstrated below.
'''
input_ = int(input("Please input a number between 1 - 1,000,000,000: "))
if input_ % 2 == 0:
print("Even")
else:
print("Uneven")
| true
|
930aa1338bd9bcab9c005cb62111e8d6b7820016
|
udichibarsagadey/pychemistry
|
/ML/panda_ML.py
| 409
| 4.15625
| 4
|
"""
how to write csv file in panda
1) Pandas head()
2) Pandas tail()
3) Pandas write csv ‘dtype’
4) Pandas write csv ‘true_values‘
5) Pandas write csv ‘false_values’
# pandas fillna
"""
import pandas as pd
ab = pd.read_csv('Fortune_10.csv')
print(ab)
print(ab.head())
print(ab.tail(7))
ab = pd.read_csv('student_results.csv')
print(ab)
# pandas interpolate()
ab = pd.interpolate()
print(ab)
| false
|
c3eafe4b5b245cf0ad6e77460780af570a92560c
|
chandrakant100/Assignments_Python
|
/Practical/assignment4/factorial.py
| 246
| 4.28125
| 4
|
# To find factorial of a number using recursion
def rec_fact(num):
if num <= 1:
return 1
return num * rec_fact(num - 1)
num = int(input("Enter a number: "))
print("Factorial of {0} is {1}".format(num, rec_fact(num)))
| true
|
349d17c98133a3970fe6f20f369a802ab59d8c3b
|
govindarajanv/python
|
/programming-practice-solutions/exercises-set-1/exercise-01-solution.py
| 968
| 4.21875
| 4
|
#1 printing "Hello World"
print ("Hello World")
#Displaying Python's list of keywords
import keyword
print ("List of key words are ..")
print (keyword.kwlist)
#2 Single and multi line comments
# This is the single line comment
''' This is multiline
comment, can be
used for a paragraph '''
#3 Multi line statements
sum = 1+\
2+\
3\
print ("sum = ",sum)
#4 mutiple assignments
a,b,c = 1, 2.0, "govindarajanv"
print ("a = ",a)
print ("b = ",b)
print ("c = ",c)
print ("Multiple statements in a line")
#5 multiple statements in a line
a = 3; b=4; c = 5
print ("a = ",a)
print ("b = ",b)
print ("c = ",c)
#print 1,2,3,4 with sep as '|' and end character as '&' default is \n
print (1,2,3,4)
print (1,2,3,4,sep='|',end='&')
print ("")
print ("a",1,"b",2,sep='+',end='=')
#Read input from the user and greet him
print ("Now let us greet and meet")
name = input ("I am Python. May I know your name?")
print ("Hi", name,"!. Glad to meet you!!!")
| true
|
4f5ad33e6485de134980f5523cb21c41b51bfb99
|
govindarajanv/python
|
/gui-applications/if-else.py
| 338
| 4.15625
| 4
|
#
number = 23
# input() is used to get input from the user
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.') # New block starts here
elif guess < number:
print('No, it is a little higher than that') # Another block
else:
print('No, it is a little lower than that')
| true
|
6658ab77e9521efd122e1348c1860401d6b7abda
|
govindarajanv/python
|
/regex/regex-special-sequences.py
| 1,679
| 4.34375
| 4
|
import re
pattern = r"(.+) \1"
print ("pattern is",pattern)
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
match = re.match(pattern, "abc ab")
if match:
print ("Match 4")
match = re.match(pattern, "abc abcd")
if match:
print ("Match 5")
# \d, \s, and \w match digits, whitespace, and word characters respectively.
# In ASCII mode they are equivalent to [0-9], [ \t\n\r\f\v], and [a-zA-Z0-9_].
# Versions of these special sequences with upper case letters - \D, \S, and \W - mean the opposite to the lower-case versions.
# For instance, \D matches anything that isn't a digit
#(\D+\d) matches one or more non-digits followed by a digit.
pattern = r"(\D+\d)"
print ("pattern is",pattern)
match = re.match(pattern, "Hi 999!")
if match:
print("Match 1")
match = re.match(pattern, "1, 23, 456!")
if match:
print("Match 2")
match = re.match(pattern, " ! $?")
if match:
print("Match 3")
# The sequences \A and \Z match the beginning and end of a string, respectively.
# The sequence \b matches the empty string between \w and \W characters, or \w characters and the beginning or end of the string. Informally, it represents the boundary between words.
# The sequence \B matches the empty string anywhere else.
pattern = r"\b(cat)\b"
print ("pattern is",pattern)
match = re.search(pattern, "The cat sat!")
if match:
print ("Match 1")
match = re.search(pattern, "We s>cat<tered?")
if match:
print ("Match 2")
match = re.search(pattern, "We scattered.")
if match:
print ("Match 3")
| true
|
170ffd1a881e4043e7e9be7d70841c5652443d9d
|
govindarajanv/python
|
/regex/regex.py
| 1,061
| 4.125
| 4
|
import re
# Methods like match, search, finall and sub
pattern = r"spam"
print ("\nFinding \'spam\' in \'eggspamsausagespam\'\n")
print ("Usage of match - exact match as it looks at the beginning of the string")
if re.match(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
print ("\nUsage of search - search a given substring in a string and returns the resuult in boolean")
if re.search(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
print ("\nUsage of findall - returns list of substrings matching the pattern")
print(re.findall(pattern, "eggspamsausagespam"))
print ("\nFinding \'pam\' in \'eggspamsausages\'\n")
pattern1 = r"pam"
match = re.search(pattern1, "eggspamsausages")
if match:
# returns string matched
print(match.group())
print(match.start())
print(match.end())
# positions as tuples
print(match.span())
str = "My name is David. Hi David."
print ("old string:",str)
pattern = r"David"
newstr = re.sub(pattern, "John", str)
print ("new string:",newstr)
| true
|
8638bd18648d6ed7aceaffd6c842e42a0cad680b
|
govindarajanv/python
|
/functional-programming/loops/fibonacci.py
| 539
| 4.1875
| 4
|
"""
0,1,1,2,3,5,8,13...n
"""
def factorial(n):
first_value = 0
second_value = 1
for i in range(1,n,1):
if i == 1:
print ("{} ".format(first_value))
elif i==2:
print ("{} ".format(second_value))
else:
sum = first_value + second_value
print ("{} ".format(sum))
first_value = second_value
second_value = sum
n=int(input("Enter the number of terms:"))
if n <= 0:
print ("Enter any number greater than zero")
else:
factorial(n)
| true
|
04db43932905662ea741f34a135cd9097941e469
|
govindarajanv/python
|
/regex/regex-character-classes.py
| 1,794
| 4.6875
| 5
|
import re
#Character classes provide a way to match only one of a specific set of characters.
#A character class is created by putting the characters it matches inside square brackets
pattern = r"[aeiou]"
if re.search(pattern, "grey"):
print("Match 1")
if re.search(pattern, "qwertyuiop"):
print("Match 2")
if re.search(pattern, "rhythm myths"):
print("Match 3")
pattern = r"[abc][def]"
if re.search(pattern, "ad"):
print("Match found for ad")
if re.search(pattern, "ae"):
print("Match found for ae")
if re.search(pattern, "ea"):
print("Match found for ea")
#Character classes can also match ranges of characters.
"""
The class [a-z] matches any lowercase alphabetic character.
The class [G-P] matches any uppercase character from G to P.
The class [0-9] matches any digit.
Multiple ranges can be included in one class. For example, [A-Za-z] matches a letter of any case
"""
pattern = r"[A-Z][A-Z][0-9]"
if re.search(pattern, "LS8"):
print("Match 1")
if re.search(pattern, "E3"):
print("Match 2")
if re.search(pattern, "1ab"):
print("Match 3")
"""
Place a ^ at the start of a character class to invert it.
This causes it to match any character other than the ones included.
Other metacharacters such as $ and ., have no meaning within character classes.
The metacharacter ^ has no meaning unless it is the first character in a class
"""
print ("\n\n")
pattern = r"[^A-Z]"
if re.search(pattern, "this is all quiet"):
print("Match 1")
if re.search(pattern, "AbCdEfG123"):
print("Match 2")
if re.search(pattern, "THISISALLSHOUTING"):
print("Match 3")
if re.search(pattern, "this is all quiet"):
print("Match 1")
if re.search(pattern, "AbCdEfG123"):
print("Match 2")
if re.search(pattern, "THISISALLSHOUTING"):
print("Match 3")
| true
|
10e85d68d0c5c121457de9a464b8cc8a22bf62db
|
Achraf19-okh/python-problems
|
/ex7.py
| 469
| 4.15625
| 4
|
print("please typpe correct informations")
user_height = float(input("please enter your height in meters"))
user_weight = float(input("please enter your weight in kg"))
BMI = user_weight/(user_height*user_height)
print("your body mass index is" , round(BMI,2))
if(BMI <= 18.5):
print("you are under weight")
elif(BMI > 18.5 and BMI <= 24.9):
print("you are normal weight")
elif(BMI > 24.9 and BMI <= 29.9):
print("overweight")
else:
print("Obesity")
| true
|
e5e26adc9ce9c5c85bd2b8afdb2bc556746f8d20
|
azhar-azad/Python-Practice
|
/07. list_comprehension.py
| 770
| 4.125
| 4
|
# Author: Azad
# Date: 4/2/18
# Desc: Let’s say I give you a list saved in a variable:
# a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a and makes a new list
# that has only the even elements of this list in it.
# -----------------------------------------------------------------------------------
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
even_list = [i for i in a if i % 2 == 0]
print(even_list)
print("\n")
print("Using a random list: ")
import random
rand_list = []
list_length = random.randint(5, 15)
while len(rand_list) < list_length:
rand_list.append(random.randint(1, 75))
even_list = [i for i in rand_list if i % 2 == 0]
print(rand_list)
print(even_list)
| true
|
bcd76925689d3e401ce55f7efe88aa323b02c0d0
|
azhar-azad/Python-Practice
|
/10. list_overlap_comprehensions.py
| 995
| 4.3125
| 4
|
# Author: Azad
# Date: 4/5/18
# Desc: Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that
# contains only the elements that are common between the lists(without duplicates).
# Make sure your program works on two lists of different sizes.
# Write this program using at least one list comprehension.
#
# Extra:
# Randomly generate two lists to test this
#_______________________________________________________________________________________________________
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
common_list = []
# using list comprehensions
common_list_dup = [i for i in a if i in b] # contains duplicates values
for i in common_list_dup:
if i not in common_list:
common_list.append(i)
print(common_list)
| true
|
900685d187fce72a3edb34daef753d90395b2a8b
|
ARBUCHELI/100-DAYS-OF-CODE-THE-COMPLETE-PYTHON-PRO-BOOTCAMP-FOR-2021
|
/Guess the Number/guess_the_number.py
| 1,951
| 4.4375
| 4
|
#Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Track the number of turns remaining.
# If they run out of turns, provide feedback to the player.
# Include two different difficulty levels (e.g., 10 guesses in easy mode, only 5 guesses in hard mode).
from art import logo
import random
print(logo)
print("Welcome to the Number Guessing Name!")
print("I'm thinking of a number between 1 and 100.")
computer_number = random.randint(1, 100)
print(f"Pssst, the correct answer is {computer_number}")
level = input("Choose a difficulty. Type 'easy' or 'hard': ")
attempts = 0
end_game = False
if level == "easy":
print("You have 10 attempts remaining to guess the number.")
attempts = 10
elif level == "hard":
print("You have 5 attempts remaining to guess the number.")
attempts = 5
def guessing():
global attempts
guess = int(input("Make a guess: "))
if not guess == computer_number:
attempts -= 1
if guess < computer_number and attempts == 0:
print("Too low.")
print("You've run out of guesses, you lose.")
elif guess > computer_number and attempts == 0:
print("Too high.")
print("You've run out of guesses, you lose.")
elif guess > computer_number:
print("Too high.")
print("Guess again.")
print(f"You have {attempts} attempts remaining to guess the number.")
elif guess < computer_number:
print("Too low.")
print("Guess again.")
print(f"You have {attempts} attempts remaining to guess the number.")
elif guess == computer_number:
print(f"You got it! The answer was {guess}.")
global end_game
end_game = True
while attempts > 0:
if end_game == False:
guessing()
| true
|
2a29710b1ce51119772ee86b796193f1eec0658a
|
tzyl/ctci-python
|
/chapter9/9.1.py
| 726
| 4.28125
| 4
|
def stair_permutations(n):
"""Returns the number of different ways a child can hop up a staircase
with n steps by hopping 1,2 or 3 steps at a time."""
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
return (stair_permutations(n - 1) +
stair_permutations(n - 2) +
stair_permutations(n - 3))
def stair_permutations2(n):
"""Iterative solution."""
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
a, b, c = 1, 1, 2
for _ in xrange(n - 2):
a, b, c = b, c, a + b + c
return c
if __name__ == '__main__':
for i in xrange(20):
print stair_permutations(i), stair_permutations2(i)
| false
|
4e51ccfe4bbdf4401dd6c2741d3f2d8ca63ef3c2
|
tzyl/ctci-python
|
/chapter9/9.2.py
| 1,672
| 4.125
| 4
|
def number_of_paths(X, Y):
"""Returns the number of paths to move from (0, 0) to (X, Y) in an X by Y
grid if can only move right or down."""
if X == 0 or Y == 0:
return 1
return number_of_paths(X - 1, Y) + number_of_paths(X, Y - 1)
def number_of_paths2(X, Y):
"""Solution using mathematical analysis that the number of paths is
(X + Y - 2) choose (min(X, Y) - 1)."""
if X == 0 or Y == 0:
return 1
numerator = X + Y
denominator = 1
for i in xrange(1, min(X, Y)):
numerator *= X + Y - i
denominator *= 1 + i
return numerator / denominator
def memoize(fn):
cache = {}
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = fn(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def find_a_path(X, Y, blocked):
"""Finds a path from (0, 0) to (X, Y) with blocked positions."""
if (X, Y) in blocked:
return None
if X == 0 and Y == 0:
return [(X, Y)]
if X != 0:
right_path = find_a_path(X - 1, Y, blocked)
if right_path is not None:
right_path.append((X, Y))
return right_path
if Y != 0:
down_path = find_a_path(X, Y - 1, blocked)
if down_path is not None:
down_path.append((X, Y))
return down_path
return None
if __name__ == '__main__':
for i in xrange(1, 10):
for j in xrange(1, 10):
print number_of_paths(i, j), number_of_paths2(i, j)
print find_a_path(100, 100, [(9, 10), (0, 1), (1, 2)])[::-1]
| true
|
9f8201a7a55fd59dc02cdd24fbd64ee8cd10ebfc
|
tzyl/ctci-python
|
/chapter5/5.5.py
| 736
| 4.28125
| 4
|
def to_convert(A, B):
"""Clears the least significant bit rather than continuously shifting."""
different = 0
C = A ^ B
while C:
different += 1
C = C & C - 1
return different
def to_convert2(A, B):
"""Using XOR."""
different = 0
C = A ^ B
while C:
if C & 1:
different += 1
C >>= 1
return different
def to_convert3(A, B):
"""Returns the number of bits required to convert
integer A into integer B.
"""
different = 0
while A or B:
if A & 1 != B & 1:
different += 1
A >>= 1
B >>= 1
return different
if __name__ == '__main__':
print to_convert(31, 14)
| true
|
e46c3484f1214958d5f7c4574cb5be85b7336c0c
|
CharlesA750/practicals_cp1404
|
/P5_Email.py
| 579
| 4.28125
| 4
|
email_dict = {}
def main():
email = input("What is your email address?\n>>> ")
while email != "":
nameget = get_name(email)
name_check = input("Is your name " + nameget + "? (y/n) ").lower()
if name_check == "y":
email_dict[email] = nameget
else:
real_name = input("Name: ")
email_dict[email] = real_name
email = input("What is your email address?\n>>> ")
print(email_dict)
def get_name(email):
parts = email.split("@")[0].split(".")
name = " ".join(parts).title()
return parts
| false
|
2e925cbed4eaeb10f9f822f1b7600823bf8f0603
|
carlosmertens/Python-Introduction
|
/default_argument.py
| 2,221
| 4.59375
| 5
|
""" DEFAULT ARGUMENTS """
print("\n==================== Example 1 ====================\n")
def box(width, height, symbol="*"):
"""print a box made up of asterisks, or some other character.
symbol="*" is a default in case there is not input
width: width of box in characters, must be at least 2
height: height of box in lines, must be at least 2
symbol: a single character string used to draw the box edges
"""
# print top edge of box
print(symbol * width)
# print sides of box
for _ in range(height - 2):
print(symbol + " " * (width - 2) + symbol)
# print bottom edge of box
print(symbol * width)
# Call function
box(10, 10)
box(10, 10, "$")
print("\n==================== Example 2 ====================\n")
def print_list(l, numbered=False, bullet_character="-"):
"""Prints a list on multiple lines, with numbers or bullets
Arguments:
l: The list to print
numbered: set to True to print a numbered list
bullet_character: The symbol placed before each list element. This is
ignored if numbered is True.
"""
for index, element in enumerate(l):
if numbered:
print("{}: {}".format(index + 1, element))
else:
print("{} {}".format(bullet_character, element))
print_list(["cats", "in", "space"])
print_list(["cats", "in", "space"], True)
print("\n==================== Example 3 ====================\n")
""" Default arguments are a helpful feature, but there is one situation where they can be surprisingly unhelpful.
Using a mutable type (like a list or dictionary) as a default argument and then modifying that argument can lead
to strange results. It's usually best to avoid using mutable default arguments: to see why, try the following
code locally.
Consider this function which adds items to a todo list. Users can provide their own todo list, or add items
to a default list:
"""
def todo_list(new_task, base_list=['wake up']):
"""Docstring is expected."""
base_list.append(new_task)
return base_list
print(todo_list("check the mail"))
print(todo_list("begin orbital transfer"))
print("\n==================== Example 4 ====================\n")
| true
|
e4232c807b730f7419e3b750122c765543747fc8
|
pawansingh10/PracticeDemo
|
/CodeVita/Fibonacci.py
| 1,724
| 4.125
| 4
|
import math
"""USING RECURSION TIME COMPLEXITY EXPONENTIAL COMPLEXITY SPACE O(N)"""
def fib(n):
if n==0 :
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
"""USING DYNAMIC PROGRAMMING AVOID REPAETED WORK"""
def fibo(n):
fib_list=[0,1]
while len(fib_list)<n+1 :
fib_list.append(0)
if n<=1:
return n
else:
if fib_list[n-1]==0:
fib_list[n-1]=fibo(n-1)
if fib_list[n-2]==0:
fib_list[n-2]=fibo(n-2)
fib_list[n]=fib_list[n-2]+fib_list[n-1]
return fib_list[n]
"""SIMPLE T=O(n) and S= O(1)"""
def fibonacci(n):
a=0
b=1
if n<0:
return False
elif n==0:
return a
elif n==1:
return b
else:
for i in range(2,n+1):
c=a+b
a=b
b=c
return b
"""USING POWER OF MATRIX T=O(n) AND S=O(1)"""
# n
# (1 1) = (Fn+1 Fn )
# (1 0) = (Fn Fn-1)
def fibon(n):
F=[[1,1],
[1,0]]
if n==0:
return 0
power(F,n-1)
return F[0][0]
def multiply(F,M):
x=(F[0][0]*M[0][0]+F[0][1]*M[1][0])
y=(F[0][0]*M[0][1]+F[0][1]*M[1][1])
z=(F[1][0]*M[0][0]+F[1][1]*M[1][0])
w=(F[1][0]*M[0][1]+F[1][1]*M[1][1])
F[0][0]=x
F[0][1]=y
F[1][0]=z
F[1][1]=w
def power(F,n):
M=[[1,1],
[1,0]]
for i in range(2,n+1):
multiply(F,M)
"""USING FORMULA o(logn)"""
# n
# Fn=[ ({sqrt(5)+1}/2) ]sqrt(5)
def fibonacci_(n):
result=(1+ math.sqrt(5))/2
return math.floor((math.pow(result,n)/math.sqrt(5)))
n=int(input())
#print(fibonacci_(n))
result=fibonacci_(n)
if result==12:
print(13)
else:
print(result)
| false
|
62ce698cea9b770dd6f641a27aec07034898d2e8
|
usmanwardag/Python-Tutorial
|
/strings.py
| 1,619
| 4.28125
| 4
|
import sys
'''
Demonstrates string functions
'''
def stringMethods():
s = 'Hello, how are you doing?'
print s.strip() #Removes whitespaces
print s.lower()
print s.upper() #Changes case
print s.isalpha()
print s.isdigit()
print s.isspace() #If all characters belong to a class
print s.startswith('H')
print s.endswith('ng?')
print s.find('are') #Locates the index where the char/string starts
print s.replace('?', '!?')
print s.split('o') #Splits on specified character
examples = ['Usman','Mahmood','Khan']
print ' '.join(examples) #Joins list with a given character/string
#Search for more by typing "Python String methods"
print '---------------------------------------------------------------------'
'''
Demonstrates procedures to find sub-strings
'''
def stringSlicing():
s = 'I am doing great! How about you?'
print s[4:] #all characters from 4 onwards
print s[-1] #last character
print s[:-3] #all characters until the third last
print s[-5:] #all characters starting from fifth last
print '---------------------------------------------------------------------'
'''
Displays the string in unicode format
'''
def unicodeString():
examples = ['Usman','Mahmood','Khan']
s = ('\n').join(examples)
t = unicode(s,'utf-8')
print t #String in unicode format
print '---------------------------------------------------------------------'
'''
Main function to run test modules.
Run any one of above listed function to test
with commands.
'''
def main():
stringMethods()
stringSlicing()
unicodeString()
if __name__ == '__main__':
main()
| true
|
d9c4bbd50b8473f6dc1ad17b3e0fa4ec8ce5c424
|
Micky143/LPU_Python
|
/Functions2.py
| 725
| 4.3125
| 4
|
greeting ="hello World.!"
print(greeting)
print(greeting.find('lo')) #output :- 3
print(greeting.replace('llo', 'y')) #output :- hey World.!
print(greeting.startswith('hell')) #output :- True
print(greeting.isalpha()) #output :- False
greeting = "Micky Mehra..!"
print(greeting.lower())
print(greeting.title()) #output :- Micky Mehra..!
print(greeting.strip()) #output :- Micky Mehra..!
print(greeting.strip('!')) #output :- Micky Mehra.. (no Show ' ! ' )
g="ram and shayam".split() #output :- ['ram', 'and', 'shayam']
print(g)
date='2-12-2000'.split(sep='-') #output :- ['2', '12', '2000']
print(date)
fnd_name = ','.join(['Micky','Shujma'])
print(fnd_name)
| false
|
16d8dd34584e0b7bddc27bd9bddddbea2be24baf
|
fibeep/calculator
|
/hwk1.py
| 1,058
| 4.21875
| 4
|
#This code will find out how much money you make and evaluate whether you
#are using your finances apropriately
salary = int(input("How much money do you make? "))
spending = int (input("How much do you spend per month? "))
saving = salary - spending
#This line will tell you if you are saving enough money to eventually reach "financial freedom"
if spending >= salary * 0.9:
print("You are spending too much money")
else:
print("Good job, you are on the path to financial freedom")
print("You are currently saving " + str(saving) + " dollars per month")
#This code will help you calculate wether you are making enough money to save X ammount in 10 years
future = int(input("How much money do you want to have in your savings account in 10 years? (Please include only a number) "))
if future / 10 <= salary:
print("You need to save",future/10,"dollars every year from now on.")
else:
print("You need to find a new job that pays " + str(future/10) + " dollars because with your current salary it is impossible to save this much money.")
| true
|
7d090650fc7fc908e6a8914310b12878ce38dd80
|
SpencerBeloin/Python-files
|
/factorial.py
| 228
| 4.21875
| 4
|
#factorial.py
#computes a factorial using reassignment of a variable
def main():
n= eval(input("Please enter a whole number: "))
fact = 1
for factor in range(n,1,-1):
fact = fact*factor
print fact
main()
| true
|
02cf43e0fbc8f701a5c57a8f87ee32c6475469d0
|
mayad19-meet/meet2017y1lab4
|
/fruit_sorter.py
| 244
| 4.21875
| 4
|
new_fruit=input('what fruit am i storing?')
if new_fruit=='apples':
print('bin 1!')
elif new_fruit=='oranges':
print('bin 2!')
elif new_fruit=='olives':
print('bin 3!')
else:
print('error!! i do not recognize this fruit!')
| false
|
0e4b133eba2337b2e30e389d1fe95606bf439233
|
annettemathew/rockpaperscissors
|
/rock_paper_scissors.py
| 2,038
| 4.1875
| 4
|
#Question 2
# Write a class called Rock_paper_scissors that implements the logic of
# the game Rock-paper-scissors. For this game the user plays against the computer
# for a certain number of rounds. Your class should have fields for how many rounds
# there will be, the current round number, and the number of wins each player has.
# There should be methods for getting the computer’s choice, finding the winner of a round,
# and checking to see if someone has won the (entire) game. You may want more methods.
from random import randint
exit_flag = False
class Rock_paper_scissors:
def __init__(self, choice):
self.choice = choice
self.list = ['r', 'p', 's']
def generate_comp_response(self):
rand_int = randint(0, 2)
print("Computer generated: ", self.list[rand_int])
return self.list[rand_int]
def check_win(self, choice, c_choice):
if(choice == c_choice):
print("Draw")
return
if(choice == 'r'):
if(c_choice == 'p'):
print('Computer won')
else: #computer picked scissors
print('User won')
elif(choice == 'p'):
if(c_choice == 'r'):
print('User won')
else: #computer picked scissors
print('Computer won')
else: #user picked scissors
if(c_choice == 'r'):
print('Computer won')
else: #Computer picked paper
print('User won')
print("Hi! Welcome to Rock Paper Scissors!")
while(exit_flag == False):
user_choice = input("Please enter r, p, s, or x(to exit): ")
user_choice = user_choice.lower()
if(user_choice == 'x'):
exit(0)
elif(user_choice != 'r' and user_choice != 'p' and user_choice != 's'):
print("Error: incorrect input")
exit(-1)
Rps = Rock_paper_scissors(user_choice)
comp_choice = Rps.generate_comp_response()
Rps.check_win(user_choice, comp_choice)
| true
|
50888ff04c2d2ad05058c3ff77a6a94a2cd93fcf
|
atulmkamble/100DaysOfCode
|
/Day 19 - Turtle Race/turtle_race.py
| 1,896
| 4.46875
| 4
|
"""
This program implements a Turtle Race. Place your bet on a turtle and tune on to see who wins.
"""
# Import required modules
from turtle import Turtle, Screen
from random import randint
from turtle_race_art import logo
def main():
"""
Creates turtles and puts them up for the race
:return: nothing
"""
# Greet the user with logo
print(logo)
# Initialize the required variables
colors = ['purple', 'blue', 'green', 'yellow', 'orange', 'red']
all_turtles = []
is_game_on = True
# Setup the screen
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title='Make your bet',
prompt='Which turtle will win the race? Enter a color (purple, blue, green, yellow, '
'orange, red): ').casefold()
# Set the y axis position of turtles
y = -100
for t in range(len(colors)):
new_turtle = Turtle(shape='turtle')
new_turtle.color(colors[t])
new_turtle.penup()
new_turtle.goto(x=-230, y=y)
all_turtles.append(new_turtle)
y += 40
# If the user has entered the bet, start the race
if user_bet:
while is_game_on:
for turt in all_turtles:
# If the turtle is at finish line
if turt.xcor() >= 220:
is_game_on = False
winner = turt.pencolor()
if user_bet == winner:
print(f'You won! The {winner} turtle is the winner.')
else:
print(f'You lost! The {winner} turtle is the winner.')
break
else:
turt.forward(randint(1, 10))
screen.exitonclick()
else:
print('You have not placed your bet!')
if __name__ == '__main__':
main()
| true
|
d70fb4d40081bda2356d7f9909c5873a7ab3a126
|
atulmkamble/100DaysOfCode
|
/Day 21 - Snake Game (Part 2)/main.py
| 1,529
| 4.125
| 4
|
"""
This program implements the complete snake game
"""
from turtle import Screen
from time import sleep
from snake import Snake
from food import Food
from scoreboard import Scoreboard
def main():
# Setup the screen
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake Game')
screen.tracer(0)
# Create snake, food & score object and bind keys for snake movement
snake = Snake()
food = Food()
scoreboard = Scoreboard()
screen.listen()
screen.onkeypress(snake.up, 'Up')
screen.onkeypress(snake.down, 'Down')
screen.onkeypress(snake.left, 'Left')
screen.onkeypress(snake.right, 'Right')
# Start the game
is_game_on = True
while is_game_on:
scoreboard.display_score()
screen.update()
sleep(0.1)
snake.move()
# Detect collision with the food
if snake.head.distance(food) < 15:
food.refresh()
snake.extend()
scoreboard.update_score()
# Detect collision with wall
if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
scoreboard.game_over()
is_game_on = False
# Detect collision with tail
for square in snake.snake_list[1:]:
if snake.head.distance(square) < 10:
is_game_on = False
scoreboard.game_over()
screen.exitonclick()
if __name__ == '__main__':
main()
| true
|
cec29c33017cd1b9398ea08710e6ff219a43933c
|
atulmkamble/100DaysOfCode
|
/Day 10 - Calculator/calculator.py
| 1,736
| 4.21875
| 4
|
"""
This program implements the classic calculator functionality (Addition, Subtraction, Multiplication & Division)
"""
from calculator_art import logo
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1 / n2
def calculator():
"""
This function get the numbers from user and operate on them recursively
:return: returns nothing
"""
# Greet the user
print(logo)
print('Note: You can close the program/window to exit')
operations = {
'+': add,
'-': subtract,
'*': multiply,
'/': divide,
}
# Get the first number
num1 = float(input('What\'s the first number?: '))
# Print the operations
for key in operations:
print(key)
# Initialize a variable to start a new calculation
go_again = True
while go_again:
# Get the operation and second number
operation_symbol = input('Pick an operation: ')
num2 = float(input('What\'s the next number?: '))
# Call the respective function as per the input operation
answer = operations[operation_symbol](num1, num2)
# Print the output
print(f'{num1} {operation_symbol} {num2} = {answer}')
# Get a response to start a new calculation or continue with the current answer
response = input(
f'Type "y" to continue calculating with {answer} or type "n" start a new calculation: ').casefold()
if response == 'n':
go_again = False
# Use recursion
calculator()
elif response == 'y':
num1 = answer
# Execute the calculator function
calculator()
| true
|
02089de9852f240b5ff07e1ca47e8e41e19537c2
|
atulmkamble/100DaysOfCode
|
/Day 4 - Rock Paper Scissors/rock_paper_scissors.py
| 2,029
| 4.3125
| 4
|
"""
This program is a game of rock, paper and scissors. You and the program compete in this game to emerge as a
winner. The program is not aware of your choice and it's a fair game. Please follow the directions in the program.
"""
from random import randint
from time import perf_counter
from time import process_time
# Time Tracking Start
tic1 = perf_counter()
tic2 = process_time()
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# Define a list with ASCII images of rock, paper, and scissors
game_options = [rock, paper, scissors]
# Display a welcome message and get the player choice
print('Welcome to Rock Paper Scissors!\nLet us see if you can beat the program and emerge as a winner. Let\'s Go!!!\n')
player_choice = int(input('What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors\n'))
# Handle invalid inputs and compare the choices to determine the winner
if 0 <= player_choice <= 2:
print(game_options[player_choice])
program_choice = randint(0, 2)
print('Computer chose:')
print(game_options[program_choice])
if player_choice == program_choice:
print('Result: It\'s a Draw!')
# Considered only player win scenarios
elif (player_choice == 0 and program_choice == 2) or (player_choice == 2 and program_choice == 1) or (
player_choice == 1 and program_choice == 0):
print('Result: You Won!')
else:
print('Result: You Lose!')
else:
print('Invalid choice! You Lose!')
# Time Tracking End
toc1 = perf_counter()
toc2 = process_time()
# Print execution time
print('\nExecution Time Details:')
print(f'Total execution time including wait/sleep time: {round(toc1 - tic1, 2)}s')
print(f'Total execution time excluding wait/sleep time: {round(toc2 - tic2, 2)}s')
| true
|
f97594ad3514fa073068bc4f54194ab13abeaec3
|
duochen/Python-Kids
|
/Lecture06_Functions/Homework/rock-paper-scissors-game.py
| 891
| 4.15625
| 4
|
print("Welcome to the Rock Paper Scissors Game!")
player_1 = "Duo"
player_2 = "Mario"
def compare(item_1, item_2):
if item_1 == item_2:
return("It's a tie!")
elif item_1 == 'rock':
if item_2 == 'scissors':
return("Rock wins!")
else:
return("Paper wins!")
elif item_1 == 'scissors':
if item_2 == 'paper':
return("Scissors win!")
else:
return("Rock wins!")
elif item_1 == 'paper':
if item_2 == 'rock':
return("Paper wins!")
else:
return("Scissors win!")
else:
return("Uh, that's not valid! You have not entered rock, paper or scissors.")
player_1_choice = input("%s, rock, paper, or scissors?" % player_1)
player_2_choice = input("%s, rock, paper, or scissors?" % player_2)
print(compare(player_1_choice, player_2_choice))
| true
|
c2abe9e5d0fce7f2cfbb6657e98349b4cfcbd591
|
JohannesHamann/freeCodeCamp
|
/Python for everybody/time_calculator/time_calculator.py
| 2,997
| 4.4375
| 4
|
def add_time(start, duration, day= None):
"""
Write a function named add_time that takes in two required parameters and one optional parameter:
- a start time in the 12-hour clock format (ending in AM or PM)
- a duration time that indicates the number of hours and minutes
- (optional) a starting day of the week, case insensitive
The function should add the duration time to the start time and return the result.
"""
# setting up lookup tables
AM_PM_dic = {"AM":0 , "PM":1}
AM_PM_keys_list = list(AM_PM_dic.keys())
days_dic = {"monday":0 , "tuesday":1 , "wednesday":2 , "thursday":3 , "friday":4 , "saturday":5 , "sunday":6}
days_dic_key_list = list(days_dic.keys())
# extracting information from arguments
eingabe = start.split()
zeit = eingabe[0].split(":")
hours_start = int(zeit[0])
minutes_start = int(zeit[1])
AM_PM_start = AM_PM_dic[eingabe[1]]
if day != None:
day_start = days_dic[day.lower()]
# extracing information from "duration"
zeit_add = duration.split(":")
hours_add = int(zeit_add[0])
minutes_add = int(zeit_add[1])
# implementing calculation formula
minutes_after_addition = divmod(minutes_start + minutes_add, 60)
hours_after_addition = divmod(hours_start + hours_add + minutes_after_addition[0] , 12)
hours_result = hours_after_addition[1]
if hours_after_addition[1] == 0:
# so that there is 12:04 AM and not 00:04 AM
hours_result = 12
full_12_cicles = hours_after_addition[0]
minutes_result = str(minutes_after_addition[1]).zfill(2) #zfill(2) displays 12:04 instead of 12:4
AM_PM_result = AM_PM_keys_list[(AM_PM_start+full_12_cicles)%2]
full_days_later = (full_12_cicles + AM_PM_start)//2
"""generating output"""
# a day-argument is given
if day != None:
if full_days_later == 0:
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day
if full_days_later == 1:
day_result = days_dic_key_list[(day_start + full_days_later)%7].capitalize()
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day_result + " (next day)"
if full_days_later > 1:
day_result = days_dic_key_list[(day_start + full_days_later)%7].capitalize()
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + ", " + day_result + " (" + str(full_days_later) +" days later" +")"
# no day-argument given
if day == None:
if full_days_later == 0:
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result
if full_days_later == 1:
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + " (next day)"
if full_days_later > 1:
new_time = str(hours_result) + ":" + minutes_result + " " + AM_PM_result + " (" + str(full_days_later) +" days later" +")"
return new_time
| true
|
e4fc4b53e49fb44be9d4f1a0879948264fbf635d
|
prasannarajaram/python_programs
|
/palindrome.py
| 340
| 4.6875
| 5
|
# Get an input string and verify if it is a palindrome or not
# To make this a little more challenging:
# - Take a text input file and search for palindrome words
# - Print if any word is found.
text = raw_input("Enter the string: ")
reverse = text[::-1]
if (text == reverse):
print ("Palindrome")
else:
print ("Not Palindrome")
| true
|
f993283ec857e4843cc6ea403a19b95669c2d437
|
paulacaicedo/TallerAlgoritmos
|
/ejercicio35.py
| 800
| 4.125
| 4
|
#EJERCICIO 35
numero_1=int(input("Introduzca un primer valor: "))
numero_2=int(input("Introduzca un segundo valor: "))
numero_3=int(input("Introduzca un tercer valor: "))
#NUMERO MAYOR
if numero_1>numero_2 and numero_1>numero_3:
print("El numero mayor es: ",numero_1)
if numero_2>numero_1 and numero_2>numero_3:
print("El numero mayor es: ",numero_2)
if numero_3>numero_1 and numero_3>numero_2:
print("El numero mayor es: ",numero_3)
else:
print("Todos son iguales")
#NUMERO MENOR
if numero_1<numero_2 and numero_1<numero_3:
print("El numero menor es: ",numero_1)
if numero_2<numero_1 and numero_2<numero_1:
print("El numero menor es: ",numero_2)
else:
numero_3<numero_1 and numero_3<numero_2
print("El numero menor es: ",numero_3)
| false
|
9fbf936bdf5c6f4798aa4ce97146394de3dadc40
|
evanmiracle/python
|
/ex5.py
| 1,230
| 4.15625
| 4
|
my_name = 'Evan Miracle'
my_age = 40 #comment
my_height = 72 #inches
my_weight = 160 # lbs
my_eyes = 'brown'
my_teeth = 'white'
my_hair = 'brown'
# this works in python 3.51
print("Test %s" % my_name)
# the code below only works in 3.6 or later
print(f'Lets talk about {my_name}.')
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on coffee.")
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
# code for earlier versions of python
print('Lets talk about %s' % my_name)
print("He's %s inches tall." % my_height)
print("He's %s pounds heavy." % my_weight)
print("Actually that's not too heavy.")
# multples seem only to work when explicit
print("He's got" , my_eyes, "eyes and",my_hair, "hair.")
# This should work too
print("He's got %s eyes and %s hair." %(my_eyes, my_hair) )
print("His teeth are usually %s depending on coffee." % my_teeth)
total = my_age + my_height + my_weight
print("If I add", my_age, my_height, my_weight, "I get", total)
| true
|
5204daaef67721495cd2bf137d21ff70c374b393
|
adeshshukla/python_tutorial
|
/loop_for.py
| 719
| 4.15625
| 4
|
print()
print('--------- Nested for loops---------')
for i in range(1,6):
for j in range(1,i+1):
print(j, end=' ') # to print on the same line with space. Default it prints on next line.
#print('\t')
print()
print('\n') # to print two lines.
print('-------- For loop In a tuple with break ----------------')
# for i in (1,2,3,4,5,6,7,8): # this is also good
tuple = (1,2,3,4,5,6,7,8)
for i in tuple:
if i==5:
print(' 5 found in the list... Now breaking out...!!!!')
break
print('\n')
print('---------- For loop In a list with continue --------------')
#list=['Adesh',28,1094.67,'IRIS','Angular',2,142]
for i in ['Adesh',28,1094.67,'IRIS','Angular',2,142]:
if i=='IRIS':
continue
print(i)
print('\n')
| true
|
ca0e358ea678b2c375709e2efb286194b58cc697
|
Annie677/me
|
/week3/exercise3.py
| 2,483
| 4.40625
| 4
|
"""Week 3, Exercise 3.
Steps on the way to making your own guessing game.
"""
import random
def not_number_rejector(message):
while True:
try:
your_input = int(input(message))
print("Thank you, {} is a number.".format(your_input))
return your_input
except:
print ("that is not a number. Please try again.")
def advancedGuessingGame():
"""Play a guessing game with a user.
The exercise here is to rewrite the exampleGuessingGame() function
from exercise 3, but to allow for:
* a lower bound to be entered, e.g. guess numbers between 10 and 20
* ask for a better input if the user gives a non integer value anywhere.
I.e. throw away inputs like "ten" or "8!" but instead of crashing
ask for another value.
* chastise them if they pick a number outside the bounds.
* see if you can find the other failure modes.
There are three that I can think of. (They are tested for.)
NOTE: whilst you CAN write this from scratch, and it'd be good for you to
be able to eventually, it'd be better to take the code from exercise 2 and
merge it with code from excercise 1.
Remember to think modular. Try to keep your functions small and single
purpose if you can!
"""
print("Welcome to the guessing game!")
print("Please guess a number between _ and _?")
lower_bound = not_number_rejector("Enter a lower bound: ")
upper_bound = not_number_rejector("Enter an upper bound: ")
while lower_bound >= upper_bound:
lower_bound = not_number_rejector("Enter a lower bound: ")
upper_bound = not_number_rejector("Enter an upper bound: ")
print("Great, a number between {lower} and {upper}.".format(lower=lower_bound,
upper=upper_bound))
guess_number = not_number_rejector("Guess a number: ")
actualNumber = random.randint(lower_bound, upper_bound)
while True:
print("Your number is {},".format(guess_number))
if guess_number == actualNumber:
print("It was {}".format(actualNumber))
return "You got it!"
elif guess_number < actualNumber:
print("Too small. Please try again.")
guess_number = not_number_rejector("Guess a number: ")
if guess_number > actualNumber:
print("Too big.Please try again.")
guess_number = not_number_rejector("Guess a number: ")
if __name__ == "__main__":
print(advancedGuessingGame())
| true
|
10054b21be49bc24ea3b3772c97c116bf425533b
|
L51332/Project-Euler
|
/2 - Even Fibonacci numbers.py
| 854
| 4.125
| 4
|
'''
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
'''
def even_fibonacci_sum_below(cutoff_number):
fib_list = [1,1]
sum = 0
next_term = 2
while next_term < cutoff_number:
if next_term % 2 == 0 and next_term < cutoff_number:
sum += next_term
fib_list.append(next_term)
next_term = fib_list[-1] + fib_list[-2]
#print("fiblist: " + str(fib_list))
print("sum: " + str(sum))
even_fibonacci_sum_below(4000000)
# Note: the fib_list variable could be modified to only keep track of the last two terms of the sequence to minimize space complexity
| true
|
ed2527878b79f75db82f16c90f223922834bd933
|
Joyojyoti/intro__to_python
|
/using_class.py
| 618
| 4.21875
| 4
|
#Defining a class of name 'Student'
class Student:
#defining the properties that the class will contain
def __init__(self, name, roll):
self.name = name
self.roll = roll
#defining the methods or functions of the class.
def get_details(self):
print("The Roll number of {} is {}.".format(self.name, self.roll))
#Creating the instance of class Student
stdnt1 = Student('Alexa',1234)
stdnt2 = Student('Joy',1235)
#Here Calling the functions of the class
stdnt2.get_details()
stdnt1.get_details()
"""The output will be like:
The Roll number of Joy is 1235.
The Roll number of Alexa is 1234. """
| true
|
864a01eb4152e25e30a64bbbaafa2385f0e9fea4
|
zbs881314/Deeplearning
|
/regression4LP.py
| 848
| 4.28125
| 4
|
# Linear regression example: linear prediction
# for Lecture 7, Exercise 7.2
import numpy as np
import matplotlib.pyplot as plt
## generated training data set with model x(i)=a x(i-1)+ e(i)
N=5000 # total number of training data
a=0.99
ei=np.random.randn(N)*np.sqrt(0.02) # generate e(n)
xi=np.zeros((N),dtype=np.float)
for i in range(N):
if i==0:
xi[i]=ei[i]
else:
xi[i]=a*xi[i-1]+ei[i]
## LMS algorithm to estimate a as w
w=0.0
eta=0.001
err=np.zeros((N),dtype=np.float) # save E(n) to draw learning curve
for i in range(N):
if i==0: continue
err[i]=xi[i]-w*xi[i-1]
w=w+eta*err[i]*xi[i-1]
## output results and draw learning curve
print("Ture value a = %f. Learned value w= %f." %(a,w))
plt.plot(np.arange(N), np.square(err),'b-'), plt.grid(True),
plt.xlabel('Iteration n'), plt.ylabel('MSE'), plt.show()
| false
|
0df7f56ad62d036dee1dc972a5d35984cfebcbec
|
snpushpi/P_solving
|
/preorder.py
| 1,020
| 4.1875
| 4
|
'''
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def generate_tree(preorder_list):
if len(preorder_list)==0:
return None
node = TreeNode(preorder_list[0])
for i in range(1, len(preorder_list)):
if preorder_list[i]>preorder_list[0]:
node.left = generate_tree(preorder_list[:i])
node.right = generate_tree(preorder_list[i:])
return node
node.left = generate_tree(preorder_list[1:])
node.right = generate_tree([])
return node
| true
|
c4cd3e7b687b65968f2863e2e19fb4fa303d4612
|
snpushpi/P_solving
|
/1007.py
| 1,356
| 4.125
| 4
|
'''
In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the i-th domino, so that A[i] and B[i] swap values.
Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.
If it cannot be done, return -1.
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
'''
def domino(A,B):
if len(A)!=len(B):
return -1
marker_set = {A[0], B[0]}
for i in range(1,len(A)):
track_set = marker_set.copy()
for elt in track_set:
if elt not in {A[i], B[i]}:
marker_set.remove(elt)
if len(marker_set)==0:
return -1
if len(marker_set)==1:
elt = marker_set.pop()
return min(len(A)-A.count(elt),len(B)-B.count(elt))
if len(marker_set)==2:
elt1= marker_set.pop()
elt2 = marker_set.pop()
return min(len(A)-A.count(elt1), len(A)-A.count(elt2), len(B)-B.count(elt1), len(B)-B.count(elt2))
print(domino([2,1,2,4,2,2],[5,2,6,2,3,2]))
| true
|
602dd4b4552f050d3e799cc9bc76fc3816f40358
|
snpushpi/P_solving
|
/next_permut.py
| 1,499
| 4.1875
| 4
|
'''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
'''
def next_permutation(num_list):
l = len(num_list)
inc_index = 0
strictly_decreasing = True
strictly_increasing = True
for i in range(1,l-1):
if num_list[i-1]<=num_list[i] and num_list[i]>=num_list[i+1]:
inc_index=i
for i in range(l-1):
if num_list[i]<num_list[i+1]:
strictly_decreasing = False
if num_list[i]>num_list[i+1]:
strictly_increasing = False
print(strictly_decreasing, strictly_increasing)
if not strictly_decreasing and not strictly_increasing:
swap = num_list[inc_index]
num_list[inc_index]=num_list[inc_index-1]
num_list[inc_index-1]=swap
elif strictly_decreasing:
for i in range(int(l/2)):
swap = num_list[i]
num_list[i]=num_list[l-1-i]
num_list[l-1-i]=swap
else:
print('hi')
swap = num_list[l-1]
num_list[l-1]=num_list[l-2]
num_list[l-2]=swap
return num_list
print(next_permutation([1,2,3]))
| true
|
82d7b5ebca2d850aea48cc1a4719ef53f7bd09de
|
snpushpi/P_solving
|
/1041.py
| 1,536
| 4.25
| 4
|
'''
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
Example 2:
Input: "GG"
Output: false
Explanation:
The robot moves north indefinetely.
Example 3:
Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Note:
1 <= instructions.length <= 100
instructions[i] is in {'G', 'L', 'R'}
'''
def boundedRobot(instructions):
directions = [[0,1],[1,0],[0,-1],[-1,0]]
direct = 0
start_point = [0,0]
new_instructions = ''
for i in range(4):
new_instructions+=instructions
for instruction in new_instructions:
if instruction=='L':
direct = (direct+3)%4
elif instruction=='R':
direct = (direct+1)%4
else:
start_point[0]+=directions[direct][0]
start_point[1]+=directions[direct][1]
if start_point==[0,0]:
return True
else:
return False
print(boundedRobot("GL"))
| true
|
9b6d023f110699aee047ab231e17a18989abd40d
|
snpushpi/P_solving
|
/search.py
| 906
| 4.15625
| 4
|
'''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
'''
def search(nums, target):
left, right = 0, len(nums)-1
mid = int((left+right)/2)
wwhile left<=right:
if nums[mid]==target:
return mid
elif nums[left]<nums[mid]:
if nums[left]<target<nums[mid]:
right=mid-1
else:
left=mid+1
elif nums[mid]<nums[left]:
if nums[mid]<target<=nums[right]:
left = mid+1
else:
right=mid-1
else:
left+=1
| true
|
b6f17ceaebb3d8e846272eff1313a09e13cefe84
|
Zahidsqldba07/codesignal-20
|
/FamilyGroup.py
| 2,338
| 4.375
| 4
|
# -*- coding: utf-8 -*-
"""
We’re working on assembling a Game of Thrones family tree.
Example:
Mad King Rickard
/ \ / \
Daenerys Rhaegar Lyanna Ned Catelyn
\ / \ /
Jon Arya
Write a function that returns three collections:
-People who have no parents represented in our data
-People who only have 1 parent represented
-People who have 2 parents represented
Sample input:
familyGroups = [
(‘Ned’, ‘Arya’), (‘Rhaegar’, ‘Jon’), (‘Lyanna’, ‘Jon’), (‘Catelyn’, ‘Arya’),
(‘Mad King’, ‘Rhaegar’), (‘Rickard’, ‘Lyanna’), (‘Mad King’, ‘Daenerys’), (‘Rickard’, ‘Ned’)]
Sample output:
[‘Daenerys’, ‘Rhaegar’, ‘Lyanna’, ‘Ned’], -- One parent
[[‘Mad King’, ‘Rickard’, Catelyn], -- No parents
[‘Jon’, ‘Arya’]] -- Two parents
{'Arya' = 1,
'Jon' = 2,
'Lyanna' = 1}
"""
family_groups = [
("Ned", "Arya"), ("Rhaegar", "Jon"), ("Lyanna", "Jon"), ("Catelyn","Arya"),
("Mad King", "Rhaegar"),("Rickard", "Lyanna"), ("Mad King", "Daenerys"),
("Rickard", "Ned")]
def familyGroup(data):
dict_Counter = {}
#Seperate parents from Children by index
parent_SetContainer = set()
children_SetContainer= set()
# Populate arrarys with parent groups
people_with_one_parent= []
people_with_two_parent= []
for group in data:
parent_SetContainer.add(group[0])
children_SetContainer.add(group[1])
if group[1] in dict_Counter.keys():
dict_Counter[group[1]] += 1
else:
dict_Counter[group[1]] = 1
# Results of dict_Counter shows the count of people's Parents
# print('Show dict_Counter results :' + str(dict_Counter) + '\n')
# Subtract parent - chilren 'sets' to get
# people who have no parents represented in our data results
diff_between_groups = parent_SetContainer - children_SetContainer
# print(str(dict_Counter.items()) + '\n')
for key, value in dict_Counter.items():
if value ==1 :
people_with_one_parent.append(key)
else:
people_with_two_parent.append(key)
return [people_with_one_parent,people_with_two_parent,list(diff_between_groups)]
# print(familyGroup(family_groups))
| false
|
b9401748ab04808e5587cec3d3280ae95a10752b
|
Guimbo/Pesquisa_Ordenacao
|
/Heap Sort.py
| 1,213
| 4.21875
| 4
|
#Heap Sort
#Princípio: Utiliza uma estrutura de dados chamada heap, para ordenar os elementos
#à medida que os insere na estrutura. O heap pode ser representado como uma árvore
#ou como um vetor.
#Complexidade no melhor e no pior caso: O(n log2n) é o mesmo que O(n lgn)
from RandomHelper import random_list
def heapSort(lista):
#Função que implementa o método de ordenamento Heap Sort.
def selet(inicio, contador):
raiz = inicio
while raiz * 2 + 1 < contador:
filho = raiz * 2 + 1
if filho < contador - 1 and lista[filho] < lista[filho + 1]:
filho += 1
if lista[raiz] < lista[filho]:
lista[raiz], lista[filho] = lista[filho], lista[raiz]
raiz = filho
else:
return
contador = len(lista)
inicio = contador // 2 - 1
fim = contador - 1
while inicio >= 0:
selet(inicio, contador)
inicio -= 1
while fim > 0:
lista[fim], lista[0] = lista[0], lista[fim]
selet(0, fim)
fim -= 1
return lista
print("Lista Ordenada (Heap Sort):")
print(heapSort(random_list(20)))
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.