blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5657687ff5fd3a24269241833c650ef87d2bd8d0 | biswaranjanroul/Python-Logical-Programms | /Fresher Lavel Logical Programms/Python program to check if a string is palindrome or not.py | 596 | 4.21875 | 4 | #using sRting Built in function
'''str=input("Enter a string:")
if str[::-1]==str:
print('it is a palindrom')
else:
print("it is not palindrom")'''
#function With reverse string
'''def reverse(s):
return s[::-1]
def ispalindrome(s):
rev=reverse(s)
if s==rev:
return True
return False
s="malayalam"
ans=ispalindrome(s)
if ans==1:
print("yes")
else:
print("No")'''
# using loop
str=input("Enter a string: ")
rev=""
for i in str:
rev=rev+i
if (rev==str):
print("It is palindroim")
break
else:
print("it is not a palindroim")
| false |
968ec4600f28007d7a84b5068b7d2b185f6f684f | olafironfoot/CS50_Web | /Lectures/Lecture4/src4/Testing and questions for classes4.py/TestingClass.py | 2,009 | 4.4375 | 4 | # class User:
# def __init__ (self, full_name, birthday):
# self.name = full_name
# self.birthday = birthday
#
# #Can assign a variable to store infomation within a class User()
# Thisperson = User("Dave", 192832)
#
# print(Thisperson.name, Thisperson.birthday)
#
# #this needs to be assigned, otherwise just spits out the memory space it's stored
# print(User("blah", 123891))
#def __repr__(self):
# return "<__main__.User: =" + str(self.full_name) + ">"
class Flight:
"""docstring for Flight."""
counter = 1
def __init__(self):
self.id = Flight.counter
Flight.counter += 1
self.passengers = []
#creating a function that adds Passengers
def add_passenger(self, p):
self.passengers.append(p)
p.flight_id = self.id
#p.flight_id = Flight.counter
def print_info(self):
# for passenger in self.passengers:
# print(f"Passenger name: {passenger.name} \n Flight ID: {passenger.flight_id}")
print(self.passengers)
#Question: Why doesn't print(self.passengers) work like print(list) below? print(self.passengers) returns a memory address instead of a list.
#Question1(Answered1), if both are list, why does one return the list and the other the memory address?
#because the list was in the function, "print_info" under the class flight. when moved to the main code, it was able to print the list.
#in order to print the list self.passengers
#Question: how to print the "self.passengers = []" list?
# print(f"Passenger name: {self.passengers} \n Flight ID: {passengers.flight_id}")
#recreating class
class Passenger:
def __init__ (self, name):
self.name = name
#after all definitions, execute the code
def main():
f1 = Flight()
michael = Passenger(name = "MichaelScott")
f1.add_passenger(michael)
f1.print_info()
list = [1, 2, 3]
print(list)
if __name__ == "__main__":
main()
| true |
c501f289e485673870ab507cde6938e037fd20ee | gerardogtn/matescomputacionales | /matescomputacionales/project02/recursive_definitions.py | 1,790 | 4.21875 | 4 | """ All strings used as patterns in a recursive definition"""
patternStrings = ['u', 'v', 'w', 'x', 'y', 'z']
def getAllCombinationsForStep(step, combinations, out):
"""" Given a single recursive definition and all possible combinations to fill
each pattern with, return all possible combinations
Keyword arguments:
step -- a string representing a single recursive definition
combinations -- a python set containing all possible combinations until N
out -- a python set (initially empty) that accumulates all possible combinations
for the current step
"""
patternsInStep = filter(lambda x: x in patternStrings, step)
if not patternsInStep :
out.add(step)
else:
for c in combinations:
getAllCombinationsForStep(step.replace(patternsInStep[0], c), combinations, out)
return out
def getStringsUntilNRecursiveStep(baseCases, recursiveSteps, N, callback=(lambda n, x: x)):
""" Get all the strings formed until N recursive steps
Keyword arguments:
baseCase -- a list of BaseRecursiveString defining the base case of the language.
recursiveSteps -- a set of RecursiveString indicating the valid strings.
N -- number of recursive steps to perform
onStringsAtStep -- A function (Set<RecursiveString> -> Void) executed every time
a recursive step occurs.
"""
n = 0
allStrings = set()
allStrings = allStrings.union(baseCases)
callback(n, allStrings)
while n < N:
current = set()
for step in recursiveSteps:
current = current.union(getAllCombinationsForStep(step, allStrings, set()))
callback(n + 1, current - current.intersection(allStrings))
allStrings = allStrings.union(current)
n = n + 1
return allStrings
| true |
5a6110d12a5f4882796302209952a91cfc3d43b1 | IvanJeremiahAng/cp1404practicals | /prac_03/lecture ex.py | 488 | 4.15625 | 4 | min_age = 0
max_age = 150
valid_age = False
while not valid_age:
try:
age = int(input("Enter your age: "))
if min_age <= age <= max_age:
valid_age = True
else:
print("Age must be 0 - 150 inclusive.")
except ValueError as e:
print("Age must be an integer")
if age % 2:
print("Your age is odd")
else:
print("Your age is even")
print("You are {} years old this year and will be {} next year.".format(age, age + 1))
| true |
144373f5a1545d765447e2b1557e9d92361a02ea | MightyElemental/SoftwareOne | /Week Four/turtlefunctionstemplate.py | 1,916 | 4.40625 | 4 | '''
Created on 24 Jul 2020
@author: Lilian
'''
import time
import turtle
import math
my_turtle = turtle.Turtle()
my_turtle.showturtle()
#################### WRITE YOUR CODE BELOW #########################
# ---- Question 1 ----
# design a function draw_triangle to draw a triangle. Using this function and a for loop, draw the following image
# Ensure Turtle is facing up
my_turtle.setpos(0,0)
my_turtle.seth(90)
def draw_triangle(radius: int):
side_len = 2*radius*math.cos(math.radians(30))
my_turtle.penup()
my_turtle.forward(radius)
my_turtle.left(150)
my_turtle.pendown()
for i in range(3):
my_turtle.forward(side_len)
my_turtle.left(360/3)
my_turtle.penup()
my_turtle.right(150)
my_turtle.back(radius)
my_turtle.pendown()
# ---- Question 2 ----
# design a function draw_polygon to draw a regular polygon. Using this function, you should be able to draw triangles, squares, pentagon, exagon and so on.
def draw_polygon(sides: int, side_len: int):
for i in range(sides):
my_turtle.forward(side_len)
my_turtle.left(360/sides)
# ---- Question 3 ----
# design a function draw_star to draw a star with six branches. Using this function and a for loop, draw the following image
def draw_star(size: int):
draw_triangle(size)
my_turtle.left(180)
draw_triangle(size)
my_turtle.left(180)
for i in range(20, 230, 25):
draw_triangle(i)
time.sleep(4)
my_turtle.clear()
for i in range(3,12):
draw_polygon(i,15+i*5)
time.sleep(4)
my_turtle.clear()
for i in range(0, 5, 1):
draw_star(250*(0.4**i))
#################### WRITE YOUR CODE ABOVE THIS LINE #########################
#################### IGNORE CODE BELOW #########################
## Must be the last line of code
my_turtle.screen.exitonclick()
| false |
f22ee0714af9a4727ee3311b5a15ee083e004c76 | urjits25/leetcode-solutions | /LC92.py | 1,880 | 4.125 | 4 | '''
REVERSE LINKED LIST II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
'''
def reverseBetween(head: ListNode, m: int, n:int) -> ListNode:
'''
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
'''
# Function to reverse a subList
# Returns the ListNode after the end of subList
def reverseList(start: ListNode, end:ListNode) -> ListNode:
l1 = start
l2 = start.next
while l1 != end: # ---- Classic Link Reversal
l3 = l2.next
l2.next = l1
l1, l2 = l2, l3
return l2
dummy = ListNode(0) # ---- Dummy head to handle edge case
dummy.next = head
l1 = dummy
start = head
while m-1: # ---- Seek to start of subList
if not m-2: # ---- (m-1)th ListNode
l1 = start
start, m, n = start.next, m-1, n-1
end = start
while n-1: # ---- Seek to end of subList
end, n = end.next, n-1
l2 = end.next # ---- (n+1)th node
reverseList(start, end) # ---- Reverse subList in-place
if l1 == dummy: # ---- If subList starts from first ListNode, start from reversed
head = end
else:
l1.next = end
start.next = l2 # ---- Last node from Reversed sublist points to (n+1)th node
return head
| true |
cd4f1bd46e15ca494d59ca9650839d313f51847b | urjits25/leetcode-solutions | /LC53.py | 758 | 4.1875 | 4 | '''
MAXIMUM SUBARRAY
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
'''
# Dynamic Programming, Time : O(N); Space: O(N)
# Better solution (O(1) space): https://leetcode.com/problems/maximum-subarray/discuss/20194, Explanation: https://youtu.be/2MmGzdiKR9Y
def maxSubArray(nums: List[int]) -> int:
sum_array = [nums[0]]
for i in range(1, len(nums)):
sum_array.append(max(nums[i], nums[i] + sum_array[-1]) ) # ---- Start a new subarray OR Add new element to previous subarray
return max(sum_array) # ---- Maximum sum from corresponding subarrays
| true |
58c93fd24db3aadf5899654ba7f63b724ae96bd3 | rubleen1903/Python-BubbleSort | /sort.py | 413 | 4.28125 | 4 | # Creating a bubble sort function
def bubblesort(lista):
#outer for loop
for i in range(0,len(lista)-1):
for j in range(len(lista)-1):
if(lista[j]>lista[i]):
temp = lista[j]
lista[j]=lista[j+1]
lista[j+1]=temp
return lista
lista=[12,42,8,33,15]
print("The unsorted list is : ",lista)
print("The sorted list is",bubblesort(lista))
| true |
0d79d97a228c8e133511f3d6d10a4fa9af1c7a12 | LeenaKH123/Python2 | /02_more-datatypes/02_14_char_count_dict.py | 347 | 4.25 | 4 | # Write a script that takes a text input from the user
# and creates a dictionary that maps the letters in the string
# to the number of times they occur. For example:
#
# user_input = "hello"
# result = {"h": 1, "e": 1, "l": 2, "o": 1}
x = input("type your string without spaces ")
freq = {}
for c in set(x):
freq[c] = x.count(c)
print(freq)
| true |
6c01755380160bfc34cb1067e9c2d05546b336d9 | LeenaKH123/Python2 | /02_more-datatypes/02_10_pairing_tuples.py | 871 | 4.40625 | 4 | # The import below gives you a new random list of numbers,
# called `randlist`, every time you run the script.
#
# Write a script that takes this list of numbers and:
# - sorts the numbers
# - stores the numbers in tuples of two in a new list
# - prints each tuple
#
# If the list has an odd number of items,
# add the last item to a tuple together with the number `0`.
#
# Note: This lab might be challenging! Make sure to discuss it
# with your mentor or chat about it on our forum.
from resources import randlist
print(randlist)
# Write your code below here
import random
randlist = []
for i in range(0, 10):
num = random.randint(1, 30)
randlist.append(num)
print(randlist)
randlist.sort()
print(randlist)
# lst_tuple = [x for x in zip(*[iter(randlist)])]
# print(lst_tuple)
lst_tuple = [x for x in zip(*[iter(randlist)] * 2)]
print(lst_tuple)
| true |
21f4c5fdebc4f4ecb80f42d20e364ca29b276377 | LeenaKH123/Python2 | /04_functions-and-scopes/04_10_type_annotations.py | 692 | 4.21875 | 4 | # Add type annotations to the three functions shown below.
# type annotations are also known as type signatures and they are used to indicate the data type of variables and the input
# and output of functions and methods in a programming language
# static type: performs type checking at compile-time and requires datattype declarations
# dynamic type: performs type checking at runtime and does not require datatype declarations
def multiply(num1: int, num2: int):
return num1 * num2
def greet(greeting: str, name: str):
sentence = f"{greeting}, {name}! How are you?"
return sentence
def shopping_list(*args: str):
[print(f"* {item}") for item in args]
return args
| true |
9bfea5d550eb6f62ad3dff93d63fa4f6058f28ee | uabua/rosalind | /bioinformatics-stronghold/rabbits-and-recurrence-relations/fib.py | 689 | 4.25 | 4 | """
ID: FIB
Title: Rabbits and Recurrence Relations
URL: http://rosalind.info/problems/fib/
"""
def count_rabbits(month, pair):
"""
Counts the total number of rabbit pairs that will be present after n(month) months, if we begin with 1 pair and
in each generation, every pair of reproduction-age rabbits produces a litter of k(pair) rabbit pairs
(instead of only 1 pair).
Args:
month (int): number of months.
pair (int): number of pairs.
Returns:
int: the total number of rabbit pairs.
"""
if month == 1 or month == 2:
return 1
else:
return count_rabbits(month-1, pair) + count_rabbits(month-2, pair) * pair
| true |
9061b877b160147aa4ad5a49172dafebd6d1db64 | Faresa/debugging-and-testing | /calendar_utils.py | 2,704 | 4.25 | 4 | # Mphephu Faresa
# CSC1010H
def is_leap_year(year) :
#code for leap year
a =year%4
b =year%100
c = year%400
if a==0 :
if b == 0 :
if c==0 : return True
else : return False
if b!=0 : return True
else: return False
def month_name(number) :
month = {1:"January",2:"February",3 :'March' , 4:"April" , 5:"May" , 6:"June" , 7:"July",8:"August",9:"September",10:"October",11:'November',12:"December"}
return month[number]
#Given the number of a month, returns the corresponding name. 1 is January, ..., 12 is December.
def days_in_month(month_number,year) :
month = month_name(month_number)
#print(month)
if month in {"January" , "March" , "May" ,'July' ,'August' , 'October' , "December" }:
return 31
elif month in {"April", "June" ,"September" ,"November" }: return 30
elif is_leap_year(year) == True and month_number == 2 : return 29
elif month_number == 2 : return 28
#Given month (in the form of a number) and (4 digit) year, return the number of days in the month (accounting, in the case of February, for whether or not it is a leap year).
def first_day_of_year(year) :
z =(year-1)%4
x= (year-1)%100
v = (year-1)%400
calc = 5*z + 1 + 4*x + 6*v
return calc%7
def first_day_of_month(month_number, year) :
count = 0
days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6}
z =(year-1)%4
x= (year-1)%100
v = (year-1)%400
calc = 5*z + 1 + 4*x + 6*v
day = calc%7
#print(day)
sto = 1
for month in range(month_number) :
#print(month)
if month == 0 :
if is_leap_year(year) == True :
sto+=5
sto+= days_in_month(month+1,year)
#print(sto)
if month == 1 :
if is_leap_year(year) == False :
sto+=-1
day-=3
sto+= days_in_month(month+1,year)
#print("Month",month)
if is_leap_year(year) == True :
sto+=2
day+=2
sto+= days_in_month(month+1,year)
#print("Month Leap",month)
else :
sto+= days_in_month(month+1,year)
#print("Sto",sto)
for i in range(sto):
day +=1
if day >=7 : day = 0
# print("day",day)
return day
# Given a month (in the form of a number) and (4 digit) year, return the number of the day on which the first of that month falls. 0 is Sunday, , 6 is Saturday.
#def main():
# days_in_month(2,2016)
#main() | false |
a41367b78fab098494c13035c415c4394baf2a8c | mohammed-ysn/online-safety-quiz | /main.py | 2,929 | 4.125 | 4 | import random
import json
class Quiz:
def __init__(self):
# Store score
self.score = 0
# Store current question number
self.q_num = 0
# Read json file into dict
with open('quiz_data.json') as json_file:
self.quiz_data = json.load(json_file)
# Create list with question numbers
self.q_order = list(range(len(self.quiz_data['data_list'])))
random.shuffle(self.q_order)
self.show_title()
self.ask_username()
self.welcome_user()
self.display_instructions()
self.start_quiz()
self.display_score()
def show_title(self):
print('-' * 20)
print('Online safety quiz')
print('-' * 20)
print()
def ask_username(self):
self.username = input('Username: ')
print()
def welcome_user(self):
print(f'Welcome {self.username}!')
print()
def display_instructions(self):
print('-' * 20)
print('Instructions')
print('-' * 20)
print()
print('You will answer a series of questions regarding online safety. Each question is multiple choice. To denote your answer, enter the respective answer number (e.g. 2). Each correct answer scores you 4 points. Your score will be displayed at the end.')
print()
def start_quiz(self):
# Loop until all questions have been asked
while (self.q_num < len(self.q_order)):
self.display_q()
self.display_ans()
self.get_user_ans()
self.check_ans()
self.q_num += 1
def display_q(self):
print(self.quiz_data['data_list']
[self.q_order[self.q_num]]['question'])
def display_ans(self):
# Store list of answers
ans_list = self.quiz_data['data_list'][self.q_order[self.q_num]]['answers']
# Create the display order of answers
ans_order = list(
range(len(ans_list)))
random.shuffle(ans_order)
# Store the correct answer number
self.correct_ans = ans_order.index(0) + 1
# Display answers
for i, j in enumerate(ans_order):
print(f'{i + 1}. {ans_list[j]}')
print()
def get_user_ans(self):
# Loop until a number is entered
while(True):
try:
self.user_ans = int(input('Answer: '))
print()
break
except ValueError:
print('Invalid answer. Please input a number.')
print()
def check_ans(self):
if self.user_ans == self.correct_ans:
self.score += 4
def display_score(self):
print('-' * 20)
print('Score')
print('-' * 20)
print()
print(f'{self.username}, you scored: {self.score}')
if __name__ == "__main__":
quiz = Quiz()
| false |
7153eecf22609652b057f756a8aff5bd17c931a1 | NoroffNIS/Python_Examples | /src/week 2/day 2/while_loop_exit.py | 385 | 4.25 | 4 | what_to_do = ''
while what_to_do != 'Exit':
what_to_do = input('Type in Exit to quit, '
'or something else to continue: ')
if what_to_do == 'Exit':
print('You typed in Exit, program stopped')
elif what_to_do == 'exit':
print('You typed in Exit, loop break, program stopped')
break
else:
pass
print('Out of loop!') | true |
23a35831d935fef121dea84bd9c38b779bea44b1 | NoroffNIS/Python_Examples | /src/week 2/day 4/km_t_to_m_s.py | 708 | 4.125 | 4 |
def km_h_to_m_s():
print('You choose to convert km/t -> m/s')
km_h = float(input('Type in a km/h:'))
m_s = km_h * 0.2778
print(km_h, 'km/h = ', m_s,'m/s', sep='')
def m_s_to_km_h():
print('You choose to convert m/s -> km/t')
m_s = float(input('Type in a m/s:'))
km_h = m_s * 3.6
print(m_s, 'm/h = ', km_h, 'km/s', sep='')
def main():
print('What do you wan to do?')
user_choise = input('Type 1 for km/t -> m/s\n'
'Type 2 for m/s -> km/t\n>')
print('Your choise is:', user_choise)
if user_choise == '1':
km_h_to_m_s()
elif user_choise == '2':
m_s_to_km_h()
else:
print('You typed in wrong!')
main()
| false |
22048e72c64345b993e87c6183c1b0a31c257d7a | NoroffNIS/Python_Examples | /src/week 2/day 3/letter_count.py | 257 | 4.125 | 4 | word = input('Type in a word:').upper()
letter = input('Type in a letter you want to count:').upper()
count = 0
for l in word:
if l == letter:
count += 1
else:
pass
print('In you word', word, 'there is', count, 'letters of', letter) | true |
09d3553282f07aebe1220d22a9a614eea96c470d | maizzuu/ot-harjoitustyo | /src/entities/user.py | 534 | 4.15625 | 4 | class User:
"""Class that depicts a User.
Attributes:
username: String that represents the users username.
password: String that represents the users password.
"""
def __init__(self, username:str, password:str):
"""Class constructor that creates a new user.
Args:
username (str): String that represents the users username.
password (str): String that represents the users password.
"""
self.username = username
self.password = password
| true |
af23b5795bbb6d606222cc34ea0dc4088e9a81f0 | Salman42Sabir/Python3-Programming-Specialization | /Tuples_course_2_assessment_5.py | 1,704 | 4.40625 | 4 | # 1. Create a tuple called olympics with four elements: “Beijing”, “London”, “Rio”, “Tokyo”.
olympics = ("Beijing", "London", "Rio", "Tokyo")
print(olympics)
# 2. The list below, tuples_lst, is a list of tuples. Create a list of the second elements of each tuple and assign this list to the variable country.
tuples_lst = [('Beijing', 'China', 2008), ('London', 'England', 2012), ('Rio', 'Brazil', 2016, 'Current'), ('Tokyo', 'Japan', 2020, 'Future')]
country = []
for item in tuples_lst:
country.append(item[1])
print(country)
# 3. With only one line of code, assign the variables city, country, and year to the values of the tuple olymp.
olymp = ('Rio', 'Brazil', 2016)
city, country, year = olymp[0], olymp[1], olymp[2]
print(city)
print(country)
print(year)
# 4. Define a function called info with five parameters: name, gender, age, bday_month, and hometown. The function should then return a tuple
# with all five parameters in that order.
def info(name, gender, age, bday_month, hometown):
_tuple = name, gender, age, bday_month, hometown
return _tuple
info("Salman", "Male", 24, "Novemeber", "Pakistan")
# 5. Given is the dictionary, gold, which shows the country and the number of gold medals they have earned so far in the 2016 Olympics.
# Create a list, num_medals, that contains only the number of medals for each country. You must use the .items() method.
# Note: The .items() method provides a list of tuples. Do not use .keys() method.
gold = {'USA':31, 'Great Britain':19, 'China':19, 'Germany':13, 'Russia':12, 'Japan':10, 'France':8, 'Italy':8}
num_medals = []
for country, medals in gold.items():
num_medals.append(medals)
print(num_medals)
| true |
d3182b67f95423e2679d3b9b9c00b6c401ec3ceb | qiuyucc/pythonRoad | /Day1- 15/Day9 OOAdvanced/override.py | 1,531 | 4.15625 | 4 | #override, poly-morphism
# 子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override)。
# 通过方法重写我们可以让父类的同一个行为在子类中拥有不同的实现版本,
# 当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,这个就是多态(poly-morphism)。
from abc import ABCMeta, abstractmethod
class Pet(object,metaclass=ABCMeta):
"""PET
"""
def __init__(self,nickname):
self._nickname = nickname
@abstractmethod
def make_voice(self):
"""
make voice
:return:
"""
pass
class Dog(Pet):
"""狗"""
def make_voice(self):
print('%s: 汪汪汪...' % self._nickname)
class Cat(Pet):
"""猫"""
def make_voice(self):
print('%s: 喵...喵...' % self._nickname)
def main():
pets = [Dog('旺财'), Cat('凯蒂'), Dog('大黄')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
# 我们将Pet类处理成了一个抽象类,所谓抽象类就是不能够创建对象的类,这种类的存在就是专门为了让其他类去继承它。
# Python从语法层面并没有像Java或C#那样提供对抽象类的支持,
# # 但是我们可以通过abc模块的ABCMeta元类和abstractmethod包装器来达到抽象类的效果,如果一个类中存在抽象方法那么这个类就不能够实例化(创建对象) | false |
8ca4330f75344811b46435ec2b92cabdaf601e89 | omwaga/Python-loop-programs | /Factorial_of_a_Number.py | 501 | 4.1875 | 4 | """
Factorial is a non-negative integer.
It is the product of all positive integers less than or equal to that number for which you ask for factorial.
It is denoted by exclamation sign (!).
"""
num = int(input("Enter a number:"))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("The factorial of", num, "is", factorial) | true |
b1739be0b25eb2d1d4ec11c915e6243f2d51b242 | tedmik/classwork | /python-workbook/37.py | 613 | 4.375 | 4 | num_sides = int(input("How many sides does your shape have?: "))
if(num_sides == 3):
print("Your shape is a triangle")
elif(num_sides == 4):
print("Your shape is a square or rectangle")
elif(num_sides == 5):
print("Your shape is a pentagon")
elif(num_sides == 6):
print("Your shape is a hexagon")
elif(num_sides == 7):
print("Your shape is a heptagon")
elif(num_sides == 8):
print("Your shape is a octagon")
elif(num_sides == 9):
print("Your shape is a nonagon")
elif(num_sides == 10):
print("Your shape is a decagon")
elif(num_sides >= 10 or num_sides <= 3):
print("Not supported side amount")
| true |
34b2cc012e22fc7015c4058c2534e7be382a91b0 | imharshr/7thSemCSEnotes | /ML Lab/Sample Programs Assignment/samplePrograms.py | 263 | 4.3125 | 4 | tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
| true |
04bda63d98d93b8974566500024579a16631ae58 | iidyachenko/GB_Python_Kurs1 | /Lesson1/Ex5.py | 751 | 4.15625 | 4 | # Расчет экономической деятельности фирмы
revenue = int(input("Введите выручку фирмы: "))
cost = int(input("Введите издержки фирмы: "))
profit = revenue - cost
if profit > 0:
rent = (profit/revenue)*100
print("Ваша прибыль составила: ", profit)
print(f"Ваша рентабльность: {rent:.2f}%")
staff = int(input("Введите численость персонала: "))
staff_profit = profit / staff
print(f"Ваша прибыль на одного сотрудника составила: {staff_profit:.2f}")
else:
print("Выши расходы превышают доходы, ваш баланс: ", profit)
| false |
cca17409f94e59fee2a880609d828f6dad0deafa | iidyachenko/GB_Python_Kurs1 | /Lesson3/Ex1.py | 648 | 4.1875 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def division(a, b):
try:
return a / b
except ZeroDivisionError:
print("На ноль делить нельязя!")
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
print(f"{a} делить на {b} = {division(a, b)}")
| false |
53bcd34a0336d4aeb77d6cc619e63532dd13a2c6 | tylerharter/caraza-harter-com | /tyler/cs301/fall18/materials3/code/lec-06-functions/example17.py | 223 | 4.3125 | 4 | x = 'A'
def f(x):
x = 'B'
print('inside: ' + x)
print('before: ' + x)
f(x)
print('after: ' + x)
# LESSON 10: it's irrelevant whether the
# argument (outside) and parameter (inside)
# have the same variable name | false |
d2ca6150538c96deef484881d7271a20d02d1b48 | tylerharter/caraza-harter-com | /tyler/cs301/fall18/materials3/code/lec-07-conditionals-loops/code04_with_functions.py | 268 | 4.46875 | 4 | def is_positive_or_negative(num):
if num > 0:
return 'POSITIVE'
elif num < 0:
return 'NEGATIVE'
else:
return 'ZERO'
number = input('Enter a number: ')
number = int(number)
num_type = is_positive_or_negative(number)
print(num_type) | false |
e12ab5d88436f7882b3a3d5891f48b5d4a16a63f | tylerharter/caraza-harter-com | /tyler/cs301/fall18/materials3/code/lec-06-functions/example12.py | 261 | 4.25 | 4 | # show global frame in PythonTutor
msg = 'hello' # global, because outside any function
def greeting():
print(msg)
print('before: ' + msg)
greeting()
print('after: ' + msg)
# LESSON 5: you can generally just use
# global variables inside a function
| true |
b41de77e9bad479e1220a76ef543d66065cf5f27 | programmingwithjack/python_course | /variables.py | 365 | 4.1875 | 4 | # variable python
a=5 # int
b="hello" #string
print(a)
print(b)
# assign multiple variable
x,y,z="hello","world","good"
print(x)
print(y)
print(z)
# output variable
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = 5
y = 10
print(x + y)
# global varibale
# when function completed than explain global variable
| false |
ad15dbee9408784ef55eb62222df7b892febf92d | GitRAK07/my_python_programs_learning | /Documents/python/dictionary.py | 714 | 4.25 | 4 | ####### Dictionary ########
user = {
'name': 'Anand',
'Age': 26,
'occupation': 'Software Engineer'
}
print(user['name'],user['Age'])
print(user.get('age')) #Use get method to avoid the program throwing the errors.
print(user.get('Age', 90)) #Returns value 90 if Age value is not found in the dict.
print( 'name' in user.keys()) #Checks the value 'name' in the keys of the variable 'user' and returns boolean
print( 'name' in user.values()) #Checks the value 'name' in the values of the variable 'user' and returns boolean
print( 26 in user.values())
print(user.items()) #List the items of the dictionary.
user.popitem() #Removes the last item from the dictionary
user.update({'Ages':55})
print(user) | true |
d4ba1f5b6867e176f47a329ac2741275894bd62f | animesh2411/python-udacity-course-movies-app | /flower.py | 828 | 4.21875 | 4 | import turtle
def draw_square(some_turtle):
for i in range(1,3):
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
#drwa square
window=turtle.Screen()
window.bgcolor("white")
brad=turtle.Turtle()
brad.speed(3)
brad.shape("turtle")
brad.color("blue")
for i in range(1,37):
draw_square(brad)
brad.right(10)
#draw circle
#angie=turtle.Turtle()
#angie.shape("triangle")
#angie.color("yellow")
#angie.circle(100)
#draw triangle
#tom = turtle.Turtle()
#tom.color("blue")
#tom.shape("square")
#tom.forward(100)
#tom.left(120)
#tom.forward(100)
#tom.left(120)
#tom.forward(100)
window.exitonclick()
draw_art()
# brad angie and tom are instances or objects of the class Turtle
| false |
1d2df47f0beaf079e3e79b40ece8905592eb71bd | jblanco75/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 474 | 4.40625 | 4 | #!/usr/bin/python3
"""Function: print_square"""
def print_square(size):
"""Prints a square with '#'
'size' is the size length of the square
'size' must be an integer"""
if type(size) != int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
if size > 0:
for i in range(size):
print('#' * size)
else:
print()
| true |
488b87e2df6b9aef7780edaeb85b199d88882c07 | sadragw/projekt | /Kolikov A. E/02/les01_02.py | 2,025 | 4.3125 | 4 | # coding: utf-8
# Python. Быстрый старт.
# Занятие 2.
# Домашнее задание: в случае, если пользователь ввел Y, то придумать и вывести список действий,
# спросить, какое он хочет выполнить;
# ознакомиться с PEP8
import os
print("Great Python Program!")
print("Привет, программист!")
name = input("Ваше имя: ")
print(name, ", добро пожаловать в мир Python!")
answer = input("Давайте поработаем? (Y/N)")
# PEP-8 рекомендует делать отступ, равный 4 пробелам
if answer == 'Y' or 'y':
print("Отлично, хозяин!")# <- здесь будет код домашнего задания
print("Я умею:")
print(" [1] - сложу два числа")
print(" [2] - найду счастливое число")
print(" [3] - показать файлы формата .jpg")
print(" [4] - выведу имя операционной системы")
do = int(input("Укажите номер действия: "))
if do == 1:
a = int(input("Введите число a ="))
b = int(input("Введите число b ="))
print(" a + b = ", a + b )
if do == 2:
n = str(input())
n = int(n)
sum1 = n % 10 + (n %100)//10 + (n % 1000)//100
sum2 = (n // 1000) %10 + (n // 10000) %10 + n // 100000
if sum1 == sum2:
print('Счастливый')
else:
print('Обычный')
if do == 3:
files = [f for f in os.listdir() if f.endswith('.jpg')]
print(files)
if do == 4:
print(os.name())
# Оператор == (двойное равно) - это логический оператор сравнения
elif answer == 'N' or 'y':
print("До свидания!")
else:
print("Неизвестный ответ") | false |
7e5f9e75db1723f379b360afb8ed88937b3783e3 | RSP123/python_puzzles | /minus_duplicates.py | 436 | 4.21875 | 4 | # Program for removing duplicate element in tthe list using set
# function to remove the duplicates
def duplicate(input):
result = []
res = set(input) # Converting list to set
for i in res:
result.append(i)
return result
# Main
if __name__=="__main__":
input = [1, 2, 2, 3, 4, 8, 8, 7, 8, 9, 5]
print(type(input))
print("without duplicates",duplicate(input))
print(type(duplicate(input)))
| true |
c2eff0cf6036a8e991ff80e7acd9b69cac631a40 | RSP123/python_puzzles | /prime_num.py | 846 | 4.40625 | 4 | # This program check weather the given number is prime or not
# Function to check prime number
def prime_number(number):
# Returning False for number 1 and less then 1
if number == 2 or number == 1:
return True
elif number < 1 or number%2 == 0:
return False
else:
# Iterating from 2 to check the number is prime or not
for i in range(3, int((number/3))+1, 2):
if (number%i) == 0:
return False
return True
# Main function
def main():
number=int(input("Enter a number to check weather it is prime or not: "))
if number == 1:
print("It's neither prime nor composite !!!")
return None
if prime_number(number):
print("The given number => ", number, " is a prime number")
else:
print("The given number => ", number, " is not a prime number")
# Checks the program call name
if __name__ == '__main__':
main()
| true |
87e0ace6902aca39ce6e71a3c4b3ddb3456df7d0 | Yaseen315/pres-excercise | /yq-grace-exercise-logic1.py | 932 | 4.25 | 4 | """This is my random number generator, I have a few problems with it. The turns don't seem to be working properly- I want them to start from 1
and increase each turn. Also the print statements seem to not be coming out the way I want them. I also can't make the game finish."""
print "Random number generator"
from random import randint
answer = randint(1, 101)
turn = 0
while turn < 5:
print "Turn", turn
user_guess = int(raw_input("Guess a number between 1 and 100:"))
if user_guess == answer:
print "You got it right!"
print "You got my number in" + str(turn) + "turns"
else:
if user_guess < 1 or user_guess > 100:
print "Not in range"
turn += 1
elif user_guess > answer:
print "Too high"
turn += 1
elif user_guess < answer:
print "Too low"
turn += 1
if turn == 5:
print "Game Over." | true |
374f5b9459446d1c2dec30776fc2c8a13bda7a4b | MarRoar/Python-code | /00-sxt/02-shujujiegou/01-yinru/08_dequeue.py | 1,015 | 4.3125 | 4 | '''
双端队列
Deque() 创建一个空的双端队列
add_front(item) 从队头加入一个item元素
add_rear(item) 从队尾加入一个item元素
remove_front() 从队头删除一个item元素
remove_rear() 从队尾删除一个item元素
is_empty() 判断双端队列是否为空
size() 返回队列的大小
'''
class Deque(object):
def __init__(self):
self.items = []
def add_front(self, item):
'''从队头加入一个item元素'''
self.items.insert(0, item)
def add_rear(self, item):
'''从队尾加入一个item元素'''
self.items.append(item)
def pop_front(self):
'''从队头删除一个item元素'''
return self.items.pop(0)
def pop_rear(self):
'''从队尾删除一个item元素'''
return self.items.pop()
def is_empty(self):
'''判断双端队列是否为空'''
return len(self.items) == 0
def size(self):
'''返回队列的大小'''
return len(self.items) | false |
911831018533759e6ff2bf4fcca1caba1a88306c | MarRoar/Python-code | /00-sxt/02-shujujiegou/01-yinru/07_queue.py | 706 | 4.28125 | 4 | '''
队列的操作
Queue() 创建一个空的队列
enqueue(item) 往队列中添加一个item元素
dequeue() 从队列头部删除一个元素
is_empty() 判断一个队列是否为空
size() 返回队列的大小
'''
class Queue(object):
def __init__(self):
self.items = []
def enqueue(self, item):
'''往队列中添加一个item 元素'''
self.items.insert(0, item)
def dequeue(self):
'''从队列头部删除一个元素'''
return self.items.pop()
def is_empty(self):
'''判断一个队列是否为空'''
return len(self.items) == 0
def size(self):
'''返回队列的大小'''
return len(self.items)
| false |
f6f15763778e1c9adbeddba0956c1ab04fb40259 | alyson1907/CodeWars | /6-kyu/python/IsIntegerArray.py | 892 | 4.125 | 4 | # https://www.codewars.com/kata/52a112d9488f506ae7000b95/train/python
# Write a function with the signature shown below:
# def is_int_array(arr):
# return True
# returns true / True if every element in an array is an integer or a float with no decimals.
# returns true / True if array is empty.
# returns false / False for every other input.
def is_int_array(arr):
if type(arr) is not list: return False
return all((type(n) is int or (type(n) is float and n.is_integer())) for n in arr)
print(is_int_array([])) # True
print(is_int_array([1, 2, 3, 4])) # True
print(is_int_array([-11, -12, -13, -14])) # True
print(is_int_array([1.0, 2.0, 3.0])) # True
print(is_int_array([1, 2, None])) # False
print(is_int_array(None)) # False
print(is_int_array("")) # False
print(is_int_array([None])) # False
print(is_int_array([1.0, 2.0, 3.0001])) # False
print(is_int_array(["-1"])) # False
| true |
e50e1e88ce23c03852a7bbd34f703ce22bf6471b | rvsreeni/ACD_MDS_Python_Session-3_Assignment-3.3 | /ACD_MDS_Python_Session#3_Assignment#3.3.py | 307 | 4.21875 | 4 | # Program to print longest word
def longest_word(wdlist):
maxlen = 0
maxwd = ""
for wd in wdlist:
if len(wd) > maxlen:
maxwd = wd
maxlen= len(wd)
return(maxwd)
input_list = ['one','three','four','two']
print(longest_word(input_list))
| false |
aa54193adecee918fa5762535ffda5dd8470d6e1 | dancaps/python_playground | /cw_titleCase.py | 2,296 | 4.40625 | 4 | #!/use/bin/env python3
'''https://www.codewars.com/kata/5202ef17a402dd033c000009/train/python
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.
Arguments (Haskell)
First argument: space-delimited list of minor words that must always be lowercase except for the first word in the string.
Second argument: the original string to be converted.
Arguments (Other languages)
First argument (required): the original string to be converted.
Second argument (optional): space-delimited list of minor words that must always be lowercase except for the first word in the string. The JavaScript/CoffeeScript tests will pass undefined when this argument is unused.
Example
title_case('a clash of KINGS', 'a an the of') # should return: 'A Clash of Kings'
title_case('THE WIND IN THE WILLOWS', 'The In') # should return: 'The Wind in the Willows'
title_case('the quick brown fox') # should return: 'The Quick Brown Fox'
'''
def title_case(title, minor_words = ''):
t = title.title().split()
m = minor_words.lower().split()
if len(t) == 0:
return ''
for i in m:
for index in range(len(t)):
if i.title() in t[index]:
t[index] = i
t[0] = t[0].title()
return ' '.join(t)
#print(title_case('a clash of KINGS', 'a an the of'))
print(title_case('THE WIND IN THE WILLOWS', 'The In'))
#print(title_case('the quick brown fox'))
#print(title_case(''))
'''
Test.assert_equals(title_case(''), '')
Test.assert_equals(title_case('a clash of KINGS', 'a an the of'), 'A Clash of Kings')
Test.assert_equals(title_case('THE WIND IN THE WILLOWS', 'The In'), 'The Wind in the Willows')
Test.assert_equals(title_case('the quick brown fox'), 'The Quick Brown Fox')
''' | true |
1736446a61e22d6c931fd7ea09648771e545b743 | dancaps/python_playground | /cw_summation.py | 455 | 4.375 | 4 | #!/usr/bin/env python3
'''
https://www.codewars.com/kata/grasshopper-summation/train/python
Summation
Write a program that finds the summation of every number between 1 and num. The number will always be a positive
integer greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
'''
def summation(num):
value = 0
for n in range(num + 1):
value += n
return value
print(summation(8)) | true |
7602a619d5f9c3f16c886f59c1c70fdd134f2de3 | sonofmun/FK-python-course | /pyhum/pig_latin.py | 891 | 4.40625 | 4 | #! /usr/bin/env python3
# -*- coding: utf8 -*-
VOWELS = 'aeiouAEIOU'
def starts_with_vowel(word):
"Does the word start with a vowel?"
return word[0] in VOWELS
def add_ay(word):
"Add 'ay' at the end of the word."
return word + 'ay'
def convert_word(word):
"Convert a word to latin (recursive style)."
if not starts_with_vowel(word):
return convert_word(word[1:] + word[0])
return add_ay(word)
def convert_word_imperative(word):
"Convert a word to latin (imperative style)."
start = 0
end = ''
for i, char in enumerate(word):
if char not in VOWELS:
end += char
else:
start = i
break # break out of the loop
return add_ay(word[start:] + end)
def convert_text(text):
"Convert all words in a sentence to latin."
return ' '.join(convert_word(word) for word in text.split())
| true |
8669a1a2503e9546d1d8a3a0c0c9e309152133f3 | mstoiovici/module2 | /ch03_functions_importingModules/ch3_file1_Mariana_functions.py | 2,509 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 15:45:32 2018
@author: maria
"""
################################## task1 ###########################
def add_two_numbers():
number1=1
number2=2
result=number1+number2
#print(result)
print(str(number1)+" plus "+str(number2)+" is " +str(result))
print("{} plus {} is {}.".format(number1,number2,result))
return result
################################## task2 ###########################
def hello_world_2args(a,b):
print("{} {}".format(a,b))
################################## task3 ###########################
def convert_distance(miles):
kilometers=(miles*8.0)/5.0
print("Converting distance in miles to kilometers:")
print("Distance in miles:", miles)
print("Distance in kilometers:", kilometers)
return kilometers
################################## task4 ###########################
def get_size(width,height,depth):
area=width*height
volume=width*height*depth
sizes=(area,volume)
return sizes
################################## task5 ###########################
def get_size(width,height,depth):
area=width*height
volume=width*height*depth
sizes=(area,volume)
return(sizes)
################################## task6 ###########################
def temp_converter(celsius):
fahrenheit=celsius*9.0/5.0+32
kelvin=celsius+273.15
print("that's {} degrees in fahrenheit and {} degrees in kelvin.".format(fahrenheit,kelvin))
values=(fahrenheit,kelvin)
return values
################################## task7 ###########################
def temp_converter(celsius):
fahrenheit=celsius*9.0/5.0+32
kelvin=celsius+273.15
temperature=(fahrenheit,kelvin)
return temperature
################################## task8 ex 19 from LPTHW ###########################
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print("You have %d cheeses!" % cheese_count)
print("You have %d boxes of crackers!" % boxes_of_crackers)
print("Man that's enough for a party!")
print ("Get a blanket.\n")
################################## task9 ex 21 from LPTHW ###########################
def add(a,b):
print("adding %d+%d" % (a,b))
return a+b
def subtract(a, b):
print ("SUBTRACTING %d - %d" % (a, b))
return a-b
def multiply(a, b):
print("MULTIPLYING %d * %d" % (a, b))
return a * b
def divide(a, b):
print("DIVIDING %d / %d" % (a, b))
return a / b
| false |
c86ebebbe6eb2c4b51b731ffb8d49cd5679528bd | mstoiovici/module2 | /Codingbat/String_1/String_1_first_half.py | 437 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 15:52:31 2018
@author: maria
"""
"""
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'S
first_half('abcdef') → 'abc'
"""
def first_half(str):
lenght= len(str)
#print(str[0:int(lenght/2)])
return str[0:int(lenght/2)]
first_half("lilian") | true |
e057e238d978fb2b6043f1810963e3f86a5b03cf | HugoPhibbs/COSC262_lab_work | /Lab_11/binary_search_tree.py | 1,187 | 4.15625 | 4 | # Do not alter the next two lines
from collections import namedtuple
Node = namedtuple("Node", ["value", "left", "right"])
# Rewrite the following function to avoid slicing
def binary_search_tree(nums, is_sorted=False, start=None, end=None):
"""Return a balanced binary search tree with the given nums
at the leaves. is_sorted is True if nums is already sorted.
Inefficient because of slicing but more readable.
"""
if not is_sorted:
nums = sorted(nums)
n = len(nums)
if n == 1:
tree = Node(nums[0], None, None) # A leaf
else:
mid = n // 2 # Halfway (approx)
left = binary_search_tree(nums[start:], start, end)
right = binary_search_tree(nums[end: ], start, end)
tree = Node(nums[mid - 1], left, right)
return tree
# Leave the following function unchanged
def print_tree(tree, level=0):
"""Print the tree with indentation"""
if tree.left is None and tree.right is None: # Leaf?
print(2 * level * ' ' + f"Leaf({tree.value})")
else:
print(2 * level * ' ' + f"Node({tree.value})")
print_tree(tree.left, level + 1)
print_tree(tree.right, level + 1)
| true |
92e483d42f1b5deba9df5b7efce92ccd22bbf551 | HugoPhibbs/COSC262_lab_work | /Lab_2/fib_matrix.py | 1,787 | 4.125 | 4 | def fib(n, matrix=None):
"""finds the nth fibonacci sequence using divide and conquer and
fast exponentiation"""
#how to use martix multiplication in python??
#how can i implement 2x2 matrix multiplicatoin in python, look at the general formula.
# fib matrix = [[fn+1, fn], [fn, fn-1]]
if n == 1 or n==2:
return 1
else:
fib_matrix = matrix_power_rec( [[1, 1], [1, 0]] , n) #helper does much of the work
fib_n = fib_matrix[0][1] # or fib_matrix[1][0], doesnt matter
return fib_n
def matrix_power_rec(matrix, n):
"""computes a matrix to a power using the power of recursion,
only works for a 2x2 matrix!
takes matrix in form [[topLeft, topRight],[bottomLeft, bottomRight]]"""
if n==0 or n==1:
return matrix
else:
result = matrix_power_rec(matrix, n//2)
# Square the result matrix
top_left = result[0][0]*result[0][0] + result[0][1]*result[1][0]
top_right = result[0][0]*result[0][1] + result[0][1]*result[1][1]
bottom_left = result[1][0]*result[0][0] + result[1][1]*result[1][0]
bottom_right = result[1][0]*result[0][1] + result[1][1]*result[1][1]
power_matrix = [[top_left, top_right], [bottom_left, bottom_right]]
if n%2==0:
return power_matrix
else: # n is odd
top_left_o = matrix[0][0]*power_matrix[0][0] + matrix[0][1]*power_matrix[1][0]
top_right_o = matrix[0][0]*power_matrix[0][1] + matrix[0][1]*power_matrix[1][1]
bottom_left_o = matrix[1][0]*power_matrix[0][0] + matrix[1][1]*power_matrix[1][0]
bottom_right_o = matrix[1][0]*power_matrix[0][1] + matrix[1][1]*power_matrix[1][1]
return [[top_left_o, top_right_o], [bottom_left_o, bottom_right_o]] | true |
0e48158e10ae5c8672c3c4b58cd1679a6afdaec1 | HugoPhibbs/COSC262_lab_work | /Lab_4/dijkstras.py | 1,825 | 4.1875 | 4 | def dijkstra(adj_list, next_node):
"""does dijkstras algorithm on a graph"""
parent_array = [None for i in range(0, len(adj_list))]
distance_array = [float('inf') for i in range(0, len(adj_list))]
in_tree = [False for i in range(0, len(adj_list))]
distance_array[next_node] = 0
true_array = [True for i in range(0, len(adj_list))]
while in_tree != true_array:
# go throught the entire one vertex at a time,
# if a vertex has been fully discovered, add its smallest edge to the parent array
# go to the added vertex, and then add its edges.
# then look at the total list of distance and the edges, and add the smallest one.
# for the smallest one that is added, repeat this, until the in_tree is all done.
# What to do with disconnected graphs?
# add all adj edges with their weights to distance array
u = next_vertex(in_tree, distance_array)
in_tree[u] = True
for (v, weight) in adj_list[u]:
if not in_tree[v] and distance_array[u] + weight < distance_array[v]:
distance_array[v] = distance_array[u] + weight
parent_array[v] = u
return parent_array, distance_array
# hasnt yet discovered an adjacent vertex for current node
def next_vertex(in_tree, distance):
"""returns the vertex that should be next added to the tree"""
# Set the current bench mark for smallest distance,
# and also set the first place to look in search
min_index = in_tree.index(False)
for i in range(min_index + 1, len(in_tree)):
# If the element isnt already in the tree (confirmed) in,
# and it has the smallest weight, add it!
if (in_tree[i] is False) and (distance[i] < distance[min_index]):
min_index = i
return min_index | true |
489714e74b951da5b5cd093d33ce3618440a5edc | ifpb-cz-ads/pw1-2020-2-ac04-team-josecatanao | /questao_06.py | 330 | 4.1875 | 4 | #6) Modifique o programa anterior de forma que o usuário também digite o início e o fim da tabuada, em vez de começar com 1 e 10.
n = int(input("Tabuada de: "))
inicio = int(input("digite o inicio da Tabuada :"))
fim = int(input("digite o fim da Tabuada :"))
x = inicio
while x <= fim:
print(n ,'*', x,'=',n*x)
x = x + 1 | false |
8ca7053bbf67d2a95481a4cd7dc58e54defb37e0 | failedpeanut/Python | /day1/MoreAboutFunctions.py | 1,137 | 4.28125 | 4 | #Default Argument Values
#can give default argument values for functions.
def defaultArguments(name, age=18, gender='Not Applicable',somethingelse=None):
print("name",name)
print("age",age)
print("gender",gender)
print("somethingelse", somethingelse)
defaultArguments("Peanut",20,"Male","Nothing!")
defaultArguments("Peanut",gender="Female")
defaultArguments(name="FailedPeanut",somethingelse="Lot of things to say!")
print("#########################################################")
#Another way:
# just to divide between default and non default parameters
#the parameters before '/' dont have default values
#The parameter after '/' has default values
#the function must be called atleast with 2 arguments else it will give error.
def defaultArgumentsWithPosition(name, age, /,gender='Not Applicable',somethingelse=None):
print("name", name)
print("age", age)
print("gender", gender)
print("somethingelse", somethingelse)
defaultArgumentsWithPosition("Tommy",20)
defaultArgumentsWithPosition("Jerry",80)
defaultArgumentsWithPosition("Tommy",50,gender="Male")
defaultArgumentsWithPosition("Tommy",90)
| true |
489444bb8d5a6526728879c779bba58c35b45534 | Christinaty/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/7-add_item.py | 584 | 4.3125 | 4 | #!/usr/bin/python3
"""Write a script that adds all arguments to a Python list, and then save
them to a file:
*If the file doesnt exist, it should be created
"""
from sys import argv
from os import path
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
load_from_json_file = __import__('6-load_from_json_file').load_from_json_file
filename = "add_item.json"
try:
my_items = load_from_json_file(filename)
except FileNotFoundError:
my_items = []
for i in range(1, len(argv)):
my_items.append(argv[i])
save_to_json_file(my_items, filename)
| true |
aae741e19ab69d1b916ad414e0b6db207f5dc3e0 | tyriem/PY | /CISCO/CISCO 33 - Tax Calc.py | 2,193 | 4.28125 | 4 | ### AUTHOR: TMRM
### PROJECT: CISCO DevNet - Tax Calc
### VER: 1.0
### DATE: 05-XX-2021
### OBJECTIVE ###
# Your task is to write a tax calculator.
# It should accept one floating-point value: the income.
# Next, it should print the calculated tax, rounded to full dollars. There's a function named round() which will do the rounding for you -
# you'll find it in the skeleton code in the editor.
# Note: this happy country never returns money to its citizens. If the calculated tax is less than zero, it only means no tax at all (the tax is equal to zero).
# Take this into consideration during your calculations.
### OBJECTIVE ###
#####################
### CODE ###
#####################
### DEPRECATED ###
#floatIncome = float(input("What was your income in thalers, citizen?"))
#if floatIncome < 3088.8:
# print("On your income of: " + str(floatIncome) + ". The tax is: 0 thalers.")
#elif floatIncome < 85528:
# floatRawTax = ((floatIncome * 0.18) - 556.02)
# floatTax = round(floatRawTax, 1)
# print("On your income of: " + str(floatIncome) + ". The tax is: " + str(floatTax) + " thalers.")
#else:
# floatRawTax = (14839.02 + (0.32 * (floatIncome - 85528)))
# floatTax = round(floatRawTax, 0)
# print("On your income of: " + str(floatIncome) + ". The tax is: " + str(floatTax) + " thalers.")
### DEPRECATED ###
# ACCEPT USER INPUT AS FLOAT
floatIncome = float(input("What was your income in thalers, citizen?"))
# IF-ELSE STATEMENT TO EVALUATE INCOME VERSUS TAX BRACKET
if floatIncome < 85528:
floatRawTax = ((floatIncome * 0.18) - 556.02)
floatTax = round(floatRawTax, 1)
# NESTED IF-ELSE STATEMENT TO EVALUATE TAX BURDEN FOR LOWER TAX BRACKET
if floatTax < 0:
print("On your income of: " + str(floatIncome) + ". The tax is: 0 thalers.")
else:
print("On your income of: " + str(floatIncome) + ". The tax is: " + str(floatTax) + " thalers.")
# ELSE STATEMENT TO EVALUATE TAX BURDEN FOR HIGHER TAX BRACKET
else:
floatRawTax = (14839.02 + (0.32 * (floatIncome - 85528)))
floatTax = round(floatRawTax, 0)
print("On your income of: " + str(floatIncome) + ". The tax is: " + str(floatTax) + " thalers.")
| true |
ffbfc2d58564e2cad36dac052f517cb9632f4d4d | tyriem/PY | /Intro To Python/14 -While Loop - Password TMRM.py | 322 | 4.15625 | 4 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - While Loop Password
### VER: 1.0
### DATE: 05-XX-2020
##Declare CALLs
##LOOPs and VARs
password = ''
while password != 'test':
print('What is the password?')
password = input()
##OUTPUTs
print('Yes, the password is ' + password + '. You may enter.')
| true |
339ac9fc350ddedccd8667e9288dc25facda7c82 | tyriem/PY | /Intro To Python/25 - Function - Param-Default-Return TMRM.py | 1,542 | 4.8125 | 5 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - FUNCTIONS
### VER: 1.0
### DATE: 05-28-2020
##Declare CALLs & DEFs
### PARAMETERS ###
# Parameters are used to pass information to functions
# Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
# The following ex. has a function with one parameter (fname). When the function is called, we pass along a first name,
# which is used inside the function to print the full name. Then we add the last name so that when we call the function
# it will attach the last name to whatever you put before.
def name_function(fname):
print(fname + " Moss ")
name_function("Ann")
name_function("Edwin")
name_function("Tyrie")
### DEFAULT PARAMETER VALUE ###
# If we call the function without parameter, it uses the default value defined in the def statement
# The following ex. has a function with a default value, observe what happens when we call the function without a value and then with one.
def country_function(country = "INSERT COUNTRY HERE"):
print ("I am from " + country)
country_function()
country_function("The Bahamas")
country_function("Cuba")
country_function("Jamaica")
### RETURN VALUES ###
# To let a function return a value, use the return statement
# The following ex. has a function with a return statement, NOTE THE INDENTATION ON THE RETURN STATEMENT
def num_function(x):
return 5 * x
print(num_function(3))
print(num_function(5))
print(num_function(9))
| true |
c4613f6ad8a571db354d428c78a9f5441cdc62a0 | tyriem/PY | /Intro To Python/41 - GUI - Radio Button SelectGet - TMRM.py | 1,047 | 4.25 | 4 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - GUI: Radio Buttons Select & Get
### VER: 1.0
### DATE: 06-06-2020
#####################
### GUIs ###
#####################
### OBJECTIVE ###
#Code a basic GUI for user
#
### OBJECTIVE ###
##Declare CALLs & DEFs
from tkinter import*
#First, we import the ttk library
from tkinter.ttk import *
##Declare/Input VALs & STRINGs
##CALCs
##OUTPUTs
window = Tk()
window.title("PYTHON APP: GUI - RADIO BUTTONS SELECT & GET")
#First, we issue the selected = IntVar()
selected = IntVar()
rad1 = Radiobutton(window,text='First', value=1, variable=selected)
rad2 = Radiobutton(window,text='Second', value=2, variable=selected)
rad3 = Radiobutton(window,text='Third', value=3, variable=selected)
#Second, we define a function for clicked
def clicked():
print(selected.get())
btn = Button(window, text="Click Me", command=clicked)
rad1.grid(column=0, row=0)
rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)
btn.grid(column=3, row=0)
window.mainloop()
| true |
a39b5eec1a8262f0e693f662b6664a79e42a7888 | tyriem/PY | /Intro To Python/6 - Perform CALCs using Formulae.py | 1,985 | 4.34375 | 4 | ### AUTHOR: TMRM
### PROJECT: Perform Calculations using Formulas
### VER: 1.0
### DATE: 05-18-2020
#Task #1: Find the area of a circle
print ("\n [TASK #1: Find the area of a circle using the formula pi(3.14) x radius^2]")
#Declare STRINGs & VALs
rad = float(input("\n Enter the Radius of The Circle = "))
measure = str(input("\n Enter the Measurement Units = (mm,cm,in,etc.) "))
pi = float(3.14)
#CALCs
val = (pi * (rad * rad))
dia = (rad * 2)
#OUTPUT
print ("\n Diameter of the circle: " + str(dia) + str(measure))
print ("\n Area of the circle: " + str(val) + str(measure) + "^2")
##################################################################################################
#Task #2: Calculate Simple Interest
print ("\n [TASK #2: Calculate Simple Interest using the formula: (Principal x Time x Rate)/100]")
#Declare STRINGs & VALs
raw_prin = input("\n Principle Of Loan (Amount of money loaned/borrowed in $) = ")
prin = float(raw_prin.replace("$",""))
raw_time = input("\n Time (Amount of Years) = ")
time = float(raw_time.replace("years",""))
raw_rate = input("\n Rate (Percentage Interest) = ")
rate = float(raw_rate.replace("%",""))
#CALCs
simple_interest = ((prin * time * rate)/ 100 )
#OUTPUT
print (str(" $ ") + str(simple_interest))
##################################################################################################
#Task #3: Calculate Perimeter & Area of Rectangle
print ("\n [TASK #3: Calculate Perimeter ((L*2)+(W*2)) & Area(L*W) of a Rectangle")
#Declare STRINGs & VALs
len_rec = float(input("\n Enter The Length of Rectangle = "))
wid_rec = float(input("\n Enter The Width of Rectangle = "))
measure_rec = str(input("\n Enter the Measurement Units = (mm,cm,in,etc.) "))
#CALCs
perim_rec = float(((len_rec * 2) + (wid_rec * 2)))
area_rec = float((len_rec * wid_rec))
#OUTPUT
print ("\n Perimeter of the square: " + str(perim_rec) + str(measure_rec))
print ("\n Area of the square: " + str(area_rec) + str(measure_rec) + "^2")
| true |
8c5f731509903fbfe23c7fa8e09b304218cdad80 | vaylon-fernandes/simple-python-projects | /guess_the_number/guess_the_number_with_levels.py | 2,677 | 4.375 | 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).
import random
from art import logo
print(logo)
# select a random number
random_number = random.randint(1, 100)
guesses = [0]
print("I'm thinking of a number between 1-100.Can you guess it?")
level = input("Choose level: type 'easy' or 'hard' -> ")
easy_level = level == "easy"
hard_level = level == "hard"
while True:
if easy_level:
max_attempts = 10
if hard_level:
max_attempts = 5
number_of_guesses = len(guesses) - 1
attempts_left = max_attempts - number_of_guesses
print(f"Attempts Left: {attempts_left}")
guess = input("What is your guess?: ")
invalid_entry = not guess.isdigit()
if invalid_entry:
print("Invalid Entry")
print("You must only enter a number between 1-100")
continue
guess = int(guess)
guess_out_of_range = guess < 1 or guess > 100
if guess_out_of_range:
print("Please enter a number between 1-100")
continue
correct_guess = random_number == guess
if correct_guess:
print(
f'Congratulations you guessed the number!!!! It took you {number_of_guesses} guesses')
break
guesses.append(guess)
current_guess_difference = abs(random_number-guess)
previous_guess_difference = abs(random_number-guesses[-2])
print(guesses[-2])
# for the first guess there will be two items in the list
# 0 at index:0, one guess at index 1
# Hence getting the item using index -2, will return the value 0, which evaluates to false in this case,
# and evaluate to True in all other cases
not_first_guess = guesses[-2]
if not_first_guess:
getting_close = current_guess_difference < previous_guess_difference
if getting_close:
print('Warmer')
else:
print('Colder')
else:
guess_is_close = current_guess_difference <= 10
if guess_is_close:
print('Warm')
else:
print('Cold')
attempts_left -= 1
attempts_over = attempts_left == 0
if attempts_over:
print(f"You are out of attempts! The correct number was {random_number}")
break
| true |
74ecde0261b07b9503333ccfc83ee50c0a4dac95 | vivian2yu/python-demo | /python-beginner/do_fun.py | 473 | 4.1875 | 4 | #比如在游戏中经常需要从一个点移动到另一个点,给出坐标、位移和角度,就可以计算出新的新的坐标:
import math
# def move(x, y, step, angle=0):
# nx = x + step * math.cos(angle)
# ny = y - step * math.sin(angle)
# return nx, ny
# x, y = move(100, 100, 60, math.pi / 6)
# print(x, y)
# r = move(100, 100, 60, math.pi / 6)
# print(r)
#高阶函数
def add(x, y, f):
return f(x) + f(y)
print(add(-5, 6, abs)) | false |
fae1263cfa2e8e3516c453acc70173377717b3a9 | mladenangel/scripts | /pyLessions/lles8.py | 254 | 4.15625 | 4 | print('demo - iteration for')
for i in range(1,5):
print(i)
print('demo - nested for')
for i in range(1,3):
for j in range(5,10):
print(str(i) + '-' + str(j))
print('demo - iteration while')
i = 0
while i < 10:
print(i)
i += 1
| false |
d3e11df9c61642894bc613cebf4f9a2f7b4e7360 | lt393/pythonlearning | /s5_data_structure/dict/dict_create.py | 670 | 4.25 | 4 |
# Python's dictionaries are kind of hash table type which consist of key-value pairs of unordered elements.
# Keys : must be immutable data types ,usually numbers or strings.
# Values : can be any arbitrary Python object.
d = {} # empty dict
d = {
1: 1,
2: 2,
3: 3
}
# Python Dictionaries are mutable objects that can change their values.
print('d[0] =', d[0])
d[0] = '1111'
print(d)
# A dictionary is enclosed by curly braces ({ }), the items are separated by commas, and each key is separated from its value by a colon (:).
# Dictionary’s values can be assigned and accessed using square braces ([]) with a key to obtain its value.
| true |
5561b4532dfe1986fa37e26beaf7490584acc298 | lt393/pythonlearning | /s12_date_time/datetime.py | 2,149 | 4.25 | 4 | # datetime
# datetime对象的构建
"""
>>> from datetime import datetime
>>> cur = datetime(year=2016, month=9, day=2, hour=10, minute=30,second=13, microsecond=2)
>>> cur
datetime.datetime(2016, 9, 2, 10, 30, 13, 2)
>>> cur.date()
datetime.date(2016, 9, 2)
>>> cur.time()
datetime.time(10, 30, 13, 2)
>>>
"""
# 获取当前时间的datetime对象
"""
>>> datetime.today()
datetime.datetime(2017, 8, 8, 8, 50, 49, 552758)
>>> datetime.now()
datetime.datetime(2017, 8, 8, 8, 50, 54, 17340)
>>>
"""
# 通过时间戳来获取一个datetime对象
"""
>>> import time
>>> datetime.fromtimestamp(time.time())
datetime.datetime(2017, 8, 8, 8, 52, 7, 158772)
>>>
"""
# 通过date和time对象来组合成一个datetime对象
"""
>>> from datetime import date
>>> from datetime import time
>>> from datetime import datetime
>>>
>>> d = date(year=2017, month=8, day=10)
>>> t = time(hour=19, minute=20)
>>> d
datetime.date(2017, 8, 10)
>>> t
datetime.time(19, 20)
>>> datetime.combine(d,t)
datetime.datetime(2017, 8, 10, 19, 20)
>>>
"""
# replace()方法允许我们对datetime的任意字段进行替换,并返回一个新的datetime对象
# 这个新的对象在其他字段上与原有对象保持一致
"""
>>> t1 = datetime.now()
>>> t1.date()
datetime.date(2017, 8, 8)
>>> t1.time()
datetime.time(11, 12, 14, 584808)
>>> t2 = t1.replace(month=t1.month+1)
>>> t2
datetime.datetime(2017, 9, 8, 11, 12, 14, 584808)
>>> t2 = t1.replace(month=t1.month+1, day=t1.day+3)
>>> t2
datetime.datetime(2017, 9, 11, 11, 12, 14, 584808)
>>>
"""
# time delta
"""
>>> t1 = datetime.now()
>>> t2 = datetime.now()
>>> t2-t1
datetime.timedelta(0, 4, 671693)
>>> t = t2 - t1
>>> t
datetime.timedelta(0, 4, 671693)
>>> t.days
0
>>> t.seconds
4
>>> t.total_seconds
<built-in method total_seconds of datetime.timedelta object at 0x10203bf80>
>>> t.total_seconds()
4.671693
>>>
>>> from datetime import timedelta
>>> delta = timedelta(days=7, seconds=10)
>>> delta
datetime.timedelta(7, 10)
>>>
>>> now = datetime.now()
>>> now
datetime.datetime(2017, 8, 8, 11, 34, 34, 918385)
>>>
>>> now + delta
datetime.datetime(2017, 8, 15, 11, 34, 44, 918385)
>>>
"""
| false |
b6aabafceb7b1b07d5952b5e48a959e1100821fc | lt393/pythonlearning | /s7_python_functions/lambda.py | 1,260 | 4.21875 | 4 |
"""
The lambda’s general form is the keyword lambda,
followed by one or more arguments (exactly like the arguments list you enclose in parentheses in a def header),
followed by an expression after a colon:
lambda argument1, argument2,... argumentN :expression using arguments
"""
def sum(x, y ,z):
return x + y + z
print(sum(1, 2, 3))
f = lambda x, y, z: x + y + z
print(f(1, 2, 3))
"""
➜ ~ python3.5
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 08:49:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3, 4]
>>> b = []
>>>
>>>
>>> for i in a:
... b.append(i + 3)
...
>>> b
[4, 5, 6, 7]
>>>
>>>
>>>
>>>
>>> a = [1, 11, 14, 56]
>>>
>>> b = [33, 2, 27, 35]
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> def inc(x):
... return x + 3
...
>>>
>>> map(inc, a)
<map object at 0x1022e25c0>
>>>
>>>
>>> list(map(inc, a))
[4, 14, 17, 59]
>>>
>>>
>>>
>>>
>>> list(map(inc, b))
[36, 5, 30, 38]
>>>
>>>
>>>
>>>
>>> a
[1, 11, 14, 56]
>>> b
[33, 2, 27, 35]
>>>
>>>
>>>
>>>
>>>
>>> map((lambda x: x+3), a)
<map object at 0x1022e2668>
>>>
>>>
>>> list(map((lambda x: x+3), a))
[4, 14, 17, 59]
>>>
>>>
>>>
>>> list(map((lambda x: x+3), b))
[36, 5, 30, 38]
>>>
""" | true |
032321af56c3fe1f915dc0c5abe8a0dde7993d3e | AndersonANascimento/PythonExercicios | /desafio035.py | 626 | 4.1875 | 4 | # Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um trângulo.
# Obs: Em todo triângulo, a medida de qualquer lado é maior que a diferença entre as medidas dos outros dois.
r1 = int(input('Informe a medida da 1ª reta: '))
r2 = int(input('Informe a medida da 2ª reta: '))
r3 = int(input('Informe a medida da 3ª reta: '))
if r1 > abs(r2 - r3) and r2 > abs(r1 - r3) and r3 > abs(r1 - r2):
ehTriangulo = ''
else:
ehTriangulo = 'não '
print('Os segmentos de reta de medidas {}, {} e {}, {}podem formar um triângulo.'.format(r1, r2, r3, ehTriangulo))
| false |
4592872fbd9b93e6a1a8d3dec72d04c438bc7a7e | AndersonANascimento/PythonExercicios | /desafio04.py | 517 | 4.15625 | 4 | # Faça um programa que leia algo pelo teclado e mostre o seu tipo primitivo e todas as informações possíveis sobre ele
obj = input('Digite algo: ')
print('O tipo primitivo desse valor é {}'.format(type(obj)))
print('Só tem espaços?', obj.isspace())
print('É um número?', obj.isnumeric())
print('É alfabético?', obj.isalpha())
print('É alfanumérico?', obj.isalnum())
print('Está em maiúsculo?', obj.isupper())
print('Está em minúsculo?', obj.islower())
print('Está em capitalizado?', obj.istitle())
| false |
c82d806ab02b2e467699dab1d57461474f8e9bce | Czbenton/HelloPython | /src/Main.py | 1,377 | 4.21875 | 4 | accountList = {"zach": 343}
def login():
global userName
print("Welcome to The Bank of Python. Please enter your name.")
userName = input()
print("Hi ", userName, "!! How much would you like to deposit to start your account?", sep="")
initDeposit = float(input())
accountList[userName] = initDeposit
def menuSelect():
print(
"What would you like to do?:\n 1. Check Balance 2. Withdraw Funds 3. Deposit Funds"
" 4. Cancel 5. DELETE ACCOUNT")
optionSelect = input()
if optionSelect == "1":
print("Your current balance is", accountList[userName])
elif optionSelect == "2":
print("How much do you want to withdraw?")
withdraw = float(input())
accountList[userName] -= withdraw
elif optionSelect == "3":
print("How much would you like to deposit?")
deposit = float(input())
accountList[userName] += deposit
elif optionSelect == "4":
print("See you next time!")
exit()
elif optionSelect == "5":
print("Are you sure you want to DELETE your account? [yes] [no]")
userInput = input()
if userInput == "yes":
del(accountList[userName])
else:
print("Okay, your account is not gone forever.")
else:
print("Bad input")
return
login()
while True:
menuSelect()
| true |
95af735aa251c5d148acf1b04761d7f7eec5851d | emanuelvianna/algos | /algo/sorting/heapsort.py | 2,914 | 4.21875 | 4 | import heapq
from algo.utils.list_utils import swap
def _min_heapify_at_a_range(numbers, left, right):
"""
Build max-heap in a range of the array.
Parameters
----------
numbers: list
List of numbers to be sorted.
left: int
Initial index.
right: int
Final index.
"""
part = slice(left, right + 1)
partial = numbers[part]
heapq.heapify(partial)
numbers[part] = partial
def _heapsort_for_top_n(numbers, top_n):
"""
Sorts "in situ" a list of numbers in ascendant order using
the Heapsort method for only the top `n` numbers.
>>> array = [5, 1, 8, 9, 2]
>>> insertion_sort(array, top_n=1)
>>> array
[1, 2, 8, 9, 5]
Parameters
----------
numbers: list
List of numbers to be sorted.
top_n: int or None
Defines the number of elements that should be sorted.
For top=1, it will only put the smallest element in the beginning.
"""
left, right = 1, len(numbers) - 1
heapq.heapify(numbers)
while left < top_n:
_min_heapify_at_a_range(numbers, left, right)
left += 1
def _max_heapify_at_a_range(numbers, left, right):
"""
Build max-heap in a range of the array.
Parameters
----------
numbers: list
List of numbers to be sorted.
left: int
Initial index.
right: int
Final index.
"""
part = slice(left, right + 1)
partial = numbers[part]
heapq._heapify_max(partial)
numbers[part] = partial
def _heapsort_algo(numbers):
"""
Sorts "in situ" a list of numbers in ascendant order using
the Insertion Sort method for the entire list.
>>> array = [5, 1, 8, 9, 2]
>>> _heapsort_algo(array)
>>> array
[1, 2, 5, 8, 9]
Parameters
----------
numbers: list
List of numbers to be sorted.
"""
left, right = 0, len(numbers) - 1
heapq._heapify_max(numbers)
while right >= 1:
number = numbers[0]
swap(numbers, 0, right)
right -= 1
_max_heapify_at_a_range(numbers, left, right)
def heapsort(numbers, top_n=None):
"""
Sorts "in-situ" a list of numbers in ascendant order
using the method Heapsort.
>>> array = [5, 1, 8, 9, 2]
>>> heapsort(array)
>>> array
[1, 2, 5, 8, 9]
It also supports the sorting of the first `n` numbers.
>>> array = [5, 1, 8, 9, 2]
>>> heapsort(array, top_n=1)
>>> array
[1, 2, 8, 9, 5]
Parameters
----------
numbers: list
List of numbers to be sorted.
top_n: int or None
Defines the number of elements that should be sorted.
For top=1, it will only put the smallest element in the beginning.
"""
if top_n is not None:
_heapsort_for_top_n(numbers, top_n)
else:
_heapsort_algo(numbers)
| true |
dce86aff42a17c01304f326cb7a55574fcd2b097 | mkhalil7625/hello_sqlite_python | /sqlite/db_context_manager_error_handling.py | 1,673 | 4.21875 | 4 | """
sqlite3 context manager and try-except error handling
"""
import sqlite3
def create_table(db):
try:
with db:
cur = db.cursor()
cur.execute('create table phones (brand text, version int)')
except sqlite3.Error as e:
print(f'error creating table because {e}')
def add_test_data(db):
try:
with db:
cur = db.cursor()
cur.execute('insert into phones values ("Android", 5)')
cur.execute('insert into phones values ("iPhone", 6)')
except sqlite3.Error:
print('Error adding rows')
def print_all_data(db):
# Execute a query. Do not need a context manager, as no changes are being made to the DB
try:
cur = db.cursor() # Need a cursor object to perform operations
for row in cur.execute('select * from phones'):
print(row)
except sqlite3.Error as e:
print(f'Error selecting data from phones table because {e}')
def delete_table(db):
try:
with db:
cur = db.cursor()
cur.execute('drop table phones') # Delete table
except sqlite3.Error as e:
print(f'Error deleting phones table because {e}')
def main():
db = None
try:
db = sqlite3.connect('my_first_db.db')
except sqlite3.Error as e:
print(f'Unable to connect to database because {e}.')
if db is not None:
create_table(db)
add_test_data(db)
print_all_data(db)
delete_table(db)
try:
db.close()
except sqlite3.Error:
print(f'Error closing database because {e}')
if __name__ == '__main__':
main()
| true |
f3b56bd393ca33e532baa4e4eaacbae7fd9ebe9c | sakshimaan/Python | /palindrome.py | 590 | 4.3125 | 4 | #python code to check whether the given string is palindrome or not
def check(string):
n=len(string)
first=0
mid=(n-1)//2
last=n-1
flag=1
while(first<mid):
if (string[first]==string[last]):
first=first+1
last=last-1
else:
flag=0
break;
if flag==1:
print("String is palindrome")
else:
print("String is not palindrome")
string=str(input("Enter a string to check whether it is palindrome or not :- "))
#string='abcddcba'
print(check(string))
| true |
1ee0023d2c872565e5405a8d850b11094b392fe4 | LachezarKostov/SoftUni | /01_Python-Basics/functions/Password Validator.py | 1,161 | 4.15625 | 4 | def is_six_to_ten_char(password):
valid = False
if 6 <= len(password) <= 10:
valid = True
return valid
def is_letters_and_digits(password):
valid = True
for char in password:
ascii = ord(char)
if (ascii < 48) or (57 < ascii < 65) or (90 < ascii < 97) or (ascii > 122):
valid = False
break
return valid
def is_there_two_digits(password):
valid = False
dig_cout = 0
for char in password:
ascii = ord(char)
if 48 <= ascii <= 57:
dig_cout += 1
if dig_cout >= 2:
valid = True
return valid
def is_valid_password(password):
valid_1 = is_six_to_ten_char(password)
valid_2 = is_letters_and_digits(password)
valid_3 = is_there_two_digits(password)
if not valid_1:
print("Password must be between 6 and 10 characters")
if not valid_2:
print("Password must consist only of letters and digits")
if not valid_3:
print("Password must have at least 2 digits")
if valid_1 and valid_2 and valid_3:
print("Password is valid")
password = input()
is_valid_password(password)
| true |
8020457b677aa37c4765a8bf014178adcd6d98b6 | Fay321/leetcode-exercise | /solution/problem 75.py | 1,696 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
判断链表是否有环
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution1(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
set_record = set()
while head:
if head in set_record:
return True
else:
set_record.add(head)
head = head.next
return False
'''
快慢指针:
https://blog.csdn.net/willduan1/article/details/50938210
设置一个快指针fp和一个慢指针sp,两个指针起始同时指向head节点,其中快指针每次走两步,慢指针每次走一步,那么如果链表有环的话他们一定能够相遇。可以想象两个人同时从操场上起跑,其中甲的速度是乙速度的2倍,那么当乙跑完一圈的时候甲也跑了两圈,他们一定能够相遇。
'''
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head==None: #边界条件
return False
slow = head.next
if head.next==None:
return False
else:
fast = head.next.next
while slow and fast:
if slow==fast:
return True
slow = slow.next
if fast.next==None:
return False
else:
fast = fast.next.next
return False | false |
d4c79eb2a3a0673e078c907808a187a25853d825 | phibzy/InterviewQPractice | /Solutions/LongestCommonPrefix/solution.py | 1,002 | 4.25 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Wednesday Sep 16, 2020 17:07:49 AEST
@file : solution
"""
"""
The "column" approach
Compare each sequential character of each string.
Return as soon as a character in one string is not the same.
Complexity:
Time: O( N * M) - Where N is number of strings, M length of strings
- Worst case all strings are of equal length
Space: O(1)
"""
def longestCommonPrefix(self, strs):
# If list is empty, or first string an empty string
# We return empty string
if not strs or not strs[0]: return ""
i = 0
# We stop if the char position index ever exceeds length of first string
while i < len(strs[0]):
# Char to compare
char = strs[0][i]
for s in strs:
# Return if exceeds length or if char not same
if i >= len(s) or s[i] != char: return strs[0][0:i]
i += 1
return strs[0][0:i]
| true |
be104d8d168f501796507c6b58a15bb49d2c9314 | phibzy/InterviewQPractice | /Solutions/DistributeCandies/candies.py | 1,124 | 4.4375 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Thursday Mar 04, 2021 12:00:57 AEDT
@file : candies
"""
"""
Questions:
- Range of number of candies?
- Will number of candies always be even? Need to floor if odd?
- Will candy types just be ints >= 0?
- Neg ints?
- Empty candy list a possibility?
- Range of N
"""
"""
Algo:
Count how many different candies there are (using dict) and then
return the minimum of N/2 and those number of candies
TC: O(N)
SC: O(N)
"""
class Solution:
def distributeCandies(self, candyType):
# Number of candies we can eat
numEat = len(candyType) // 2
# Keep track of unique candy types
uniq = dict()
# Check if candy is unique, add to dict
for candy in candyType:
uniq.setdefault(candy, 1)
# If number of unique candies is equal to the max
# we're allowed to eat, we can early exit
if len(uniq) == numEat:
return numEat
# Otherwise return the number of unique candies
return len(uniq)
| true |
85938d4ff2bad05052c6158c29525d45d74a9428 | naumanurrehman/ekhumba | /problem3/recursion/reverseString.py | 1,012 | 4.1875 | 4 | '''
Given a string, Write recursive function that reverses the string.
Input Format
A String.
Constraints
x
Output Format
Reverse of Strings.
Sample Input
Being
Sample Output
gnieB
Explanation
Self explanatory.
'''
def recur(content, num, length):
if num >= length:
return ''
return recur(content, num+1, length) + content[num]
def reverse_string(content):
return recur(content, 0, len(content))
if __name__ == '__main__':
tests = [
("Yello", "olleY"),
("King", "gniK"),
("", ""),
("Nauman", "namuaN"),
("a", "a")
]
for test in tests:
print("Test: ", test[0])
result = reverse_string(test[0])
print("Result: ", result)
if not result==test[1]:
print("Error")
print("Expected: ", test[1])
else:
print("Passed")
print()
while True:
content = input("Enter a string: ")
print(reverse_string(content))
print()
| true |
4050182c72685750fd92c6fb0bdca5c5879db964 | JanakSharma2055/Cryptopals | /challenge6.py | 613 | 4.5 | 4 | def find_hamming_distance(string1: bytes, string2: bytes) -> int:
"""
Find hamming distance between two strings.
The Hamming distance is just the number of differing bits.
:param string1: The first string to be compared, as bytes
:param string2: The second string to be compared, as bytes
:returns: The hamming distance between the two params as an int
"""
distance = 0
for byte1, byte2 in zip(string1, string2):
diff = byte1 ^ byte2
# XOR only returns 1 if bits are different
distance += sum([1 for bit in bin(diff) if bit == '1'])
return distance | true |
16a17fc8a65afedb33d9cd32c49b27f2d12559b8 | jermcmahan/ATM | /ATM/simulator/tree.py | 1,546 | 4.4375 | 4 |
"""
Tree --- class to represent an accepting computation tree of an Alternating Turing Machine
:author Jeremy McMahan
"""
class Tree:
"""
Creates the tree from the root data and a list of subtrees. A leaf is denoted by having the empty list
as its children
:param root the data associated with the tree's root
:param children a list of trees to be the tree's subtrees
"""
def __init__(self, root, children=[]):
self.root = root
self.children = children
"""
Computes the depth of the Tree
:returns the depth
"""
def depth(self):
if self.children == []:
return 0
else:
return 1 + max([child.depth() for child in self.children])
"""
Determines if the tree is equal to other_tree
:param other_tree a tree
:returns True iff this tree and other_tree are equal
"""
def __eq__(self, other_tree):
if other_tree is None or self.root != other_tree.root:
return False
else:
if len(self.children) != len(other_tree.children):
return False
else:
for i in range(len(self.children)):
if self.children[i] != other_tree.children[i]:
return False
return True
"""
Determines if the tree is not equal to other_tree
:param other_tree a tree
:returns True iff this tree and other_tree are not equal
"""
def __ne__(self, other_tree):
return not self == other_tree
| true |
08a8f2c334e8bc7ea3e064c3fb0da40055e30618 | OneDayOneCode/1D1C_julio_2017 | /funciones.py | 1,132 | 4.25 | 4 | #-*-coding: utf-8 -*-
# Declarando una función en python 3
def operaciones(a, b):
# Las siguientes líneas imprimen suma de variables y concatenación
print ('la suma de', a, 'y', b, 'da como resultado:\n', a + b)
print ('la multiplicación de', a, 'y', b, 'da como resultado:\n', a * b)
print ('la división de', a, 'y', b, 'da como resultado:\n', a // b)
# Ingresando datos por teclado
num1 = int(input('Ingrese número 1 y de click en enter:\n'))
num2 = int(input('Ingrese número 2 y de click en enter:\n'))
# Mandamos a llamar la función con el paso de parametros (variables que ingresa el usuario)
operaciones(num1, num2)
# Declarando una función en python 3
def cadenas(cad):
# Se imprime la longitud en índices de nuestra cadena String
print ('Tu cadena', cad, 'tiene', len(cad), 'indices')
# Pasamos una cadena a mayúsculas
print ('en mayusculas tu cadena queda de la siguiente manera:\n', cad.upper())
# Ingresando datos por teclado
cadi = input('Ingrese una cadena de texto...\n')
# Llamando una función con el parametro de la cadena que ingresael usuario
cadenas(cadi)
| false |
9b2cb3097309c1b454167420187600bcb73293f4 | OneDayOneCode/1D1C_julio_2017 | /tablaMult.py | 1,222 | 4.46875 | 4 | # -*- coding: utf-8 -*-
# El siguiente programa es en la versión 2.7 de python, aún vigente
# se hace en esta versión para conocer la diferencia en la sintaxis
# Diferencias entre versión 2 y 3 de python
# Ambas utilizadas , diferencias como la falta de parentesis en la función print
# raw_input entre las versiones y las conversiones de str e int
# Ambas versiones se utilizan mucho es necesario conocer esas pequeñas diferencias entre la sintaxis
# este programa se ejecuta de la siguiente manera por línea de comandos
# python2 tablaMult.py
print "-------------------------------TABLAS DE MULTIPLICAR-----------------------"
# Con la sentencia raw_input le pedimos al usuario ingresar datos por teclado
# por defecto son String's , así que lo convertimos a enteros por que en este caso queremos un número
# todo esto lo guardamos en la variable 'num'
num = int(raw_input("Ingrese un número: "))
# Ciclo for en python3 , hace un recorrido en un rango del 1 al 10
# imprime la variable x que tiene el valor del rango del 1 al 10, concatenando
# con nuestro número ingresado y el resultado de la multiplicación de estos
for x in range(1,11):
print str(x) + " X " + str(num) + " = " + str((num * x))
| false |
70cbc8e51a38048c50c5bdd0cc765b97ecbe0fa2 | dylanplayer/ACS-1100 | /lesson-7/example_4.py | 337 | 4.1875 | 4 | # This while loop prints count until 100, but it breaks when
# the counter reaches 25
counter = 0
while counter < 100:
print(f"Counter: {counter}")
counter += 1
# If counter is 25, loop breaks
if counter == 25:
break
# Write a for loop that counts backwards from 50 to
# 0.
for num in range(50, 0, -1):
print(num) | true |
92ece88144930e7c5988738c24ca00c903a09d1c | dylanplayer/ACS-1100 | /lesson-10/example-3.py | 808 | 4.59375 | 5 | '''
Let's practice accessing values from a dictionary!
To access a value, we access it using its key.
'''
# Imagine that a customer places the following order
# at your empanada shop:
'''
Order:
1 cheese empanada
2 beef empanadas
'''
menu = {"chicken": 1.99, "beef":1.99, "cheese":1.00, "guava": 2.50}
# Get the price of a guava empanada
guava_price = menu['guava']
guava_order = 7
print(f"guava_price: {guava_price} order: {guava_order} total: {guava_order * guava_price}")
# TODO: Using the dictionary called menu, access the prices
# for cheese and beef. Print the prices to terminal.
print("Order: ")
print(menu["cheese"])
print(menu["beef"])
print("items = 2")
total = menu["cheese"] + menu["beef"]
print(f"Total = {total}")
# TODO: Calculate the total price of the order
# and print it.
| true |
90c220bac3f0f604e7ad0352859940d1729c40f9 | dylanplayer/ACS-1100 | /lesson-7/example_2.py | 403 | 4.25 | 4 | '''
Use while loops to solve the problems below.
'''
# TODO - Exercise 1: Repeatedly print the value of the variable price,
# decreasing it by 0.7 each time, as long as it remains positive.
from typing import Counter
price = 5
while price > 0:
print(price)
price -= 1
print("--------------")
# TODO - Exercise 2: Print ONLY even numbers from 0 to 20
for num in range(21):
print(num) | true |
7fe979cb792ebdf4ccaf4f199c7a43466da3a7c4 | dylanplayer/ACS-1100 | /lesson-2/example-4.py | 905 | 4.125 | 4 | # Types
# Challenge: Guess the type for each of these and define a value
# write the type as a comment then define a value.
# Then test your work
# For example
height_in_inches = 72
print("int")
print(type(height_in_inches))
# Your age: type and value
age = 15
print("int")
print(type(age))
# Your shoe size: Type and value
shoe_size = 14
print("int")
print(type(shoe_size))
# You birthday: Type and value
birthyear = "12/13/2002"
print("string")
print(type(birthyear))
# Is it spicy: Type and value
is_spicy = True
print("boolean")
print(type(is_spicy))
# Servings per container: Type and value
servings = 13
print("int")
print(type(servings))
# Percent of fuel remaining
fuel_remaining = .095
print("float")
print(type(fuel_remaining))
# Favorite color
fav_color = "blue"
print("string")
print(type(fav_color))
# URL
some_url = "htttps://dylanplayer.com"
print("string")
print(type(some_url))
| true |
714c14a6b333ab2ac08deb00a132cf5a9dbccc20 | dylanplayer/ACS-1100 | /lesson-2/example-10.py | 399 | 4.625 | 5 | print("Welcome to the snowboard length calculator!")
height = input("Please enter your height in inches: ")
height = float(height) # Converts str to float!
# Input sees the user input as a string
# Before we can calculate it, we need to convert it to the correct
# data type... in this case, height should be an float
print(f"The length of the snowboard you need is: {height * 2.54 * 0.88} cm") | true |
01b2a5e8659fedd193ada2f2bdf3869eab30f2ed | moritzemm/Ch.09_Functions | /9.7_BB8.py | 1,968 | 4.34375 | 4 | '''
BB8 DRAWING PROGRAM
-------------------
Back to the drawing board! Get it? Let's say we want to draw many BB8 robots
of varying sizes at various locations. We can make a function called draw_BB8().
We've made some basic changes to our original drawing program. We still have the
first two lines as importing arcade and opening an arcade window. We actually took
all of the other drawing code and put it in a function called main(). At the bottom
we call the main() function. In the main() function we call the draw_BB8() function
multiple times. We pass three parameters to it: x, y and radius. Write the code for
the draw_BB8() function so that the resulting picture looks as close as you can get
it to the one on the website.
'''
import arcade
arcade.open_window(600, 600, "BB8")
def draw_BB8(x,y, radius):
arcade.draw_circle_filled(x,y,radius,arcade.color.WHITE)
arcade.draw_circle_outline(x,y,radius,arcade.color.BLACK,2)
arcade.draw_circle_filled(x,y,radius*0.70, arcade.color.ORANGE)
arcade.draw_circle_outline(x, y, radius*.70, arcade.color.BLACK,2)
arcade.draw_circle_filled(x,y,radius*0.40,arcade.color.BABY_BLUE)
arcade.draw_circle_outline(x, y, radius*0.40, arcade.color.BLACK,2)
arcade.draw_arc_filled(x,y+radius*0.8,radius*0.85,radius*0.8,arcade.color.WHITE,0,180)
arcade.draw_arc_outline(x,y+radius*0.8,radius*0.85,radius*0.8,arcade.color.BLACK,0,180,2)
arcade.draw_circle_filled(x,y+radius*1.1,radius*0.20,arcade.color.BLUE)
arcade.draw_circle_outline(x,y+radius*1.1,radius*0.20,arcade.color.BLACK,2)
arcade.draw_line(x+radius*-0.85,y+radius*0.8,x+radius*0.85,y+radius*0.8,arcade.color.BLACK,2)
def main():
arcade.set_background_color(arcade.color.WHEAT)
arcade.start_render()
draw_BB8(100,50,50)
draw_BB8(300, 300, 30)
draw_BB8(500, 100, 20)
draw_BB8(500, 400, 60)
draw_BB8(120, 500, 15)
arcade.finish_render()
arcade.run()
if __name__== "__main__":
main() | true |
8fcfa372d51f99068336f9896d44edd6255c8d1f | rynoschni/python_dictionaries | /dictionary.py | 603 | 4.15625 | 4 | meal = {
"drink": "Beer",
"appetizer": "chips & salsa",
"entree": "fajita's",
# "dessert": "churros"
}
#print(meal["drink"])
#print("This Thursday, I will have a %s and %s for dinner!") % (meal("drink"), meal("entree"))
# if "dessert" in meal:
# print("Of course, Ryan had a dessert!! He ate %s" % (meal("dessert")))
# else:
# print("Ryan did not have dessert, and was sad!")
if "dessert" in meal:
print("Of course, Ryan had a dessert!! He ate %s" % (meal("dessert")))
else:
meal["dessert"] = "churros"
print(meal)
if 'dessert' in meal:
meal["dessert"] =
| true |
7828342c4fee61624aeae648a3374b40d7055478 | front440/PYTHON | /Primer_Trimestre/Prpgramas_Repetitivos/Ejercicio02_MayorOMenorque0.py | 1,420 | 4.15625 | 4 | # Programa: Ejercicio01_MayorOMenorque0.py
#
# Proposito: Realizar un algoritmo que pida números (se pedirá por
# teclado la cantidad de números a introducir). El programa debe
# informar de cuantos números introducidos son mayores que 0, menores
# que 0 e iguales a 0.
#
# Autor: Francisco Javier Campos Gutiérrez
#
# Fecha : 24/10/2019
#
# Variables, algoritmos a usar
# * contador <-- Variable para almacenar contador de 1 a 10
# * numero <-- Variable para almacenar numero introducido
# Analisis, Algoritmos
# Deberemos de pedir una serie de números, de estos pedidos deberemos
# decir cuales son mayores, iguales o menores.
# Entonces, crearemos un contador hasta 5, para que pare en esta cifra
# y según nos vaya dando datos, iremos diciendo si es mayor, igual o menor
# mediante un "if". Cuando el contador llegue a 5, parará el programa.
# Leer datos
print("Este programa nos dirá que números de los introducidos son mayores, iguales o menores que 0.")
print("-----------------------------------------------------------------")
contador = 0
for contador in range(0,5):
numero = int(input("Introduce el primer número: "))
print(f"-Número {contador+1} introducido-")
if numero < 0:
print("Numero introducido menor que 0")
elif numero == 0:
print("Número igual a 0")
else:
print("Número mayor que cero")
print("Has llegado al límite para introducir datos")
| false |
6bda29d8f766a2fdb3ac307fab5c770ff5c977a7 | front440/PYTHON | /Primer_Trimestre/Programas_Alternativas/Ejercicio08_Triangulos.py | 1,874 | 4.3125 | 4 | # Programa: Ejercicio08_Triangulos.py
# Proposito: Programa que lea 3 datos de entrada A, B y C. Estos
# corresponden a las dimensiones de los lados de un triángulo.
# El programa debe determinar que tipo de triangulo es, teniendo en
# cuenta los siguiente:
#
# Si se cumple Pitágoras entonces es triángulo rectángulo
# Si sólo dos lados del triángulo son iguales entonces es isósceles.
# Si los 3 lados son iguales entonces es equilátero.
# Si no se cumple ninguna de las condiciones anteriores, es escaleno.
#
# Autor: Francisco Javier Campos Gutiérrez
#
# Fecha : 18/10/2019
#
# Variables a usar
# * lado1 <-- Almacenamos el valor de lado1
# * lado2 <-- Almacenamos el valor de lado2
# * lado3 <-- Almacenamos el valor de lado3
#
# Algoritmo:
# Triángulo rectángulo:
# Debe de cumplirse Pitagoras por lo que: a**2 = (b**2)+(c**2)
# Tiángulo equilatero:
# Todos los lados son iguales.
# Triángulo isósceles:
# Si dos lados son iguales
# Triángulo Escaleno:
# Si no se cumple niguna de las anteriores condiciones
import math
# Leer datos
print("Este programa nos dirá que tipo de triángulo es al introducir sus datos")
print("-----------------------------------------------------------------------")
lado1 = float(input("Ingresa el valor del lado 1: "))
lado2 = float(input("Ingresa el valor del lado 2: "))
lado3 = float(input("Ingresa el valor del lado 3: "))
# Desarrollo
if math.pow(lado1,2)+math.pow(lado2,2)==math.pow(lado3,2) or math.pow(lado1,2)+math.pow(lado3,2)==math.pow(lado2,2) or math.pow(lado3,2)+math.pow(lado2,2)==math.pow(lado1,2):
print("Triángulo Rectángulo")
elif lado1 == lado2 == lado3:
print("Tendremos un triángilo equilatero.")
elif (lado1 == lado2 and lado1 != lado3) or (lado2 == lado1 and lado2 != lado3) or (lado3 == lado1 and lado3 != lado2):
print("El triágunlo sera isósceles")
else:
print("El triángulo es escaleno")
| false |
21f5e6be1e8e21fce1d7554e18c9d609411e4323 | front440/PYTHON | /Primer_Trimestre/Programas_Alternativas/Ejercicio02_NumeroPar.py | 691 | 4.1875 | 4 | # Programa: Ejercicio2_NumeroPar.py
# Proposito: Escribe un programa que lea un número e indique
# si es par o impar..
#
# Autor: Francisco Javier Campos Gutiérrez
#
# Fecha : 16/10/2019
#
#
# Variables a usar
# * n <--- Número introducido
#
# Algoritmo:
# n % 2
# Leer datos
print("En este ejercicio os mostraremos si el número es par o impar.")
print("-------------------------------------------------------------")
n = float(input("Introduce número: "))
print("-------------------------------------------------------------")
# Cálculo
if n % 2:
print("El número introducido es impar") #Imprimimos resultado falso
else:
print("El número introducido es par") #Imprimimos resultado verdadero
| false |
c2e7538357c9e8ef0db7fa23d077c7f1570ebfd7 | front440/PYTHON | /Primer_Trimestre/Programas_Secuenciales/Ejercicio12_PideNumeroXeY.py | 1,295 | 4.15625 | 4 | # Programa: Ejercicio12_PideNumeroXeY.py
#
# Proposito: Pide al usuario dos pares de números x1,y2 y x2,y2, que
# representen dos puntos en el plano. Calcula y muestra la distancia
# entre ellos.
#
# Autor: Francisco Javier Campos Gutiérrez
#
# Fecha : 10/10/2019
#
#
# Variables a usar
# * x1 <-- Coordenada asignada x1
# * y1 <-- Coordenada asignada y1
# -------------------------------
# * x2 <-- Coordenada asignada x2
# * y2 <-- Coordenada asignada y2
# * distancia <-- distancia entre punto1 y punto2
#
# Algoritmo:
# distancia = (1/2)**((x2 - x1)**2 + (y2 - y1)**2)
import math
# Leer datos
print("---------------------------------------")
print("---------- Datos para punto 1 ---------")
x1 = float(input("introduce el valor para x1:"))
x2 = float(input("introduce el valor para x2:"))
print("---------------------------------------")
print("---------- Datos para punto 2 ---------")
y1 = float(input("introduce el valor para y1:"))
y2 = float(input("introduce el valor para 21:"))
print("---------------------------------------")
# Cáculo de datos
distancia = ((x2 - x1)**2 + (y2 - y1)**2)**(1/2)
#distancia = math.sqrt(math.pow((x2 - x1),2)) + (math.pow((y2 - y1),2))
# Salida de datos
print("La distancia entre el punto 1 y el punto2 es: ", round(distancia, 2))
| false |
1a904488a7fb8e90dca5c40443afe59c5fc2603c | mluis98/AprendiendoPython | /practica/condiciones3.py | 938 | 4.125 | 4 | # El numero 0 se evalua como False
variable = 0
if variable:
print "La condicion 1 es verdadera"
else:
print "La condicion 1 es falsa"
# Cualquier numero que no sea cero se evalua como True
variable = -10
if variable:
print "La condicion 2 es verdadera"
else:
print "La condicion 2 es falsa"
# Un string vacio se evalua como False
variable = ""
if variable:
print "La condicion 3 es verdadera"
else:
print "La condicion 3 es falsa"
# Un string no vacio se evalua como Verdadero
variable = " "
if variable:
print "La condicion 4 es verdadera"
else:
print "La condicion 4 es falsa"
# Un string no vacio se evalua como Verdadero
variable = "Melvin"
if variable:
print "La condicion 5 es verdadera"
else:
print "La condicion 5 es falsa"
# Un valor no definido se evalua como False
variable = None
if variable:
print "La condicion 7 es verdadera"
else:
print "La condicion 7 es falsa"
| false |
e10ec57bd111df03b31fb9482c64fc39d5f1d0dd | thaimynguyen/Automate_Boring_Stuff_With_Python | /regrex_search.py | 1,578 | 4.25 | 4 | #! python 3.8
"""
Requirement:
_ Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression.
_ The results should be printed to the screen.
Link: https://automatetheboringstuff.com/2e/chapter9/#calibre_link-322
"""
import os, re
def search_txt(folder, regex):
os.chdir(folder)
files = os.listdir(folder)
txt_files = list(filter(lambda x: x.endswith(('.txt', '.TXT')), files))
for file in txt_files:
with open(file, 'r') as f:
lines = f.read().splitlines()
for line in lines:
if re.search(regex, line):
print(f'"{line}" from "{file}" file')
def prompt_input():
while True:
# Input folder path
folder_path = input('Enter the absolute path of the folder that you want to search: \n')
#folder_path = r'C:\Users\My\Desktop\Python projects\Automate_The_Boring_Stuff_With_Python\RegexSearch'
# Check if folder path exists:
if os.path.isdir(folder_path):
regex_pattern = input('Enter the regular expression pattern that you want to search:\n')
return folder_path, regex_pattern
else:
print("The path you entered is not valid!")
search_txt(*prompt_input())
#search_txt(r'C:\Users\My\Desktop\Python projects\Automate_The_Boring_Stuff_With_Python\RegexSearch', "\d")
# splitlines() will get a list of lines without "\n"
# readlines() will get a list of lines with "\n"
| true |
3e5075d3b68fd8d52eda91cc7c122d56951af2cb | codecherry12/Python_for_EveryBody | /AccessingFileData/filelist.py | 657 | 4.40625 | 4 | """8.4 Open the file romeo.txt and read it line by line. For each line,
split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see
if the word is already in the list and if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.py4e.com/code3/romeo.txt"""
fname = input("Enter file name: ")
fh =open(fname)
lst=list()
a=[]
for line in fh:
a+=line.split()
for i in range(len(a)):
if a[i] not in lst:
lst.append(a[i])
lst.sort()
print(lst)
| true |
d5bc47ab56ef47eb9e3997b84c58cd62437f85f6 | GitKurmax/coursera-python | /week02/task11.py | 500 | 4.1875 | 4 | # Даны координаты двух точек на плоскости, требуется определить,
# лежат ли они в одной координатной четверти или нет
# (все координаты отличны от нуля).
x1, y1, x2, y2 = int(input()), int(input()), int(input()), int(input())
if (x1 > 0 and x2 < 0) or (y1 > 0 and y2 < 0):
print("NO")
elif (x1 < 0 and x2 > 0) or (y1 < 0 and y2 > 0):
print("NO")
else:
print("YES")
| false |
8901f47cf34579292368352c41e9a5c0436883ce | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/05-Data-Structure/04-sets.py | 752 | 4.34375 | 4 | """
This doc provide detailed overview of sets in Python.
These are basically unordered collection of data items. Can't contain repeated values
Mutable data structures like lists or dictionaries can’t be added to a set.
However, adding a tuple is perfectly fine.
"""
# Syntax:
data_set = set()
data_set.add(5)
print(data_set)
data_set.update([True, 12, (5, "point", 'boil'), 100])
print(data_set)
# print integers only from set
for sets in data_set:
if isinstance(sets, int):
print(sets)
# Union and Intersection of sets
set_A = {1, 2, 3, 4}
set_B = {2, 8, 4, 16}
print(set_A.union(set_B))
print(set_A.intersection(set_B))
print(set_B & set_A)
print(set_B | set_A)
# Difference
print(set_A - set_B)
print(set_B.difference(set_A))
| true |
bb36bc53737c632b2113a43934c59f5fc461363c | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/07-Classes/01-python-classes.py | 521 | 4.40625 | 4 | """
In this Doc we'll cover all details about classes in Python.
Class Inheritance e.t.c.
"""
# start by creating a simple example of Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("David", 25)
print(p1.name)
# let's create a new class name Teacher and inherit it from person as every teacher must be person
class Teacher(Person):
pass
t1 = Teacher("Rehan", 24)
print(t1.name)
print(t1.age) # it's inherit properties of Person object
| true |
7c8c15582d92d04bf10ec58f1886a2fe54903edf | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/01-Introduction/writing-first-code.py | 449 | 4.25 | 4 | """
This file is created for practicing Python
Print statement
"""
# printing string
print("First Lesson")
# printing integers/float
print(300)
print(102.5784)
#using format
print('Data: {}'.format(10))
# Printing Multiple Pieces of Data
print('Integer: {}\nFloat: {}\nString: {}\nList: {}'.format(120, 14.25, 'Hello', [10, 23, 'World']))
# Use end in print statement to print multiple statements
print('Programming is ', end="")
print("life")
| true |
8a6f54f6ea0c18c4bfda517406ee9b30c2566f0d | c4llmeco4ch/eachDayInYear | /main.py | 1,339 | 4.6875 | 5 | #see attached jpg
'''
* @param day The day of the month we want to print
* @param month The string of the month we want to print
* i.e. "Jan"
* Given a "day" and "month", this function prints out
* The associated calendar day. So, passing 1 and "Feb"
* Prints "Feb 1st"
'''
def printDay(day, month):
ending = ""
if day == 1 or (day >= 20 and
day % 10 == 1):
ending = "st"
elif day % 10 == 2 and (day > 20 or day < 10):
ending = "nd"
elif day % 10 == 3 and (day > 20 or day < 10):
ending = "rd"
else:
ending = "th"
print(month + " " + str(day)
+ ending)
'''
* Goal: For all the days in the year, we want to
* print out the calendar day associated with that day in
* the year
* For example, the 32nd day of the year is Feb 1st
'''
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"]
daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, +
30, 31]
currentMonth = 0
runningTotal = 0
DEBUG = False
for day in range(1,366):
if day > runningTotal + daysInMonth[currentMonth]:
runningTotal += daysInMonth[currentMonth]
currentMonth += 1
if DEBUG:
print("Moving to " + months[currentMonth])
printDay(day - runningTotal, months[currentMonth])
| true |
fd384b8b89d722b99c77963f49a4d35ef3402341 | ananyasaigal001/Wave-1 | /Units_Of_Time_2.py | 437 | 4.21875 | 4 | #obtaining seconds
time_seconds=input("Enter the time in seconds: ")
time_seconds=int(time_seconds)
#computing the days,hours,minutes,and seconds
days="{0:0=2d}".format(time_seconds//86400)
hours="{0:0=2d}".format((time_seconds% 86400)//3600)
time_remaining=((time_seconds% 86400)%3600)
minutes="{0:0=2d}".format(time_remaining//60)
seconds="{0:0=2d}".format(time_remaining%60)
#output
print(days,":",hours,":",minutes,":",seconds)
| true |
6d8296c395ce9da9502dfe7c3a9ca32593c98884 | aragon08/Python3-101 | /PythonOOP/metodo.py | 694 | 4.125 | 4 | #metodos
# class Matematica:
# def suma(self):
# self.n1 = 2
# self.n2 = 3
# s = Matematica()
# s.suma()
# print(s.n1 + s.n2)
#**************************************
# __init__ constructor
# class Ropa:
# def __init__(self):
# self.marca = 'willow'
# self.talla = 'M'
# self.color = 'rojo'
# camisa = Ropa()
# print(camisa.talla)
# print(camisa.marca)
# print(camisa.color)
#**************************************
class Calculadora:
def __init__(self, n1,n2):
self.suma = n1 + n2
self.resta = n1 - n2
self.producto = n1 * n2
self.division = n1 / n2
operacion = Calculadora(10,3)
print(operacion.producto) | false |
8f257a0493eb3fd85030f0bdab42e973271ab95d | kgermeroth/Code-Challenges | /lazy-lemmings/lemmings.py | 2,027 | 4.3125 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
>>> furthest_optimized(7, [0, 6])
3
>>> furthest_optimized(3, [0, 1, 2])
0
>>> furthest_optimized(3, [2])
2
>>> furthest_optimized(3, [0])
2
>>> furthest_optimized(6, [2, 4])
2
"""
def furthest(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
# set a farthest counter
farthest = 0
# loop through lemming hole locations
for num in range(num_holes):
# find the shortest distance from lemming hole (num) to cafe
smallest_distance = num_holes - 1
for cafe in cafes:
distance = abs(cafe - num)
if distance < smallest_distance:
smallest_distance = distance
if smallest_distance > farthest:
farthest = smallest_distance
return farthest
def furthest_optimized(num_holes, cafes):
"""Find longest distance between a hole and a cafe."""
# set a farthest counter
farthest = 0
if len(cafes) == num_holes:
return farthest
cafe_indices = set(cafes)
# loop through lemming hole locations
for num in range(num_holes):
if num in cafe_indices:
continue
else:
# find the shortest distance from lemming hole (num) to cafe
smallest_distance = num_holes - 1
for cafe in cafes:
distance = abs(cafe - num)
if distance < smallest_distance:
smallest_distance = distance
if smallest_distance > farthest:
farthest = smallest_distance
return farthest
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED; GREAT JOB!\n")
| true |
4a499c580419ba601df9f6540540aa3342fcbb5b | saswat0/catalyst | /catalyst/contrib/utils/misc.py | 1,471 | 4.125 | 4 | from typing import Any, Iterable, List, Optional
from itertools import tee
def pairwise(iterable: Iterable[Any]) -> Iterable[Any]:
"""Iterate sequences by pairs.
Examples:
>>> for i in pairwise([1, 2, 5, -3]):
>>> print(i)
(1, 2)
(2, 5)
(5, -3)
Args:
iterable: Any iterable sequence
Returns:
pairwise iterator
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def make_tuple(tuple_like):
"""Creates a tuple if given ``tuple_like`` value isn't list or tuple.
Returns:
tuple or list
"""
tuple_like = (
tuple_like
if isinstance(tuple_like, (list, tuple))
else (tuple_like, tuple_like)
)
return tuple_like
def args_are_not_none(*args: Optional[Any]) -> bool:
"""Check that all arguments are not ``None``.
Args:
*args (Any): values
Returns:
bool: True if all value were not None, False otherwise
"""
if args is None:
return False
for arg in args:
if arg is None:
return False
return True
def find_value_ids(it: Iterable[Any], value: Any) -> List[int]:
"""
Args:
it: list of any
value: query element
Returns: indices of the all elements equal x0
"""
inds = [i for i, el in enumerate(it) if el == value]
return inds
__all__ = ["args_are_not_none", "make_tuple", "pairwise", "find_value_ids"]
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.