blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
829b630bbee495fec0f014527394a540d0df6b60 | hrithik0/newbieProjects | /if.py | 507 | 4.21875 | 4 | is_hot = bool
is_cold = bool
whether = input("How is the current whether? ").lower()
if whether == 'hot':
is_hot = True
is_cold = False
elif whether == 'cold':
is_cold = True
is_hot = False
else:
is_hot = is_cold = False
if is_hot:
print("It's a hot day.")
print("Drink plenty of water!")
elif is_cold:
print("It's a cold day.")
print("Wear warm clothes.")
elif not is_hot and not is_cold:
print("it's a lovely day.")
print("enjoy your day.") | true |
e4e08af8a583938934af4fc84fb124ffbad43cde | hrithik0/newbieProjects | /hello.py | 212 | 4.1875 | 4 | print("hello, {}".format(input("write your name? ")).split(","))
patient_name = "Jhon Smith"
age = 20
is_new_patient = True
if is_new_patient:
print(patient_name)
else:
print("not an existing patient") | false |
2cca8f03805672d3c42328c3612c7827d1205274 | grantferowich/python | /conditionals.py | 1,102 | 4.25 | 4 | # If/else condtions
# x = 10
# y = 20
# Comparison operators
#Simple if
# if x > y:
# print(f'{x} is greater than {y}')
# If/Else
# if x > y:
# print(f'{x} is greater than {y}')
# else:
# print(f'{y} is greater than {x}')
# Elif
# if x > y:
# print(f'{x} is greater than {y}')
# elif x == y:
# print(f'{x} is equal to {y}')
# else:
# print(f'{y} is greater than {x}')
# Nested if
# if x > 2:
# if x <= 10:
# print(f'{x} is greater than 2 and less than or equal to 10')
# Logical operators
# and
# if x > 2 and x <= 10:
# print(f'{x} is greater than 2 and less than or equal to 10')
# or
# if x > 2 or x <= 10:
# print(f'{x} is greater than 2 and less than or equal to 10')
# not
# if not (x == y):
# print(f'{x} is not equal to {y}')
# MEMBERSHIP OPERATORS - test if a sequence is present in an object
x = 13
y = 10
nums = [1, 2, 3, 4, 5]
# IN
# if x in nums:
# print(x in nums)
#NOT IN
# if x not in nums:
# print(x not in nums)
#IDENTITY OPERATORS
# is
if x is y:
print(x is y)
# is not
if x is not y:
print(x is not y)
| true |
2e8556af41e702cf915921972c50bf21dd311b65 | CharlesMontgomery2/Python-Class-Exercises | /Class/restaurant.py | 2,665 | 4.5625 | 5 | # 1) Make a class called Restaurant. The __init__() method for Restaurant should store two attributes:
# a restaurant_name and a cuisine_type. Make a method called describe_restaurant()
# that prints these two pieces of information, and a method called open_restaurant()
# that prints a message indicating that the restaurant is open.
# 2) Update the above program by creating three different instances from the class,
# and call describe_restaurant() for each instance.
class Restaurant(): # Define the Class
"""Class for a restaurant.""" # These will help in discribing what is going on without using comments
def __init__(self, name, cuisine_type): # provide the two perameters and one prefix perameter using the init method
"""Initialize name and cuisine_type."""
self.name = name.title() # use the prefix self that takes the value in the perameter
self.cuisine_type = cuisine_type # and assign it a variable along with title casing.
def describe_restaurant(self): # create a method using the prefix perameter
"""Display description of the restaurant."""
msg = f"{self.name} serves the most amazing {self.cuisine_type}." # create a variable for the message that will describe the restaurant
print(f"{msg}") # Display the message
def open_restaurant(self): # Create a method using the prefix perameter
"""Display a message to the restaurant is open."""
msg = f"{self.name} is open." # create a variable for the message
print(f"{msg}") # Display the message
big_bobs = Restaurant("Big Bob's BBQ Babyback Ribs", "BBQ Ribs") # create an instance in the restaurant class
print(big_bobs.name) # Display the restaurant name
print(big_bobs.cuisine_type) # Display the restaurant cusine_type
big_bobs.describe_restaurant() # call the method within the class
big_bobs.open_restaurant() # call the method within the class
print()
burgatory = Restaurant("burgatory", "Cheese Burgers") # create an instance in the restaurant class
print(burgatory.name) # Display the restaurant name
print(burgatory.cuisine_type) # Display the restaurant cusine_type
burgatory.describe_restaurant() # call the method within the class
burgatory.open_restaurant() # call the method within the class
print()
garden_of_eatin = Restaurant("the garden of eat'n", "Salads") # create an instance in the restaurant class
print(garden_of_eatin.name) # Display the restaurant name
print(garden_of_eatin.cuisine_type) # Display the restaurant cusine_type
garden_of_eatin.describe_restaurant() # call the method within the class
garden_of_eatin.open_restaurant() # call the method within the class
| true |
e3b5ce2ef149a66b723ac7ffd972d154148cc390 | CharlesMontgomery2/Python-Class-Exercises | /Lists and Tuples/buffet_food.py | 879 | 4.34375 | 4 | foods = ("chicken strips", "spaghetti", "pizza", "prime rib", "salad") # created a tuple for foods in a buffet
for food in foods: # looped through the tuple for each of the foods
print(food) # Displays each of the items per line in the tuple
print() # empty print statment will give a blank line and will allow an empty space between the 2 lists
try: # I went witha try catchf error handling statement so that my code will continue to run after an error is displayed
foods.append("icecream") # this throws the error because tuples can't be appended this way
finally: # finally will run the next code below
foods = ("chicken strips", "spaghetti", "fried rice", "prime rib", "mashed potatoes") # changed the tuple
for food in foods:# looped through the tuple for each of the foods
print(food)# Displays each of the items per line in the tuple
| true |
7b0779cb1405f7c347993c55720f5f122ad55513 | Divi2701/Algorithms | /Python/Sorting/bubble_sort.py | 1,183 | 4.125 | 4 | class BubbleSort:
"""
Bubble sort for a list of elements.
bubble_sort = BubbleSort([5,6,10,2,3])
>>> ascending_sort = bubble_sort.ascending()
[2,3,5,6,10]
>>> descending_sort = bubble_sort.descending()
[10,6,5,3,2]
"""
def __init__(self, arr=[13, 24, 21, 7, 8, 4]):
self.arr = arr
self.arr_length = len(self.arr)
def ascending(self) -> list:
for i in range(self.arr_length):
for j in range(i + 1, self.arr_length):
if self.arr[i] > self.arr[j]:
self.arr[i], self.arr[j] = self.arr[j], self.arr[i]
return self.arr
def descending(self) -> list:
for i in range(self.arr_length):
for j in range(i + 1, self.arr_length):
if self.arr[i] < self.arr[j]:
self.arr[i], self.arr[j] = self.arr[j], self.arr[i]
return self.arr
if __name__ == "__main__":
input_arr = list(map(int, input().strip().split()))
if not input_arr:
bubble_sort = BubbleSort()
else:
bubble_sort = BubbleSort(arr=input_arr)
print(bubble_sort.ascending())
print(bubble_sort.descending())
| false |
aff2f6f948ff14077f322be39a20cb8b6490973c | wendy696905/driving_licence_available | /driving.py | 446 | 4.21875 | 4 | country = input('Where are you from? ')
age = input('Your age: ')
age = int(age)
if country == 'Taiwan':
if age >= 18:
print('You can have a driving license.')
else:
print('You cannot have a driving license.')
elif country == 'America':
if age >= 16:
print('You can have a driving license.')
else:
print('You cannot have a driving license.')
else:
print('this can only track the country of Taiwan or America') | true |
6384f86f28ef17594897950fe3d98f0780e25d5b | igul222/Euler | /euler_common.py | 675 | 4.15625 | 4 | from math import sqrt
def is_prime(n):
if n < 2: return False
if n == 2: return True
if n%2 == 0: return False
for i in range(3,int(sqrt(n))+1, 2):
if n%i == 0:
return False
return True
# should give the same result as is_prime(n), provided you call it with every number between 2 and n (in ascending order) first.
_primes = [2]
def sequential_is_prime(n):
if n < 2: return False
if n == 2: return True
for prime in _primes:
if n%prime == 0: return False
_primes.append(n)
return True
def nth_prime(n):
i = _primes[-1] + 1
while len(_primes) <= n:
sequential_is_prime(i)
i += 1
return _primes[n] | false |
bbefcf612f1bf3b935befbd0a010da0790c57324 | nkrishnappa/100DaysOfCode | /Python/Day-#8/5-Caeser-Cipher-part-1.py | 1,944 | 4.46875 | 4 | alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#TODO-1.1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs.
def encrypt(text: str, shift: int) -> None:
#TODO-1.2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text.
cipher_text = ""
for letter in text:
encrypt_letter_index = (alphabet.index(letter) + shift) % 26
cipher_text += alphabet[encrypt_letter_index]
print(f"The enocoded text is {cipher_text}")
#TODO-2.1: Create a different function called 'decrypt' that takes the 'text' and 'shift' as inputs.
def decrypt(text: str, shift: int) -> None:
#TODO-2.2: Inside the 'decrypt' function, shift each letter of the 'text' *backwards* in the alphabet by the shift amount and print the decrypted text.
decrypt_text = ""
for letter in text:
decrypt_letter_index = (alphabet.index(letter) - shift) % 26
decrypt_text += alphabet[decrypt_letter_index]
print(f"The decrypted text is {decrypt_text}")
#TODO-2.3: Check if the user wanted to encrypt or decrypt the message by checking the 'direction' variable. Then call the correct function based on that 'drection' variable. You should be able to test the code to encrypt *AND* decrypt a message.
while True:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
if direction == "encode":
#TODO-1.3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message.
encrypt(text=text, shift=shift)
elif direction == "decode":
decrypt(text=text, shift=shift)
else:
print(f"invalid input : {direction}")
| true |
c433786e592bcce86414b0dad1c7ecb8ee05440f | nkrishnappa/100DaysOfCode | /Python/Day-#9/4-DictionaryInList.py | 1,151 | 4.65625 | 5 | '''
Instructions
You are going to write a program that adds to a travel_log. You can see a travel_log which is a List that contains 2 Dictionaries.
Write a function that will work with the following line of code on line 21 to add the entry for Russia to the travel_log.
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
You've visited Russia 2 times.
You've been to Moscow and Saint Petersburg.
DO NOT modify the travel_log directly. You need to create a function that modifies it.
'''
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
#🚨 Do NOT change the code above
#TODO: Write the function that will allow new countries
#to be added to the travel_log. 👇
def add_new_country(country: str, visits: int, cities: list) -> None:
travel_log.append(
{
"country" : country,
"visits" : visits,
"cities":cities,
})
#🚨 Do not change the code below
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
| true |
90ee31292c4387b45767fc91c094618c6a0c1528 | nkrishnappa/100DaysOfCode | /Python/Day-#4/2-coin.py | 409 | 4.25 | 4 | '''
write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".
Important, the first letter should be capitalised and spelt exactly like in the example e.g. Heads, not heads.
'''
#Write your code below this line 👇
#Hint: Remember to import the random module first. 🎲
import random
toss_it = random.randint(0,1)
if toss_it == 1 :
print("Heads")
else:
print("Tails") | true |
d6c5dd832481a4fef94ec7eb0fa40b31307f93ad | nkrishnappa/100DaysOfCode | /Python/Day-#4/7-RockPaperScissors.py | 1,583 | 4.5625 | 5 | '''
https://wrpsa.com/the-official-rules-of-rock-paper-scissors/
The outcome of the game is determined by 3 simple rules:
Rock wins against scissors.
Scissors win against paper.
Paper wins against rock.
'''
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
list_choices = [rock, paper, scissors]
your_choice = int(input("what fo you choose? type 0 for Rock, 1 for Paper or 2 for scissors.\n"))
print (list_choices[your_choice])
print("Computer chose:\n")
computer_choice = random.randint(0,2)
print (list_choices[computer_choice])
# Rock wins against scissors.
# Scissors win against paper.
# Paper wins against rock.
if (your_choice == computer_choice):
print("Draw")
elif (your_choice == 0 and computer_choice == 2) or (your_choice == 1 and computer_choice == 0) or (your_choice == 2 and computer_choice == 1):
print("You win!")
else:
print("You lose!")
# solution #2
# rock 0 > scissors 2
# scissors 2 > paper 1
# paper 1 > rock 0
# 0 > 2 , 1 > 0 , 2 > 1
if (your_choice == computer_choice ):
print("Draw")
elif (your_choice == 0 and computer_choice == 2):
print("You win!")
elif (your_choice == 2 and computer_choice == 0):
print("You lose!")
elif computer_choice > your_choice:
print("You lose!")
elif computer_choice < your_choice:
print("You win!")
| false |
5b884c29be578b3c73c0453d424b2a87d73f4fcd | BatesyBoy/Polygon-Maker | /main.py | 938 | 4.15625 | 4 | import turtle
print("============================\n========POLYGON MAKER=======\n============================")#Line 2: Makes Some Simple ASCII Art
t = turtle.Turtle()
while True:
sides=int(input("> INPUT POLYGON SIDES (3-12) "))#Lines 5-7: Polygon Options
thick=int(input("> INPUT PEN THICKNESS (1-10) "))
colour=input("> INPUT COLOUR ").lower()
if sides>12 or sides<3 or thick>10 or thick<1:#Lines 8-9: Checks For Invalid inputs
print("> INVALID INPUT- TRY AGAIN")
else:
t.color(colour)
t.pensize(thick)
for x in range(0,sides): #Lines 13-15: Draws Polygon
t.forward(500/sides)
t.right(360/sides)
rerun=input("> RERUN PROGRAM (Y/N) ").upper()#Lines 16-24: Checks If The Program Should Run Again And If So, If The Canvas Should Be Cleared.
if not rerun=="Y":
print("> PROGRAM ENDED")
break
else:
clear=input("> CLEAR CANVAS (Y/N)").upper()
if clear=="Y":
t.reset()
print("> RERUNNING PROGRAM") | true |
52459e98aadb715b06be258e16b4c63136a86033 | LuisWitts/Python- | /ex017 catetos e hipotenusas.py | 1,094 | 4.34375 | 4 | #esse foi eu tentando fazer
'''co = float(input('Informe o comprimento do cateto oposto : '))
ca = float(input('Informe o comprimento do cateto adjacente : '))
h = co**2 + ca**2
print('A hipotenusa é {}'.format(h))'''
#a hipotenusa é igual a raiz quadrada da soma dos quadrados dos catetos
'''co = float(input('Comprimento do cateto oposto: '))
ca = float(input('comprimento do cateto adjacente: '))
h = (co ** 2 + ca ** 2) ** (1/2)
print('A hipotenusa vai medir {:.2f} '.format(h))'''
#usando o módulo math com a funcionalidade hypot que calcula a hipotenusa de uma forma mais fácil
'''import math
co = float(input('Informe o comprimento do cateto oposto : '))
ca = float(input('Informe o comprimento do cateto adjacente : '))
h = math.hypot(co, ca)
print('A hipotenusa vai medir {:.2f}'.format(h))'''
#importando apenas a funcionalidade hypot do módulo math
from math import hypot
co = float(input('Informe o comprimento do cateto oposto : '))
ca = float(input('Informe o comprimento do cateto adjacente : '))
h = hypot(co, ca)
print('A hipotenusa vai medir {:.2f}'.format(h))
| false |
392c90315cfb9fa40529b737cfd3edb2dde8a4e3 | amir-mersad/ICS3U-ASS5-Python | /positive_negative_zero.py | 1,232 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Amir Mersad
# Created on: November 2019
# This program gets numbers from the user and gives
# the number of positive, negative, and zeros
def main():
# This program gets numbers from the user and gives
# the number of positive, negative, and zeros
zeros = 0
positive_numbers = 0
negative_numbers = 0
counter = input("How many numbers would you like to enter: ")
try:
counter = int(counter)
except(Exception):
print("Wrong input!!!\n")
return
if counter > 0:
for counter in range(1, counter + 1):
number = input("Please enter a number: ")
try:
number = int(number)
except(Exception):
print("Wrong input!!!")
return
if number == 0:
zeros += 1
elif number > 0:
positive_numbers += 1
elif number < 0:
negative_numbers += 1
print("\npositive numbers:", positive_numbers)
print("zeros:", zeros)
print("negative numbers:", negative_numbers)
else:
print("\nnumber should be more than 0!")
if __name__ == "__main__":
main()
| true |
900ec1a1d384830558917038ac0675ac2ee1c524 | cuixd/PythonStudy | /6.函数.装饰器.偏函数.异常与文件读取/exception.py | 1,298 | 4.5 | 4 | # python 异常处理格式
# 1
'''
try:
代码
except 错误码1 as e:
错误处理代码1
except 错误码2 as e:
错误处理代码2
......
else:
没有出现异常是才执行的代码
'''
try:
print(num)
except NameError as e:
print("没有这个变量啊", e)
else:
print("没问题啊")
num = 1
try:
print(num)
except NameError as e:
print("没有这个变量啊", e)
else:
print("没问题啊")
# 2 不明确指定捕获哪些异常,统一处理
'''
try:
代码
except:
错误处理代码
else:
没有出现异常是才执行的代码
'''
# 3 一次捕获多个异常
'''
try:
代码
except (错误码1, 错误码2):
错误处理代码
else:
没有出现异常是才执行的代码
'''
# 如果异常没有被成功捕获,那么害死会报错,下面这个例子只对变量未定义的异常进行了捕获
# 因此,数组下标越界的错误还是会报错,从而程序终止
try:
list = [1, 2, 3]
print(list[3])
except NameError as e:
print(e)
else:
print("正常啊")
print("看来我是打印不出来了")
# finally
'''
try:
代码
except 错误码1 as e:
错误处理代码1
except 错误码2 as e:
错误处理代码2
......
finally:
始终要执行的的代码
''' | false |
10cda77b1788f699c90bfea882d1c1e6b6bd84f5 | cuixd/PythonStudy | /11.面向对象类的属性、继承/private_attr.py | 2,301 | 4.21875 | 4 | class Person():
def __init__(self,name,age,money):
self.name = name
self.age = age
# 属性前加__双下划线,则是一个私有属性,类的外部如法通过实例名.私有属性的方式获取值
self.__money = money
def __str__(self):
# 在类的方法内部可以直接获取私有属性的值
return "My name is %s,I am %d years old, I hava %d yuan" %(self.name, self.age, self.__money)
'''
成员属性的get set方法
'''
def eat(self, food):
print(self.name + "吃" + food)
def getMoney(self):
return self.__money
def setMoney(self,money):
if money < 0:
money = 0
self.__money = money
'''
私有属性的另一种访问方式,这种方式可以允许通过实例变量名.属性的方式直接获取和设置属性
'''
# 定义与私有属性同名(舍去双下划线)的方法,结合@property提示(装饰器),来实现get方法
@property
def money(self):
return self.__money
# 定义私有属性同名(舍去双下划线)带参方法,结合@属性.setter提示来实现set方法
@money.setter
def money(self, money):
if money < 0:
money = 0
self.__money = money
if __name__ == "__main__":
p1 = Person("cuixd",33,200)
print(p1)
# 类的外部如法通过实例名.私有属性的方式获取值,也就是无法获取该变量,pycharm甚至都没有提示该属性
# print(p1.__money)
# 而这里可以赋值和获取值,是因为python是解释型动态语言,
# 可以动态的为对象添加属性,这里的__money并不是类中的那个私有属性
p1.__money = 10
print(p1.__money)
# 再次打印对象的信息,可以发现对象的私有属性__money依然是200
print(p1)
# 只能通过set方法修改私有属性的值
p1.setMoney(10)
print(p1)
# 私有成员属性被Python解释器改名为, _类名__属性名,如下方式还是可以直接访问到私有属性并可以直接修改,不建议使用
print(p1._Person__money)
# 使用实例.属性(舍去双下划线)的方式访问和设置私有属性
print(p1.money)
p1.money = -100
print(p1.money)
| false |
1fc1bd9235c823bff156a610db34f3d2b02788db | syed0019/Unscramble_Computer_Science_Problems | /Task2.py | 1,197 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
from operator import itemgetter
def number_with_max_duration(calls_records):
call_duration = 0
new_dict = {}
for lst in calls_records:
for n in lst[0:2]:
new_dict[n] = call_duration
for lst in calls_records:
for n in lst[0:2]:
if n in new_dict:
call_duration = int(lst[3])
new_dict[n] += call_duration
print('{} spent the longest time, {} seconds, on the phone during September 2016.'
.format(max(new_dict.items(), key=itemgetter(1))[0], max(new_dict.items(), key=itemgetter(1))[1]))
number_with_max_duration(calls)
| true |
13e0751caa29cf12b90b21c82c918b82556d222d | rakash/Data-Analysis-using-Python-Coursework | /Assignment3/Assignment3Q2Part2.py | 2,080 | 4.1875 | 4 |
# coding: utf-8
# **Question2 PART TWO**
#
# • Use 'employee_compensation' data set.
#
# • Data contains fiscal and calendar year information. Same employee details exist twice in the dataset. Filter data by calendar year and find average salary (you might have to find average for each of the columns for every employee. Eg. Average of Total Benefits, Average of total compensation etc.) for every employee.
#
# • Now, find the people whose overtime salary is greater than 5% of salaries (salaries refers to ’Salaries' column)
#
# • For each ‘Job Family’ these people are associated with, calculate the percentage of total benefits with respect to total compensation (so for each job family you have to calculate average total benefits and average total compensation). Create a new column to hold the percentage value.
#
# • Display the top 5 Job Families according to this percentage value using df.head().
#
# • Write the output (jobs and percentage value) to a csv.
# In[2]:
#import libraries
from pandas import Series, DataFrame
import pandas as pd
# In[3]:
# read data from csv
employee_comp=pd.read_csv("Data/employee_compensation.csv")
print(employee_comp.head())
# In[11]:
# check if the year type is Calendar and group by Employee Identifier
print(employee_comp[employee_comp['Year Type']=='Calendar'].groupby(['Employee Identifier']).mean().reset_index().head())
# In[12]:
#check if the Overtime is 5% mpre than Salaries
employee_comp=employee_comp[employee_comp['Overtime']>0.05*employee_comp['Salaries']]
print(employee_comp.head())
# In[27]:
# group by family to calculate the mean
mean_job=pd.DataFrame(employee_comp.groupby(['Job Family']).mean().reset_index())
mean_job['Percent_Total_Benefit']=(mean_job['Total Benefits']/mean_job['Total Compensation'])*100 #calculate the percentage of total benefits over total compensation
# In[30]:
Family_data=mean_job.drop(mean_job.columns[[1,2,3,4,5,6,7,8,9,10,11]],axis=1).head()
# In[31]:
Family_data.to_csv("Data/Question2Part2.csv") # export the data to csv
# In[ ]:
| true |
36abd5a6c78e46035f112ec7c1a225b3969990ec | evalemon/uband-python-s1 | /homeworks/A10418/checkin10/day19-homework-eva.py | 1,148 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class Fish():
def __init__(self, name, location):
self.name = name
self.location = location
def jump(self):
print '来自 %s 的鱼 %s 开始跳起来了' %(self.location, self.name)
class Bird():
def __init__(self, name):
self.name = name
def fly(self, height):
print '%s 飞了 %d 米'%(self.name, height)
def down(self):
print '%s 摔死了'%(self.name)
class Dog():
def __init__(self, name, kind):
self.name=name
self.kind=kind
def run(self):
print '小明回到家,他的宠物狗 %s 犬 %s 奔向他'%(self.kind, self.name)
def jump(self):
print '%s 看到小明非常开心,在小明脚边不停的蹦跳'%(self.name)
def eat(self,meat):
print '小明抱起 %s 走向厨房,喂它 %s '%(self.name, meat)
def bark(self,times):
print '%s 非常满意,高兴的叫了 %d 声'%(self.name, times)
def main():
# angle=Bird('angle')
# angle.fly(800)
# angle.down()
# bubu=Fish('bubu', 'Shanghai')
# bubu.jump()
meimei=Dog('meimei', '贵宾')
meimei.run()
meimei.jump()
meimei.eat('pork')
meimei.bark(3)
if __name__ == '__main__':
main() | false |
08139af469e1b36e6ca8e999ec854ddbb020aedc | rpearodrguez/Python-Proyects | /caesar_cipher.py | 2,321 | 4.28125 | 4 | '''
*Caesar cipher** - Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25.
This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th
next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encoded
message can either use frequency analysis to guess the key, or just try all 25 keys
'''
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
code = ""
lag = 0
def cipher(code, key):
#funcion para cifrar texto
print("Su palabra original era: \n"+code)
cifrado = ''
#revisa el texto
for letter in code.lower():
#busca letra por letra en el alfabeto
if letter == ' ':
cifrado = cifrado+' '
if letter in alphabet:
#revisa el indice, si supera al numero de letras del alfabeto, vuelve atrás
if alphabet.index(letter)+key<= 25:
cifrado = cifrado+alphabet[alphabet.index(letter) + key]
elif alphabet.index(letter)+key > 25:
cifrado = cifrado+alphabet[alphabet.index(letter) + key - 26]
print("Su cifrado ya realizado es: \n"+cifrado)
#devuelve el texto ya cifrado
return cifrado
def decipher(code, key):
# funcion para cifrar texto
print("Su palabra original era: \n" + code)
cifrado = ''
# revisa el texto
for letter in code.lower():
# busca letra por letra en el alfabeto
if letter == ' ':
cifrado = cifrado + ' '
if letter in alphabet:
# revisa el indice, si supera al numero de letras del alfabeto, vuelve atrás
if alphabet.index(letter) + key <= 25:
cifrado = cifrado + alphabet[alphabet.index(letter) - key]
elif alphabet.index(letter) + key > 25:
cifrado = cifrado + alphabet[alphabet.index(letter) - key + 26]
print("Su cifrado ya realizado es: \n" + cifrado)
# devuelve el texto ya cifrado
return cifrado
cipher("Todo el mundo coma tierra",2)
cipher("hi",20)
cipher("az",1)
decipher("ba",1) | true |
1c13a54fe95f1a10590edcb03fad1ea6dc2f37e8 | sositon/Intro2CS | /Ex_2/calculate_mathematical_expression.py | 1,477 | 4.53125 | 5 | #################################################################
# FILE : calculate_mathematical_expression.py
# WRITER : Omer Siton , omer_siton , 316123819
# EXERCISE : intro2cs2 ex2 2021
# DESCRIPTION: A simple program that contains two mathematical functions
# STUDENTS I DISCUSSED THE EXERCISE WITH: None
# WEB PAGES I USED: https://en.wikipedia.org/wiki/Binary_operation,
# https://en.wikipedia.org/wiki/Operand
# NOTES: None
#################################################################
def calculate_mathematical_expression(operand_1, operand_2, binary_operation):
"""this function gets 3 parameters, the first two are numbers(int or float)
and the third one is a character that represent the desired operation.
return the mathematical result."""
if binary_operation == '+':
return operand_1 + operand_2
elif binary_operation == '-':
return operand_1 - operand_2
elif binary_operation == '*':
return operand_1 * operand_2
elif binary_operation == ':' and operand_2 != 0:
return operand_1 / operand_2
else:
return None
def calculate_from_string(string):
"""this function gets a string with two operands and an operation separated
by spaces. return the mathematical result."""
string = string.split(" ")
return calculate_mathematical_expression(float(string[0]),
float(string[2]), string[1])
| true |
2847a35ed290bd45070f76872ffd98d27a326a35 | nikolettlakos/Python-basic-exercises | /list_overlapping.py | 573 | 4.21875 | 4 | ''' Define a function overlapping() that takes two lists and returns True if they have at least one member in common,
False otherwise. You may use your is_member() function,
or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops. '''
def overlapping(list_a, list_b):
for i in list_a:
for j in list_b:
if i == j:
return True
return False
def main():
a = ["something", "cat", 1, 2, 5.4]
b = ["2"]
print(overlapping(a, b))
if __name__ == '__main__':
main() | true |
e2722ccae3b1150bee987f190d8ede9ffe02efda | vsdrun/lc_public | /hash/409_Longest_Palindrome.py | 1,509 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/longest-palindrome/description/
Given a string which consists of lowercase or uppercase letters,
find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
"""
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
sdict = {}
for c in s:
if c in sdict:
sdict[c] += 1
else:
sdict[c] = 1
length = 0
# 以判斷 奇數偶數
odd = False
for _, v in sdict.iteritems():
if not v % 2:
length += v
else:
if v == 1 and not odd:
length += v
odd = True
else:
oddadd = v - 1
length += oddadd
if not odd:
length += 1
odd = True
return length
def build_input():
return "bananas" # 5
return "AAAccccdd"
if __name__ == "__main__":
s = build_input()
r = Solution()
result = r.longestPalindrome(s)
print(result)
| true |
498174abb526903508a0e990f9039d5808307655 | vsdrun/lc_public | /hash/350_Intersection_of_Two_Arrays_II.py | 1,476 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/intersection-of-two-arrays-ii/
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk,
and the memory is limited such that you cannot load all elements into the memory at once?
"""
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
from collections import Counter as CC
nums1, nums2 = (nums1, nums2) if len(nums1) >= len(nums2) else \
(nums2, nums1)
n2dmap = CC(nums2)
result = []
for n1 in nums1:
if n1 in n2dmap:
result.append(n1)
n2dmap.subtract([n1])
if n2dmap[n1] == 0:
n2dmap.pop(n1)
return result
def build():
return [4,9,5], [9,4,9,8,4]
if __name__ == "__main__":
s = Solution()
print(s.intersect(*build()))
| true |
7c03e289dfd4a0adebccfad75bf9dac2d37dfd0f | vsdrun/lc_public | /array/73_Set_Matrix_Zeroes.py | 1,206 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/set-matrix-zeroes/description/
Given a m x n matrix,
if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
"""
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows = set()
cols = set()
for i, r in enumerate(matrix):
if 0 in r:
rows.add(i)
for i, c in enumerate(zip(*matrix)):
if 0 in c:
cols.add(i)
for e in rows:
matrix[e][:] = [0] * len(matrix[0])
for c in cols:
for r in matrix:
r[c] = 0
def build():
return [
[1, 0, 2, 0],
[3, 4, 5, 2],
[1, 3, 1, 5]
]
if __name__ == "__main__":
nums = build()
s = Solution()
s.setZeroes(nums)
print(nums)
| true |
a6d8bfc86a2977029eccdf114478f3355842733e | vsdrun/lc_public | /co_linkedin/8_String_to_Integer_atoi.py | 2,763 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/string-to-integer-atoi/description/
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until
the first non-whitespace character is found.
Then, starting from this character,
takes an optional initial plus or minus sign followed by as many
numerical digits as possible,
and interprets them as a numerical value.
The string can contain additional characters after those that form the
integral number,
which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a
valid integral number,
or if no such sequence exists because either str is empty or
it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Only the space character ' ' is considered as whitespace character.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is
not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign.
Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a
32-bit signed integer.
Thefore INT_MIN (−231) is returned.
"""
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if not str:
return 0
# https://docs.python.org/2/library/itertools.html
# takewhile() pred, seq seq[0], seq[1], until pred fails
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
from itertools import takewhile as tw
s = str.lstrip()
sign = list(tw(lambda x: x in '+-', s))
digits = list(tw(lambda x: x in '0123456789', s[1:] if sign else s))
try:
result = int((sign[0] if sign else "") + "".join(digits))
except Exception:
return 0
return max(min(result, 2**31 - 1), -2**31)
def build():
return "+words and 987"
return "42"
return "+-o"
return "-42"
return " "
return " -42"
return "-91283472332"
return "-123"
if __name__ == "__main__":
s = Solution()
print(s.myAtoi(build()))
| true |
dff3d1c0b6ee2ac36c49c18f554359b00d5bb41e | vsdrun/lc_public | /hash/166_Fraction_to_Recurring_Decimal.py | 1,614 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/fraction-to-recurring-decimal/description/
Given two integers representing the numerator and denominator of a fraction,
return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
"""
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
# 判斷 +-
sign = '-' if numerator * denominator < 0 else ''
q, r = divmod(abs(numerator), abs(denominator))
result = [sign, str(q)]
if r:
result.append(".")
remainder = [] # 看是否重複.
while r:
remainder.append(r)
q, r = divmod(r * 10, abs(denominator))
result.append(str(q))
if r in remainder:
back_index = len(remainder) - remainder.index(r)
result = result[:-back_index] + \
["("] + result[-back_index:] + [")"]
break
return "".join(result)
def build_input():
# return (1, 99)
# return (-2, 3)
# return (0, 2)
# return (2, 1)
# return (1, 2)
return (2, 3)
if __name__ == "__main__":
n, d = build_input()
s = Solution()
result = s.fractionToDecimal(n, d)
print(result)
| true |
1ee8ecc9fd8827d4cdc627d6f85509fc202d59e4 | vsdrun/lc_public | /co_google/310_Minimum_Height_Trees.py | 2,384 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/minimum-height-trees/description/
For a undirected graph with tree characteristics, we can choose any node
as the root.
The result graph is then a rooted tree. Among all possible
rooted trees, those with minimum height are called minimum height trees
(MHTs).
即哪個點為root時其高度最小(不是所有高度的和! 是單一最長高度最小!)
Given such a graph, write a function to find all the MHTs and
return a list of their root labels.
**
The basic idea is "keep deleting leaves layer-by-layer, until reach the root."
--
Format
The graph contains n nodes which are labeled from 0 to n - 1.
You will be given the number n and a list of undirected edges
(each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges.
Since all edges are undirected, [0, 1] is the same as [1, 0]
and thus will not appear together in edges.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
return [3, 4]
"""
class Solution(object):
def findMinHeightTrees(self, n, edges):
from collections import defaultdict as dd
nodes = set(range(n))
dmap = dd(set)
for (f, e) in edges:
dmap[f].add(e)
dmap[e].add(f)
# 所謂leaf node為connection只有一個link
while len(nodes) > 2:
# 找出leaf nodes
leave = []
remove = dd(set)
for k in dmap.keys():
if len(dmap[k]) == 1:
leave.append(k)
for p in dmap[k]:
remove[p].add(k)
dmap.pop(k)
nodes -= set(leave)
# remove leaves
for k in remove:
for v in remove[k]:
dmap[k].remove(v)
return list(nodes)
def build():
return 6, [[0,1],[0,2],[0,3],[3,4],[4,5]]
return 6, [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
return 5, [[0, 1], [1, 2], [1, 3], [3, 4]]
return 4, [[1, 0], [1, 2], [1, 3]]
if __name__ == "__main__":
s = Solution()
print(s.findMinHeightTrees(*build()))
| true |
fddf5e84e2b195b3c29548a6a88717d11d6cb2c9 | vsdrun/lc_public | /co_ms/328_Odd_Even_Linked_List.py | 1,843 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/odd-even-linked-list/description/
Given a singly linked list, group all odd nodes together followed by the
even nodes.
Please note here we are talking about the node number
and not the value in the nodes.
You should try to do it in place.
The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return
def change(node):
"""
modify odd/even node's next
"""
theeven = peven = None
lastodd = None
while node:
even= node.next if node else None
if peven:
peven.next = even
if not theeven:
theeven = even
peven = even
node.next = node.next.next if node.next else None
lastodd = node
node = node.next
lastodd.next = theeven
change(head)
return head
def build():
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
return head
if __name__ == "__main__":
s = Solution()
r = s.oddEvenList(build())
result = []
while r:
result.append(r.val)
r = r.next
print(result)
| true |
188405ec2c5c2996c0bdbc9c4df5fbeace808420 | vsdrun/lc_public | /binary_search_tree/275_H-Index2.py | 2,466 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/h-index-ii/description/
Follow up for H-Index:
What if the citations array is sorted in ascending order?
Could you optimize your algorithm?
---------
Given an array of citations (each citation is a non-negative integer)
of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia:
"A scientist has index h
if h of his/her N papers have at least
h citations each,
and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5],
which means the researcher has 5 papers in total and each of them had
received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3
citations each and the remaining two with no more than 3
citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as
the h-index.
h: 即須有h個paper其citation要大於等於h
剩下的 N-h paper 其 citation < h citations.
"""
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
ll, r = 0, n - 1
while ll <= r:
mid = (ll + r) / 2
if citations[mid] > n - mid:
r = mid - 1
elif citations[mid] < n - mid:
ll = mid + 1
else:
return n - mid
return n - ll
def hIndex_2(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
length = len(citations)
left = 0
right = length - 1
while left <= right: # 考慮只有 [100], [0]等 這種case.
mid = left + (right - left) / 2
if citations[mid] >= (length - mid) and \
len(citations[mid:]) == (length - mid):
right = mid - 1 # mid 是中了 故下一個不含mid
else:
left = mid + 1 # mid 沒中 下一個不含mid
ans = length - left
return ans
def build_input():
return [1, 2]
return [1]
return [0]
return [0, 1, 3, 5, 6]
return [100]
return [3, 0, 6, 1, 5]
if __name__ == "__main__":
n = build_input()
s = Solution()
result = s.hIndex(n)
print(result)
| true |
64d1404b40f27d43df616fedd80ea35035900444 | vsdrun/lc_public | /co_linkedin/205_Isomorphic_Strings.py | 1,370 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/isomorphic-strings/description/
Given two strings s and t, determine if they are isomorphic.
isomorphic: corresponding or similar in form and relations.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while
preserving the order of characters.
No two characters may map to the same character but a
character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
"""
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
d1, d2 = {}, {}
for i, val in enumerate(s):
d1[val] = d1.get(val, []) + [i]
for i, val in enumerate(t):
d2[val] = d2.get(val, []) + [i]
print(d1)
print(d2)
print(d1.values())
print(d2.values())
return sorted(d1.values()) == sorted(d2.values())
# or
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
def build():
return "egg", "add"
return "paper", "title"
return "ab", "aa"
if __name__ == "__main__":
s = Solution()
print(s.isIsomorphic(*build()))
| true |
165bd19a405a7e96a5c473552e095547ada27adc | vsdrun/lc_public | /co_fb/295_Find_Median_from_Data_Stream.py | 2,092 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Median is the middle value in an ordered integer list.
If the size of the list is even, there is no middle value.
So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
"""
import heapq
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.lower_q = [] # max heap
self.higher_q = [] # min heap
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
l_len = len(self.lower_q)
h_len = len(self.higher_q)
if l_len < h_len:
heapq.heappush(self.higher_q, num)
heapq.heappush(self.lower_q, -heapq.heappop(self.higher_q))
elif l_len >= h_len: # l_len > h_len
if len(self.higher_q) and num < self.higher_q[0]:
heapq.heappush(self.lower_q, -num)
heapq.heappush(self.higher_q, -heapq.heappop(self.lower_q))
else:
heapq.heappush(self.higher_q, num)
l_len = len(self.lower_q)
h_len = len(self.higher_q)
if l_len == h_len:
self.result = (-self.lower_q[0] + self.higher_q[0]) / 2.0
else:
self.result = self.higher_q[0]
def findMedian(self):
"""
:rtype: float
"""
return self.result
def build_list():
l = [6, 10, 2, 6, 5, 0, 6, 3, 1, 0, 0]
# l = [-1, -2, -3, -4, -5]
return l
if __name__ == "__main__":
input_list = build_list()
print("input: {0}".format(input_list))
s = MedianFinder()
for i in input_list:
s.addNum(i)
result = s.findMedian()
print(result)
| true |
61c1d42404a9ee5a05744846234fe4e99c8064c0 | vsdrun/lc_public | /hash/358_Rearrange_String_k_Distance_Apart.py | 1,248 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/rearrange-string-k-distance-apart/description/
Given a non-empty string s and an integer k,
rearrange the string such that the same characters are at
least distance k from each other.
All input strings are given in lowercase letters.
If it is not possible to rearrange the string, return an empty string "".
Example 1:
s = "aabbcc", k = 3
Result: "abcabc"
The same letters are at least distance 3 from each other.
Example 2:
s = "aaabc", k = 3
Answer: ""
It is not possible to rearrange the string.
Example 3:
s = "aaadbbcc", k = 2
Answer: "abacabcd"
Another possible answer is: "abcabcda"
The same letters are at least distance 2 from each other.
"""
class Solution(object):
def rearrangeString(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
import collections as cc
s = list(s)
s.sort()
result = cc.Counter(s)
print(dir(result))
print(result.most_common())
def build():
return "aaadbbcc", 2
return "aaabc", 3
return "aabbcc", 3
if __name__ == "__main__":
s = Solution()
result = s.rearrangeString(*build())
print(result)
| true |
427bbf607bccaa40c6c39e7f0b1714d5d3db67f6 | vsdrun/lc_public | /co_apple/question1.py | 2,064 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
1) given a binary tree, each tree node has an integer value
2) we define a path as a series of node that starts from root node, ends at a leaf node
3) add the numbers up along the path
4) return the sum of the longest path
e.g. you have a tree looks like this:
1
/ \
2 3
\ / \
5 6 7
/
1
there are 3 paths in this tree: (1,2,5,1), (1,3,6), (1,3,7)
add them up, you will get 3 sums: 9(1+2+5+1), 10(1+3+6), 11(1+3+7)
then the function should return 9, which is the longest path with lengh of 4
5) if there are multiple paths that have the same longest length, please return the largest sum among those sums
"""
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution(object):
def maxSum(self, root):
"""
using bfs due to we have multiple values at last layer,
pick the maximum one.
"""
nodes = [root]
prev = None
while nodes:
tmp = []
prev = nodes
for n in nodes:
if n.left:
n.left.val += n.val
tmp.append(n.left)
if n.right:
n.right.val += n.val
tmp.append(n.right)
nodes = tmp
return max(n.val for n in prev)
def build():
"""
1
/ \
2 3
\ / \
5 6 107
/ /
1 42
"""
_1_1 = Node(1)
_1_2 = Node(1)
_2 = Node(2)
_3 = Node(3)
_5 = Node(5)
_6 = Node(6)
_107 = Node(107)
_42 = Node(42)
_1_1.left = _2
_1_1.right = _3
_2.right = _5
_5.left = _1_2
_3.left = _6
_3.right = _107
_6.left = _42
return _1_1
if __name__ == "__main__":
s = Solution()
print(s.maxSum(build()))
| true |
ae66aa76e3002c3a54b85b4f548ece716f00c884 | vsdrun/lc_public | /co_fb/246_Strobogrammatic_Number.py | 1,308 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/strobogrammatic-number/description/
A strobogrammatic number is a number that looks the
same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic.
The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
"6699"
"66199"
"""
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
0 0 不能為第一個.
1 1
6 9
9 6
8 8
"""
from __builtin__ import xrange
dmap = dict((('0', '0'), ('1', '1'), ('6', '9'),
('9', '6'), ('8', '8')))
if num[0] == '0' and len(num) > 1:
return False
if len(num) % 2:
# corner cases
if num[len(num) / 2] not in ('0', '1', '8'):
return False
for i in xrange(len(num) / 2):
if num[i] not in dmap or num[~i] != dmap[num[i]]:
return False
# -i 保 減 1 去
return True
def build():
return '080' # False
return '25'
if __name__ == "__main__":
s = Solution()
print(s.isStrobogrammatic(build()))
| true |
31f7fedc4acec779d4916c617be0d3bbc17ab74c | vsdrun/lc_public | /tree/114_Flatten_Binary_Tree_to_Linked_List.py | 1,945 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def flatten(self, root):
def dfs(node):
if not node:
return
# return last node
oright = node.right
leftEnd = None
rightEnd = None
if node.left:
node.right = node.left
leftEnd = dfs(node.left)
node.left = None
if oright:
rightEnd = dfs(oright)
if leftEnd:
leftEnd.right = oright
return rightEnd if rightEnd else leftEnd if leftEnd else node
dfs(root)
def build():
"""
1
/ \
2 5
/ \ \
3 4 6
1
/
2
/
3
"""
_1= TreeNode(1)
_2= TreeNode(2)
_3= TreeNode(3)
_1.left = _2
_2.left= _3
return _1
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right = TreeNode(5)
root.right.right = TreeNode(6)
return root
def pr(t):
while t:
print(t.val)
if t.right:
t = t.right
else:
break
def debug(t):
r = [t]
while r:
print([n.val for n in r])
r = [N for n in r for N in (n.left, n.right) if N]
if __name__ == "__main__":
s = Solution()
t = build()
s.flatten(t)
pr(t)
| true |
95dee3f0ae928d02e7a72203593b0cfe6dd9418d | vsdrun/lc_public | /co_ms/784_Letter_Case_Permutation.py | 1,144 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
"""
https://leetcode.com/problems/letter-case-permutation/description/
Given a string S,
we can transform every letter individually to be lowercase or uppercase to
create another string. Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Output: ["3z4", "3Z4"]
Input: S = "12345"
Output: ["12345"]
"""
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
L = [[i.lower(), i.upper()] if i.isalpha() else i for i in S]
print(L)
# https://docs.python.org/2/library/itertools.html#itertools.product
# Roughly equivalent to nested for-loops in a generator expression.
# For example, product(A, B) returns the same as
# ((x,y) for x in A for y in B).
return [''.join(i) for i in itertools.product(*L)]
def build():
return "a1b2"
if __name__ == "__main__":
s = Solution()
result = s.letterCasePermutation(build())
print(result)
| true |
1928a539e6e5e406201bcf6009f3489c95ea31df | vsdrun/lc_public | /toposort/269_Alien_Dictionary.py | 2,243 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/alien-dictionary/description/
There is a new alien language which uses the latin alphabet.
However, the order among letters are unknown to you.
You receive a list of non-empty words from the dictionary,
where words are sorted lexicographically by the rules of this new language.
Derive the order of letters in this language.
Example 1:
Given the following words in dictionary,
zip(
[
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
[
"wrf",
"er",
"ett",
"rftt"
""
])
The correct order is: "wertf".
Example 2:
Given the following words in dictionary,
[
"z",
"x"
]
The correct order is: "zx".
Example 3:
Given the following words in dictionary,
[
"z",
"x",
"z"
]
The order is invalid, so return "".
You may assume all letters are in lowercase.
You may assume that if a is a prefix of b,
then a must appear before b in the given dictionary.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.
https://leetcode.com/problems/alien-dictionary/discuss/70137/1618-lines-Python-30-lines-C++
"""
class Solution(object):
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
less = []
# build graph!!
for pair in zip(words, words[1:]):
for a, b in zip(*pair):
if a != b: # 都相同我無法build graph direction dependency...
less += a + b,
break
chars = set(''.join(words))
order = []
print("less: {}".format(less))
print("chars: {}".format(chars))
while less:
print(zip(*less)[1])
head = chars - set(zip(*less)[1]) # 找 head
if not head:
return ''
order += head
less = filter(head.isdisjoint, less) # 找出不含 head的 pair
chars -= head
return ''.join(order + list(chars))
def build():
return [
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
if __name__ == "__main__":
s = Solution()
print(s.alienOrder(build()))
| true |
65f81a838881588ab34ff39a88e728d47e31bc37 | tudortrita/M3SC-Scientific-Computing | /python_algorithms/msort.py | 1,400 | 4.1875 | 4 | """ Module contains 2 functions:
merge: used by mergesort
mergesort: recursive implementation of merge sort algorithm
Running this module will run mergesort with a random sequence
of 8 integers
"""
def merge(L, R):
"""Merge 2 sorted lists provided as input
into a single sorted list
"""
M = [] # Merged list, initially empty
indL, indR = 0, 0 # start indices
nL, nR = len(L), len(R)
# Add one element to M per iteration until an entire sublist
# has been addedz
for i in range(nL + nR):
if L[indL] < R[indR]:
M.append(L[indL])
indL = indL + 1
if indL >= nL:
M.extend(R[indR:])
break
else:
M.append(R[indR])
indR = indR + 1
if indR >= nR:
M.extend(L[indL:])
break
return M
def mergesort(X):
"""Given a unsorted list, sort list using
merge sort algorithm and return sorted list
"""
n = len(X)
if n == 1:
return X
L = mergesort(X[:n // 2])
R = mergesort(X[n // 2:])
return merge(L, R)
if __name__ == '__main__':
"""
Executing "run msort" within a python terminal will run the example
code below
"""
import numpy as np
A = list(np.random.randint(0, 20, 8))
S = mergesort(A)
print("Initial list:", A)
print("Sorted list:", S)
| true |
0f638b08deabaa4ec07a6aa8825695ba896269d0 | nathanzhu144/coding | /coding_exercises/dp/sets_of_numbers_add_up.py | 1,898 | 4.125 | 4 | # Saturday October 6th, 2018
# Nathan Zhu
# Hatcher Library
#
# https://www.youtube.com/watch?v=nqlNzOcnCfs
#
# How many sets of number in a list add up to a certain number?
#
# Ex. [1, 2, 3] to make 4, is only one, (1, 3)
#
# Coin change:
# To use a number twice, as in a coin change problem where we can use a
# denomination twice, we only need a slight tweak
#
# Notes:
#
# Note that there cannot be repeats - as in
# Given a set [1, 2, 3], there are only two ways of making
# it, specifically
def dp(arr, total, i, memoization):
key = (total, i)
if key in memoization:
return memoization[key]
# There is 1 way to make 0
elif total is 0:
return 1
# 0 ways to make neg sum
elif total < 0:
return 0
# if we run out of objects to make sum with.
# Impossible to make 8 with a set of {2, 3} for example
elif i < 0:
return 0
#cannot include this object, arr[i] if subtracting leads to < 0
elif total - arr[i] < 0:
sum = dp(arr, total, i - 1, memoization)
else:
sum = dp(arr, total, i - 1, memoization) + dp(arr, total - arr[i], i - 1, memoization)
## Note: changing to this would be same problem as coin problem where you can use
## same denomination twice
#sum = dp(arr, total, i - 1, memoization) + dp(arr, total - arr[i], i, memoization)
memoization[key] = sum
return sum
def find_sets_of_num_add_up_to(arr, total):
memoization = {}
return dp(arr, total, len(arr) - 1, memoization)
if __name__ == "__main__":
arr = [2, 23, 2, 20, 1, 5, 9, 13, 4]
print find_sets_of_num_add_up_to(arr, 1)
print find_sets_of_num_add_up_to(arr, 3)
print find_sets_of_num_add_up_to(arr, 13)
coin_arr = [1, 2, 3]
print find_sets_of_num_add_up_to(coin_arr, 4)
n10_Arr = [2, 5, 3, 6]
print find_sets_of_num_add_up_to(n10_Arr, 10) | true |
a948b5ab692623aaaa171d854c48d03a5d1359ca | PerilousApricot/WMCore | /src/python/Utils/Utilities.py | 1,723 | 4.15625 | 4 | #! /usr/bin/env python
from __future__ import division, print_function
def makeList(stringList):
"""
_makeList_
Make a python list out of a comma separated list of strings,
throws a ValueError if the input is not well formed.
If the stringList is already of type list, then return it untouched.
"""
if isinstance(stringList, list):
return stringList
if isinstance(stringList, basestring):
toks = stringList.lstrip(' [').rstrip(' ]').split(',')
if toks == ['']:
return []
return [str(tok.strip(' \'"')) for tok in toks]
raise ValueError("Can't convert to list %s" % stringList)
def makeNonEmptyList(stringList):
"""
_makeNonEmptyList_
Given a string or a list of strings, return a non empty list of strings.
Throws an exception in case the final list is empty or input data is not
a string or a python list
"""
finalList = makeList(stringList)
if not finalList:
raise ValueError("Input data cannot be an empty list %s" % stringList)
return finalList
def strToBool(string):
"""
_strToBool_
Try to convert a string to boolean. i.e. "True" to python True
"""
if string in [False, True]:
return string
elif string in ["True", "true", "TRUE"]:
return True
elif string in ["False", "false", "FALSE"]:
return False
raise ValueError("Can't convert to bool: %s" % string)
def safeStr(string):
"""
_safeStr_
Cast simple data (int, float, basestring) to string.
"""
if not isinstance(string, (tuple, list, set, dict)):
return str(string)
raise ValueError("We're not supposed to convert %s to string." % string)
| true |
d3795b79f92353648ebacf0b9f10e8f4bac927b7 | spelee/python_edu | /tutorials/c26_oop/first_ex.py | 1,038 | 4.15625 | 4 |
class FirstClass:
def setdata(self, value):
self.data = value
def display(self):
print(self.data)
def display2(self):
print(self.otherdata)
class SecondClass(FirstClass):
def display(self):
print('Current value = "%s"' % self.data)
class ThirdClass(SecondClass):
def __init__(self, value):
self.data = value
def __add__(self, other):
return ThirdClass(self.data + other)
def __str__(self):
return '[ThirdClass: %s]' % self.data
def mul(self, other):
self.data *= other
if __name__ == '__main__':
x = FirstClass()
y = FirstClass()
x.setdata("King Arthur")
y.setdata(3.14159)
x.display()
y.display()
x.otherdata = 'new'
x.display2()
z = SecondClass()
z.setdata(42)
z.display()
x.data = "New value"
x.display()
print('-' * 80)
a = ThirdClass('abc')
a.display()
print(a)
b = a + 'ayz'
b.display()
print(b)
a.mul(3)
print(a)
print('end') | false |
7ec3ab057c6e3b82b18d758a3140ed77465f69f7 | Green95GT/Document-Reader | /median_word_length.py | 1,439 | 4.25 | 4 | import sys
def print_words(fopen):
f = open(fopen,'r')
letters = []
word = []
word_size = []
"""iterate over the lines in the file"""
for line in f:
if line != '\n':
"""iterate over each letter in line"""
for printable in line:
if not printable.isspace():
letters.append(printable)
else:
word_size.append(len(letters))
"""concatenate letters list into words"""
result = ''
for element in letters:
result += str(element)
word.append(result)
letters.clear()
elif line == '\n\n':
letters.append('\n\n\n')
elif line == '\n':
letters.append('\n\n')
"""Calculating the median size of word length"""
word_size.sort()
if len(word_size) % 2 == 0:
median = (word_size[int(len(word_size)/2 - 1)] + word_size[int(len(word_size)/2)]) / 2
else:
median = word_size[int((len(word_size)-1)/2)]
print ('The amount of words in this document is: ', len(word))
print ('The median length of word is: ', median)
decision = input('Would you like the program to read the document (y/n)? ')
if decision == 'y':
"""Concatenates word list into a scentence"""
result1 = ''
for elements in word:
result1 += str(elements)
result1 += ' '
print (result1)
else:
f.close()
def main():
if len(sys.argv) != 2:
print ('usage: ./median_word_length.py file')
sys.exit(1)
filename = sys.argv[1]
print_words(filename)
if __name__ == '__main__':
main()
| true |
50354714220b4446b49477af631d816cc27ed739 | nikkilkum26/Python_programs | /python/arithematic operations.py | 241 | 4.1875 | 4 | x = int(input("Enter number 1: "))
y = int(input("Enter number 2: "))
print('ADDITION :',x+y)
print('Subtraction :',x-y)
print('Multiplication :',x*y)
print('Division :',x/y)
print('Divide with integral result :',x//y)
print('power :',x**y) | false |
de7eb5b05a3971e16e305ff1922099d76d6d9f62 | GregoryWu/Fundamental-blocks | /Algorithms/fibonacci.py | 1,158 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 15:36:58 2019
@author: gregorywu
"""
# Recursive method
# T = O(2**n)
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return fibonacci(n-2) + fibonacci(n-1)
for n in range(1,50):
print(n,":", fibonacci(n))
# Dynamic approach
# [1] Memoization
# T = O(2N+1) = O(2N)
fibonacci_cache = {}
def fib_with_memo(n):
if n in fibonacci_cache:
return fibonacci_cache[n]
if n == 1 or n == 2:
value = 1
else:
value = fib_with_memo(n-2) + fib_with_memo(n-1)
fibonacci_cache[n] = value
return value
for n in range(1,500):
print(n,":", fib_with_memo(n))
# [2] bottom-up
# T = O(N)
def fib_bottom_up(n):
if n ==0:
return 0
if n == 1 or n == 2:
return 1
bottom_up = [None] * (n+1)
bottom_up[1] = 1
bottom_up[2] = 1
for i in range(3,n+1):
bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]
return bottom_up[n]
for n in range(1,500):
print(n,":", fib_bottom_up(n))
| false |
cf5a9b8dad5a02610fa5ce2a849b6f9fc50a0aa8 | Mithileshshirke/Python | /bankingsystem.py | 2,588 | 4.1875 | 4 | #2) write a program to make banking system develop business logic
#in one module and call functionality in another .py file
class Customer: #user defined class
def __init__(self,name,phoneno,address,pin,accno,balance) : #constructor with multiple arguments
self._name=name
self._pno=phoneno
self._add=address
self._pin=pin
self._acc=accno
self._bal=balance#protected variable
def add(self) : #user defined method
self._d={} #create empty dictionary
self._d['CustomerName']=self._name #add values to the dictionary using key names
self._d['CustomerPhonenumber']=self._pno
self._d['CustomerAddress']=self._add
self._d['CustomerPin']=self._pin
self._d['CustomerAccountNumber']=self._acc
self._d['CustomerBalance']=self._bal
print('Customer Details Add Successfully')
def deposit(self):
amt=int(input('Enter Deposit amount : '))
self._d['CustomerBalance']+=amt
print('Your a/c is credited for INR ',amt)
print('Account Balance is ',self._d['CustomerBalance'])
print()
def withdraw(self):
amt=int(input('Enter Withdraw amount : '))
if amt>self._d['CustomerBalance'] :
print('Insufficient Balance')
print('Account Balance is ',self._d['CustomerBalance'])
print()
else:
self._d['CustomerBalance']-=amt
print('Your a/c is debited for INR ',amt)
print('Account Balance is ',self._d['CustomerBalance'])
print()
def transfer(self):
name=input('Enter Recipient name : ')
acc=input('Enter account number : ')
if len(acc)==16:
amt=int(input('Enter amount to transfer : '))
if amt>self._d['CustomerBalance'] :
print('Insufficient Balance')
print('Account Balance is ',self._d['CustomerBalance'])
print()
else:
self._d['CustomerBalance']-=amt
print('Transfer amount successfully')
print('Your a/c is debited for INR ',amt)
print('Account Balance is ',self._d['CustomerBalance'])
print()
else:
print('Invalid Account Number\n')
def mini(self):
print('Name : ',self._d['CustomerName'])
print('Account Balance is ',self._d['CustomerBalance'])
print()
def __del__(self): #destructor
print('Thank You')
pass
| true |
bad8264fbfa46e0ad1213d78a406c945d9c64937 | Hudsonsue/GMIT-Programming-Scripting | /factorial.py | 1,037 | 4.40625 | 4 | # G00219132 Susan Hudson Programming & Scripting
# script defines a function to return factorial of entered integers.
# https://en.wikipedia.org/wiki/Factorial
# for positive integer n! is n multiplied by all positive integars less than it
# example 4! = 4*3*2*1 = 24
# 0! = 1
def factorial(n):
"""This function returns factorial of positive integar n."""
"""where n = 0 will return 1 as 0! = 1. Where n < 0 returns Invalid argument warning"""
if n == 0:
return 1
elif n < 0:
return print('INVALID ARGUMENT, Positive integars only please!!')
else:
return n * factorial (n-1)
n = int(input("Enter a positive integar: "))
print ("the factorial of your integar" ,n, "is", factorial(n))
# Test the function with the following values, 5, 7, 10
# as well as returning the factorial of the entered integar it will return the factorials of 5,7 and 10
print ("the factorial of 5 is:", factorial (5))
print ("the factorial of 7 is:", factorial (7))
print ("the factorial of 10 is:", factorial (10)) | true |
6ff07bd7430df78f1c5d9e9a089b5fda7053b9d5 | shekhar-joshi/Assignments | /Creating pattern using nested loop.py | 531 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 01:54:57 2018
@author: shekhar
"""
"""Create the below pattern using nested for loop in Python.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
for i in range(0,5): #we actually do not need the nested loop to draw this pattern
for j in range(0,1): #its used to enter the nested loop and the initialize it to value 1 again
print("* "*i)
for i in range(5,0,-1):
for j in range(0,1):
print("* "*i)
| true |
be0bf957aa6b2ae05ec1d60edbcd6b2f19a0780c | OhsterTohster/Project-Euler | /Python/q1.py | 306 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
sumOfNumbers = 0
for i in range(1,1000):
if (i%3 ==0) or (i%5==0):
sumOfNumbers+=i
print(sumOfNumbers) | true |
4b3e19aeddec5657a7187b21b959f67a5784dc51 | akumarkk/Algorithms | /twenty_eight/17_search_unknown_lenarray/binary_search.py | 1,452 | 4.15625 | 4 | # Given a sorted array of unknown length and a number to search for, return the index of the number in the array.
# Accessing an element out of bounds throws exception.
# If the number occurs multiple times, return the index of any occurrence.
# If it isnt present, return -1.
def binary_search(array, key):
# To check for first element
index = -1
while key >= array[int(2**index)]:
try:
if key == array[int(2**index)]:
return int(2**index)
else:
index = index + 1
# This is just to check for exception
if array[2**index]:
pass
except IndexError:
print("Exception for index = ", 2**index)
break
# It is either exception or key < array[2**index]
# high will remain same
high = (2**index) - 1
low = (2**(index-1)) + 1
print("index = ", index, "low = ", low, " high = ", high)
while low <= high:
try:
mid = (low + high) / 2
print("mid = ", mid, "low = ", low, " high = ", high)
if(array[mid] == key):
return mid
elif array[mid] > key:
high = mid - 1
print("now high = ", high)
else:
low = mid + 1
print("now low = ", low)
except IndexError:
print("Mid index Error ", mid)
mid = mid - 1
return -1
array = [1, 3, 45, 67, 78, 89, 90, 100]
print("***key = 10 ret = ", binary_search(array, 10));
print("***key = 89 ret = ", binary_search(array, 89));
print("***key = 1 ret = ", binary_search(array, 1));
| true |
088ff6af263149e5596156b7e69cba37edce4519 | adriculous/pythonbible | /scope.py | 800 | 4.15625 | 4 | # variable scopes (global (scope outside functions) and local (scope inside functions))
a = 250 # this is a global variable scope
def f1(): # adding parameters inside the parentheses are optional
global a # global keyword, redefines default global scope
a = 100
print(a)
def f2():
a = 50 # this is a local variable scope, will be different from global variable
print(a)
f1()
f2()
print(a)
# What I learned about variable scopes
# 1) Two types of scopes - global & local
# 2) Python functions create local scopes
# 3) You can't override a global scope from a local scope (inside a function) unless if you use the "global" keyword
# 4) Lists and dictionaries will also not override a global scope, but you can change a value within a list or dictionary from within a function.
| true |
a1e73023bba4a1726ea8a2de9ba87f2e00f6c3a8 | renkeji/leetcode | /python/src/main/python/Q114.py | 1,138 | 4.21875 | 4 | from src.main.python.Solution import Solution
from src.main.python.datastructures.TreeNode import TreeNode
# Given a binary tree, flatten it to a linked list in-place.
#
# For example,
# Given
#
# 1
# / \
# 2 5
# / \ \
# 3 4 6
#
# The flattened tree should look like:
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
class Q114(Solution):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
def find_node(node):
if not node.left and not node.right:
return node
if node.right:
return find_node(node.right)
else:
return find_node(node.left)
if root:
while root.left or root.right:
if root.left:
node = find_node(root.left)
node.right = root.right
root.right = root.left
root.left = None
root = root.right
| true |
f235fb3f22fc62c1e3bf16b5a7b7be67480b1224 | renkeji/leetcode | /python/src/main/python/Q054.py | 1,454 | 4.25 | 4 | from src.main.python.Solution import Solution
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# For example,
# Given the following matrix:
#
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# You should return [1,2,3,6,9,8,7,4,5].
class Q054(Solution):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
def spiral_order(matrix, row, col, offset, ans):
if row <= 0 or col <= 0:
return
elif row == 1:
for j in range(col):
ans.append(matrix[offset][offset+j])
elif col == 1:
for i in range(row):
ans.append(matrix[offset+i][offset])
else:
for j in range(col-1):
ans.append(matrix[offset][offset+j])
for i in range(row-1):
ans.append(matrix[offset+i][offset+col-1])
for j in range(col-1):
ans.append(matrix[offset+row-1][offset+col-1-j])
for i in range(row-1):
ans.append(matrix[offset+row-1-i][offset])
spiral_order(matrix, row-2, col-2, offset+1, ans)
ans = []
if matrix and matrix[0]:
spiral_order(matrix, len(matrix), len(matrix[0]), 0, ans)
return ans
| true |
38af562d1e6397f44f9e3d2a6fd5d791d9261c04 | qrnik/Kodilla | /4.2 zad. 1.py | 542 | 4.4375 | 4 | def is_palindrome(word):
"""
Prints whether a word or sentence is a palindrome, based on argument passed
Argument:
word
"""
lower_word = word.lower()
replaced_word = lower_word.replace(" ", "")
if replaced_word != replaced_word[::-1]:
return f"{word.capitalize()} is not a palindrome."
else:
return f"{word.capitalize()} is a palindrome."
print(is_palindrome("Anna"))
print(is_palindrome("potop"))
print(is_palindrome("bootcamp"))
print(is_palindrome("A to kiwi zdziwi kota")) | true |
aba431ed5c69a55ff4a8fb4d6e4b62cb46aa83e1 | VitaliiHudukhin/ithub | /lesson2_tasks/task2_08.py | 591 | 4.21875 | 4 |
import math
print('Please, enter whole positive number, more than 1:')
def is_prime(n):
or_prime = 'Prime'
if n < 2:
print("A number must be 2 and more")
or_prime = 'Composite'
elif n == 2:
pass
i = 2
limit = n//2 #int(math.sqrt(n))
while i <= limit:
if n % i == 0:
or_prime = 'Composite'
i += 1
return or_prime, n
n = is_prime(int(input()))
if n[0] == 'Composite':
print('You entered composite number')
else:
for i in range (n[1],1, -1):
if is_prime(i) == ('Prime',i):
print(i) | false |
ff3b3a0bce0dbc73eb296241a53eb9c9053b0504 | VitaliiHudukhin/ithub | /lesson1_tasks/task2.py | 1,053 | 4.15625 | 4 | from math import sqrt
def is_number(strg):
try:
float(strg)
if float(strg) > 0:
return float(strg)
else:
print("The number is < or == 0, try again")
return False
except ValueError:
print("Entered data isn't the number, try again")
return False
print("Please, enter a radius for first planet: ")
radius1 = is_number(input())
print("Please, enter a rotation period for first planet: ")
period1 = is_number(input())
print("Please, enter a radius for second planet: ")
radius2 = is_number(input())
while radius1 == False or period1 == False or radius2 == False:
print("Please, enter a correct radius for first planet: ")
radius1 = is_number(input())
print("Please, enter a correct rotation period for first planet: ")
period1 = is_number(input())
print("Please, enter a correct radius for second planet: ")
radius2 = is_number(input())
period2 = sqrt(period1**2 * radius2**3 / radius1**3)
print('Rotation period for second planet = '+str(period2)) | true |
8b7672dbd47f7d480f5543937d8e8309ac74cf3d | isora9958/C | /20181016 | 1,339 | 4.25 | 4 | #!/usr/bin/env python
#coding=utf-8
# radius = 25
# Input(輸入):Prompt the user to enter a radius
radius = eval(input("Enter a number for radius: "))
# Processing(處理):Compute area
area = radius * radius * 3.1415962
# Output(輸出):Display results
print("The area for the circle of radius", radius, "is", area)
#!/usr/bin/env python
#coding=utf-8
# Prompt the user to enter three numbers
number1, number2, number3 = eval(input("Enter three numbers separated by commas: "))
# Compute average
average = (number1 + number2 + number3) / 3
# Display result
print("The average of", number1, number2, number3, "is", average)
>>> q = 259
>>> p = 0.038
>>> print(q, p, p * q)
>>> print(q, p, p * q, sep=",")
>>> print(q, p, p * q, sep=" :-) ")
>>> print(str(q) + " " + str(p) + " " + str(p * q))
>>> x = input("Enter a character: ")
Enter a character: A
>>> y = input("Enter a character: ")
Enter a character: Z
>>> print(ord(y) - ord(x))
25
>>> x = input("Enter a character: ")
Enter a character: A
>>> ch = chr(ord(x) + 3)
>>> print(ch)
D
>>> sum = 2 + 3
>>> print(sum)
5
>>> s ='2' + '3'
>>> print(s)
23
>>> title = "Chapter " + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> ChapterNO = 1
>>> title = "Chapter"+str(ChapterNO)
>>> title
'Chapter1'
| true |
5fab1ea2f9528119646194b0064199cc2c02db97 | HannahKnights/the-snake-and-the-mouse | /introductions/4-types-and-attributes-examples.py | 1,140 | 4.28125 | 4 | """
Here are some examples of using
to go with python introductions/4-types-and-attributes.py
To run this:
python introductions/4-types-and-attributes-examples.py
"""
# example 1...
this_is_a_list = [
'this',
'that',
'other'
]
this_is_a_list.append('more things')
this_is_a_list.append('what a long list!')
print('Here is a long list of things:')
for thing_in_the_list in this_is_a_list:
print(thing_in_the_list)
# example 2
# when you print the item in the list you could add a bullet-point
print('\n')
print('Here is a long list of things:')
for thing_in_the_list in this_is_a_list:
print(' * ' + thing_in_the_list)
# example 3...
print('\n')
lucky_number = 7
number_of_seconds_a_fish_can_remember = '3' # apparently?
print('A fish has a ' + number_of_seconds_a_fish_can_remember + ' second memory')
# example 4...
('\n')
print('If...')
print(lucky_number)
print('is lucky, does that make...')
print(lucky_number + lucky_number)
print('extra lucky?')
# example 5...
('\n')
print('If you wrap me, caringly, in a `str()`, I become a ' + str(lucky_number) + 'ssssstring')
print('.. now that is lucky')
| false |
a310b4c784eeba0d52e210b2195777bc3c0f1ec5 | HannahKnights/the-snake-and-the-mouse | /introductions/4-types-and-attributes.py | 1,296 | 4.46875 | 4 | """
python (the snake):
- has expectations about what is possible for cerain "types" (the definition of type-cast!)
- some things have specific actions associated with them...
- some things cannot be combined together...
Tips:
this_is_a_list = [
'this',
'that',
'other'
]
- you can add new things to the list using 'append'
but, you cannot add new things to a string using 'append'
this_is_a_number = 1
this_is_a_string = '100' # i know it looks like a number ! but there are quotes around it
- you can add a string to a string
new_thing = this_is_a_string + this_is_a_string
- you can add a number to a number
new_number = this_is_a_number + this_is_a_number
- but, you can't add a string to a number... !
- you can turn a number into a string !
see these example by looking at the code and/ or running:
python introductions/4-types-and-attributes-examples.py
python introductions/4-types-and-attributes.py
"""
things_in_the_sky = [
'sun',
'moon',
'stars',
'planets',
'satellite',
'clouds',
'rain',
'wind'
]
'sky'.append('birds')
for thing_number, a_thing_in_the_sky in enumerate(things_in_the_sky):
print(thing_number + '. ' + a_thing_in_the_sky)
| true |
144696358af72f491206bd1b0fe79b208b5a4c96 | tabris1103/inf1340_2014_asst1 | /exercise2.py | 2,410 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Verifies that the digits of a UPC code are correct by performing a checksum
Assignment 1, Exercise 2, INF1340 Fall 2014
"""
__author__ = 'Kyungho Jung & Christine Oh'
__status__ = "Completed"
# imports one per line
def checksum(upc):
"""
Verifies that the digits of a UPC are correct by performing checksum
:param upc: a 12-digit Universal Product Code
:return:
Boolean: True, checksum is correct
False, otherwise
:raises:
TypeError if input is not a string
ValueError if string is the wrong length (with error string stating how many digits are over or under
"""
is_correct_upc_code = False
# Verify that the type of input is valid
if type(upc) is str:
# Verify that the length of string is valid
if len(upc) != 12:
raise ValueError("Length of the UPC input is not equal to 12")
# Verify that the UPC input does not contain any non-numerical characters or strings
elif str(upc).isnumeric() is False:
raise ValueError("UPC code must not contain any non-numerical characters or string values")
else:
# Convert string to list
upc_array = list(upc)
check_sum = 0
# Generate checksum using the first 11 digits of the UPC input
for string_index in range(0, 11):
if string_index % 2 == 0:
check_sum += int(upc_array[string_index]) * 3
print("Check Sum at " + str(string_index) + " = " + str(check_sum))
else:
check_sum += int(upc_array[string_index])
print("Check Sum at " + str(string_index) + " = " + str(check_sum))
# Calculate modulo 10 of check_sum
mod_10_of_check_sum = check_sum % 10
# Subtract mod_10_of_check_sum from 10 to get the supposed last digit
subtracting_from_10 = 10 - mod_10_of_check_sum
# Compare the supposed last digit with the the actual twelfth digit
# Return True if they are equal, False otherwise
last_digit = int(upc_array[11])
if subtracting_from_10 == last_digit:
is_correct_upc_code = True
else:
# raise TypeError if not string
raise TypeError("The UPC input is not string type")
return is_correct_upc_code
| true |
d613bf20b77a095d255d4524b3d63e5b65bf71ff | GauthamAjayKannan/coding | /lowestCommonAncestor.py | 1,804 | 4.15625 | 4 | class Node:
def __init__(self,value):
self.data=value
self.left=None
self.right=None
class BST:
def __init__(self):
self.root=None
def insert(self,data):
if self.root==None:
print("inserted")
self.root=Node(data)
else:
self.insertnode(self.root,data)
def insertnode(self,node,data):
if data<node.data:
if node.left==None:
node.left=Node(data)
else:
self.insertnode(node.left,data)
elif data>node.data:
if node.right==None:
node.right=Node(data)
else:
self.insertnode(node.right,data)
def traversein(self):
if self.root==None:
print("no nodes in binary search tree to be traversed")
else:
self.traverse_in_order(self.root)
def traverse_in_order(self,node):
if node.left!=None:
self.traverse_in_order(node.left)
print(node.data)
if node.right!=None:
self.traverse_in_order(node.right)
def lca(self,x,y):
if self.root==None:
print("no tree is present")
else:
return self.lowest(self.root,x,y)
def lowest(self,node,x,y):
if node==None:
return None
if node.data==x or node.data==y:
return node.data
l=self.lowest(node.left,x,y)
r=self.lowest(node.right,x,y)
if l==None:
return r
if r==None:
return l
print(l,r)
return node.data
a=BST()
a.insert(5)
a.insert(2)
a.insert(9)
a.insert(3)
a.insert(6)
a.insert(10)
a.insert(7)
a.insert(20)
a.traversein()
print("LCA",a.lca(10,20))
| false |
cb48bc4eb2d258e7e856db4da312f1cf7c3122ca | heatherstafford/unit5 | /longestWord.py | 236 | 4.28125 | 4 | #Heather Stafford
#4/23/18
#longestWord.py
words = input('Enter some words: ').split(' ')
longest = 0
word = ' '
for item in words:
if len(item) > longest:
longest = len(item)
word = item
print('The longest word is', word)
| true |
1a3a79a67093b63478b48ba907f0c6bb64377a65 | annadorzhieva/lesson_3 | /HW_3_lesson_3.py | 458 | 4.34375 | 4 | ''' Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших
двух аргументов'''
def my_func(num_1, num_2, num_3):
# max(arg_1, arg_2, arg_3)
a = num_1+num_2
b = num_1+num_3
c = num_2+num_3
# max_number = max(int(a, b, c))
# return max_number
print(max(a, b, c))
my_func(2, 12, 19)
| false |
fb7f11996b1c7be5bd487fb238f3a7dfa99f2cca | athulanish/Python_Practise | /ternary_operator.py | 622 | 4.34375 | 4 | ## A ternary operator is a simpler version of an if-else statement
a = 24
b = 35
#get an minimum output for a if its smaller than b
print("a is minimum" if a<b else "a is maximum")
good_movie = True
print("Movie is a blockbuster" if good_movie else "Movie is a one time watch")
##lets try the above exercise using tuple method
print(("Movie is a one time watch","Movie is a blockbuster")[good_movie])
num = 13
print("Even" if num%2 == 0 else "Odd")
##using tuple method
print(("Odd", "Even")[num%2 == 0])
##Define a function for range
def ran(n):
if n > 0:
ran(n-1)
print (n)
print(ran(100))
| true |
1013f87e691313005146466a12d8d23ea25eede7 | tbatsenko/UCU-blockchain-lesson1 | /curve.py | 1,181 | 4.125 | 4 | class EllipticCurve(object):
"""
This class represents Elliptic Curve of the form:
y^2 = x^3 + ax + b
>>> print(EllipticCurve(a=17, b=1))
y^2 = x^3 + 17x + 1
>>> EllipticCurve(a=0, b=0)
Traceback (most recent call last):
...
Exception: The curve y^2 = x^3 + 0x + 0 is not smooth!
"""
def __init__(self, a, b):
self.a = a
self.b = b
self.discriminant = -16 * (4 * a*a*a + 27 * b * b)
if not self.isSmooth():
raise Exception("The curve %s is not smooth!" % self)
def isSmooth(self):
return self.discriminant != 0
def testPoint(self, x, y):
"""
This function checks if a Point belongs to the given Elliptic Curve.
>>> EllipticCurve(a=0, b=3).testPoint(1, 2)
True
>>> EllipticCurve(a=3, b=2).testPoint(1, 1)
False
"""
return y**2 == x**3 + self.a * x + self.b
def __str__(self):
return "y^2 = x^3 + {0}x + {1}".format(self.a, self.b)
def __eq__(self, other):
return (self.a, self.b) == (other.a, other.b)
if __name__ == "__main__":
import doctest
doctest.testmod() | true |
c053c5291ea1cbb0dac1e6d51ed2f0fce534f3f5 | cutewindy/CodingInterview | /LintCode_Python/reverseLinkedListII.py | 1,030 | 4.15625 | 4 | # Reverse a linked list from position m to n.
# Have you met this question in a real interview? Yes
# Example
# Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL.
# Note
# Given m, n satisfy the following condition: 1 <= m <= n <= length of list.
# Challenge
# Reverse it in-place and in one-pass
from ListNode import ListNode
def reverseLinkedListII(head, m, n):
if head == None:
return None
dummy = ListNode(0)
dummy.next = head
head = dummy
# find premmNode and mNode
for i in range(1, m):
head = head.next
prevmNode = head
mNode = head.next
# reverse link from m to n
nNode = mNode
nextnNode = nNode.next
for i in range(m, n):
temp = nextnNode.next
nextnNode.next = nNode
nNode = nextnNode
nextnNode = temp
# combine
prevmNode.next = nNode
mNode.next = nextnNode
return dummy.next
head = ListNode.arrayToList([1, 2, 3, 4, 5])
ListNode.printList(reverseLinkedListII(head, 2, 4))
| true |
a6a95821e7c120d4cf65fc62b7e0c5e504a7e7d0 | cutewindy/CodingInterview | /LintCode_Python/wordLadder.py | 759 | 4.15625 | 4 | # Given two words (start and end), and a dictionary, find the length of shortest
# transformation sequence from start to end, such that:
# Only one letter can be changed at a time
# Each intermediate word must exist in the dictionary
# Have you met this question in a real interview? Yes
# Notice
# Return 0 if there is no such transformation sequence.
# All words have the same length.
# All words contain only lowercase alphabetic characters.
# Example
# Given:
# start = "hit"
# end = "cog"
# dict = ["hot","dot","dog","lot","log"]
# As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
# return its length 5.
def wordLadder(start, end, dict):
return 0
print wordLadder("hit", "cog", ["hot","dot","dog","lot","log"])
| true |
bc8703060eb491a6f5770edfdb74a4d4409fda08 | cutewindy/CodingInterview | /LintCode_Python/deleteNodeintheMiddleofSinglyLinkedList.py | 668 | 4.125 | 4 | # Implement an algorithm to delete a node in the middle of a singly linked list,
# given only access to that node.
# Have you met this question in a real interview? Yes
# Example
# Given 1->2->3->4, and node 3. return 1->2->4
from ListNode import ListNode
def deleteNodeintheMiddleofSinglyLinkedList(node):
if node is None:
return
# node is not last node
if node.next is not None:
node.val = node.next.val
node.next = node.next.next
# node is the last node
else:
node = None
head = ListNode.arrayToList([1, 2, 3, 4])
node = head.next.next
deleteNodeintheMiddleofSinglyLinkedList(node)
ListNode.printList(head)
| true |
9c1e6d82837f91184c652a245c9b54afc2d39e47 | cutewindy/CodingInterview | /LintCode_Python/sortColorsII.py | 1,482 | 4.125 | 4 | # Given an array of n objects with k different colors (numbered from 1 to k),
# sort them so that objects of the same color are adjacent, with the colors in
# the order 1, 2, ... k.
# Have you met this question in a real interview? Yes
# Example
# Given colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to
# [1, 2, 2, 3, 4].
# Note
# You are not suppose to use the library's sort function for this problem.
# Challenge
# A rather straight forward solution is a two-pass algorithm using counting sort.
# That will cost O(k) extra memory. Can you do it without using extra memory?
import sys
def sortColorsII(colors, k):
if not colors or not k:
return None
left = 0
right = len(colors) - 1
count = 0
while count < k:
maxColor = -sys.maxint
minColor = sys.maxint
for i in range(left, right + 1):
maxColor = max(colors[i], maxColor)
minColor = min(colors[i], minColor)
curr = left
while curr <= right:
if colors[curr] == minColor:
colors[left], colors[curr] = colors[curr], colors[left]
curr += 1
left += 1
elif minColor < colors[curr] and colors[curr] < maxColor:
curr += 1
else:
colors[right], colors[curr] = colors[curr], colors[right]
right -= 1
count += 2
return colors
print sortColorsII([3, 2, 2, 1, 4], 4)
| true |
81ed12d426c23043b62e2b5caef5e4401f46e8e3 | nthatf01/Treehouse-Python | /looping.py | 943 | 4.46875 | 4 | name = input("What's your name? ")
def prompt_for_yes_or_no():
return input("(Enter yes/no) ").lower()
# Ask the user by name if they understand Python while loops
print("{}, do you understand Python while loops? ".format(name))
user_answer = prompt_for_yes_or_no()
# Write a while statement that checks if the user doesn't understand while loops
while user_answer != "yes":
# Since the user doesn't understand while loops, let's explain them.
print("Ok, {}, while loops in Python repeat as long as a certain Boolean condition is met.".format(name))
# Ask the user again, by name, if they understand while loops.
print("{}, now do you understand Python while loops?".format(name))
user_answer = prompt_for_yes_or_no()
# Outside the while loop, congratulate the user for understanding while loops
print("That's great, {}. I'm pleased that you understand while loops now. That was getting repetitive".format(name))
| true |
3b49f3cc7190b9eb1b9b3b397478bd6b8844d66b | umair-s5/Python-Projects | /part_A.py | 391 | 4.3125 | 4 | # Umair Sayeed
# tempConversion, 25 October 2017, Chapter 1 Lab
# Gets temperature in Fahrenheit from the user and prints it in Celsius.
# Inputs: Number from user
# Outputs: Conversion of user's input to Celsius.
tempFahrenheit = eval(input("Enter temperature in Fahrenheit: "))
conversionToCelsius = (tempFahrenheit - 32)*(5/9)
print("The temperature in Celsius: ", conversionToCelsius) | true |
6db9049be0ba3ea96374aec99f59cae0bcbda436 | snebotcifpfbmoll/DAMProgramacion | /A01/P06/P06E01.py | 371 | 4.25 | 4 | # P06E01:
# Escribe un programa que te pida palabras y las guarde en una lista. Para terminar de introducir palabras, simplemente pulsa Enter. El programa termina escribiendo la lista de palabras.
palabra = input("Escribe una palabra: ")
lista = []
while palabra != "":
lista += [palabra]
palabra = input("Escribe otra palabra: ")
print("Has escrito: ", lista)
| false |
29d78a6fab15829e894287ce9f0d7aa5cb61dfe8 | snebotcifpfbmoll/DAMProgramacion | /A01/P07/P07E04.py | 570 | 4.34375 | 4 | # P07E04:
# Escribe un programa que pida una frase, y le pase como parámetro a una función dicha frase. La función debe sustituir todos los espacios en blanco de una frase por un asterisco, y devolver el resultado para que el programa principal la imprima por pantalla.
def cambiarEspacios(frase):
ret = ""
for i in frase:
char = ''
if i == " ":
char = '*'
else:
char = i
ret += char
return ret
frase = input("Escribe una frase: ")
final = cambiarEspacios(frase)
print("Frase final: %s" % (final))
| false |
fbd04c76d00a2e5f9b041ff13601964486449bde | snebotcifpfbmoll/DAMProgramacion | /A01/P03/P03E07.py | 1,843 | 4.15625 | 4 | # P03E07: Serafi Nebot Ginard
# Pida al usuario tres número que serán el día, mes y año. Comprueba que la fecha introducida es válida.
print("Introduce una fecha.")
dia = int(input("Dia: "))
mes = int(input("Mes: "))
ano = int(input("Ano: "))
# Cada mes tine 30 o 31 dias (excepto febrero)
# Se empieza el año con un mes de 31 dias y se va alternando entre 31 y 30 dias cada mes
# (Si el mes es un numero par va a tener 30 dias y si no es par va a tener 31)
# A partir de Agosto es al reves (meses pares 31 dias i meses no pares 30)
if mes >= 1 and mes <= 12:
if mes == 2:
# El mes es febrero por lo tanto solo va a tener 28 dias
if dia <= 28:
print("%02d/%02d/%04d - La fecha es correcta." %(dia, mes, ano))
else:
print("%02d/%02d/%04d - La fecha es incorrecta." %(dia, mes, ano))
elif (mes < 8 and mes % 2 == 0) or (mes >= 8 and mes % 2 != 0):
# El mes es par (y esta al principio del año) por lo tanto va a tener 30 dias como maximo
# O
# El mes no es par (y esta al final del año) por lo tanto va a tener 30 dias como maximo
if dia <= 30:
print("%02d/%02d/%04d - La fecha es correcta." %(dia, mes, ano))
else:
print("%02d/%02d/%04d - La fecha es incorrecta." %(dia, mes, ano))
elif (mes < 8 and mes % 2 != 0) or (mes >= 8 and mes % 2 == 0):
# El mes no es par (y esta al principio del año) por lo tanto va a tener 31 dias como maximo
# O
# El mes es par (y esta al final del año) por lo tanto va a tener 31 dias como maximo
if dia <= 31:
print("%02d/%02d/%04d - La fecha es correcta." %(dia, mes, ano))
else:
print("%02d/%02d/%04d - La fecha es incorrecta." %(dia, mes, ano))
else:
print("%02d/%02d/%04d - La fecha es incorrecta." %(dia, mes, ano))
| false |
226fd7819b9fcc33fb993d9bbb9ffb8ac97c7565 | snebotcifpfbmoll/DAMProgramacion | /A01/P07/P07E13.py | 1,402 | 4.125 | 4 | # P07E13:
# Escribe un programa que le pida al usuario si quiere calcular si un número es primo con for o con while, por tanto, habrán dos funciones que se caracterizan por hacer ese mismo cálculo de una manera (con for y sin breaks), o de otra (con while). Ambas funciones devolverá true (si es es primo) o false (si no es primo). El programa principal informará del resultado. Además, como mejora puedes calcular el tiempo que tarda en encontrar la solución de una manera u otra. Comentario: aprovecha el código que tienes ya creado
def comprobarNumero(num, usarWhile=True):
numero_primo = True
if usarWhile:
indice = num - 1
while indice > 1:
if num % indice == 0:
numero_primo = False
indice -= 1
else:
for i in range(num, 1, -1):
if num % i == 0:
numero_primo = False
return numero_primo
num = int(input("Escribe un numero: "))
decision = None
while decision == None:
while_for = input("Quieres hacerlo con while o con for? ").lower()
if while_for == "while":
decision = True
elif while_for == "for":
decision = False
else:
print("[Error] %s: No se reconoce." % (while_for))
numero_primo = comprobarNumero(num, decision)
if numero_primo:
print("El numero", num, "es primo.")
else:
print("El numero", num, "no es primo.")
| false |
ca2392eb4ca25c86fa95601eea710aaf48de742f | himalayaashish/ML | /Python General/reverse_number.py | 310 | 4.1875 | 4 | def reverse_number(x):
result, x_remainder = 0, abs(x)
while x_remainder:
result = result * 10 + x_remainder % 10
x_remainder //=10
return -result if x<0 else result
x = int(input("Enter the Number"))
answer = reverse_number(x)
print("The reverse of {} ==> {}".format(x,answer))
| true |
e9650a8d930909e9bfe0a3d5bd80b6c861665359 | INF1007-2021A/2021a-c01-ch4-exercices-AnthonyLor | /exercice.py | 1,777 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def is_even_len(chaine) -> bool:
liste = []
for i in chaine:
liste.append(i)
if len(liste)%2 == 0:
return True
pass
def remove_third_char(chaine) -> str:
liste = list(chaine)
del(liste[2])
string = "".join(liste)
return string
pass
def replace_char(string: str, old_char: str, new_char: str) -> str:
liste = list(string)
for i in range(len(liste)):
if liste[i] == "w":
liste[i] = "z"
allo = "".join(liste)
return allo
def get_number_of_char(string: str, char: str) -> int:
liste = list(string)
c = 0
for i in range(len(liste)):
if liste[i] == "l":
c +=1
return c
pass
def get_number_of_words(sentence: str, word: str) -> int:
a = sentence.split()
c = 0
for i in range(len(a)):
if a[i] == "doo":
c += 1
return c
pass
def main() -> None:
chaine = "Bonjour!"
if is_even_len(chaine):
print(f"Le nombre de caractère dans la chaine {chaine} est pair")
else:
print(f"Le nombre de caractère dans la chaine {chaine} est impair")
chaine = "salut monde!"
print(f"On supprime le 3e caratère dans la chaine: {chaine}. Résultat : {remove_third_char(chaine)}")
chaine = "hello world!"
print(f"On remplace le caratère w par le caractère z dans la chaine: {chaine}. Résultat : {replace_char(chaine, 'w', 'z')}")
print(f"Le nombre d'occurrence de l dans hello world est : {get_number_of_char(chaine, 'l')}")
chaine = "Baby shark doo doo doo doo doo doo"
print(f"L'occurence du mot doo dans la chaine {chaine} est: {get_number_of_words(chaine, 'doo')}")
if __name__ == '__main__':
main()
| false |
d0593ca9f4e10d10357580f8fba21a62f4eb53fa | davidfabian/46excercises | /excercises/task_34.py | 1,045 | 4.125 | 4 | __author__ = 'd'
'''
A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a
language, the works of an author, or in a single text. Define a function that given the file name of a text will
return all its hapaxes. Make sure your program ignores capitalization.
'''
'''
test file location:
D:\python\46excercises\data\wordcount.txt
'''
import re
def hapax(location):
f = open(location, 'r')
h_count = 0
freq = {}
for line in f:
word = re.split('\W+', line)
for each in word:
if re.match('\w+', each):
if each.lower() in freq:
freq[each.lower()] += 1
else:
freq[each.lower()] = 1
for i in freq:
if freq[i] == 1:
h_count += 1
print(i)
print(len(freq), 'words found.', h_count, 'hapaxes')
print(freq)
f.close()
filename = input('path and filename: ')
hapax(filename)
# hapax('D:/python/46excercises/data/wordcount.txt') | true |
a6d3f09972f3062805605afe64ffaedb7c59b29e | davidfabian/46excercises | /excercises/task_30.py | 723 | 4.21875 | 4 | __author__ = 'd'
'''
Represent a small bilingual lexicon as a Python dictionary in the following fashion
{"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it to translate
your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate()
that takes a list of English words and returns a list of Swedish words.
'''
# this does not work if there ara any words that are not in the dictionary
sweng = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new": "nytt", "year": "år"}
def translate(a):
result = map(lambda item: sweng[item], a)
print(list(result))
translate(['merry', 'merry', 'new']) | true |
e133d6fe07c51feacb482d669aca23d31b7f7075 | aroseca15/Python_MarketApp | /Tutorial_Notes/comparisionOperators.py | 820 | 4.3125 | 4 | # COMPARISION OPERATIONS:
# temperature = 3
# if temperature >= 30:
# print("Man, it's too hot today!")
# elif temperature < 4:
# print("Woooo! It's cold!! Too Cold! I need Jimmy to cuddle with me!")
# else:
# print("It's not too bad today. Actually nice!")
# EXERCISE:
# Enforcing a Character Limit:
#
# MY SOLUTION:
# name_characters = 30
# if name_characters < 3:
# print("Your name is too short.")
# elif name_characters > 50:
# print("Your name exceeds the character limit.")
# else:
# print("Looks good! Thank you.")
# Enforcing a Character Limit: MOSH'S SOLUTION:
# name = "Jimmy"
# print(len(name))
# if len(name) < 3:
# print("Your name is too short.")
# elif len(name) > 50:
# print("Your name exceeds the character limit.")
# else:
# print("Looks good! Thank you.") | true |
fa48865cdd805279431f1134baee941283cf2575 | lancerdancer/leetcode_practice | /code/binary_tree_and_tree-based_dfs/114_flatten_binary_tree_to_linked_list.py | 1,526 | 4.21875 | 4 | """
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
last_node = None
def flatten(self, root):
self.helper(root)
# restructure and return last node in preorder
def helper(self, root):
if root is None:
return None
left_last = self.helper(root.left)
right_last = self.helper(root.right)
# connect
if left_last is not None:
left_last.right = root.right
root.right = root.left
root.left = None
if right_last is not None:
return right_last
if left_last is not None:
return left_last
return root
def flatten1(self, root):
"""
another version
"""
while root:
if root.left:
self.flatten(root.left)
tail = root.left
while tail.right:
tail = tail.right
tail.right = root.right
root.right = root.left
root.left = None
root = root.right
| true |
7433a50861985decfef7bd51f6185420b6d6088b | lancerdancer/leetcode_practice | /code/permutation_based_and_graph-based_dfs/17_letter_combinations_of_a_phone_number.py | 982 | 4.1875 | 4 | """
https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
KEYBOARD = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
}
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
result = []
self.dfs(digits, 0, '', result)
def dfs(self, digits, start, path, result):
if start == len(digits):
result.append(str(path))
return
for c in KEYBOARD[digits[start]]:
self.dfs(digits, start+1, path+c, result)
| true |
76ad6285d6596aaab844eff1b0bab4be2f7100c4 | noel-maldonado/Data-Programming | /HW Assignments/Chapter_8/Exercise_9.py | 1,004 | 4.5 | 4 | # (Binary to hex) Write a function that parses a binary number into a hex number.
# The function header is:
# def binaryToHex(binaryValue):
# Write a test program that prompts the user to enter a binary number and displays
# the corresponding hexadecimal value.
def f(x):
return {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
10: 'A',
11: 'B',
12: 'C',
13: 'D',
14: 'E',
15: 'F'
}[x]
def binaryToHex(binaryValue):
binary = binaryValue[::-1]
hex = ""
while len(binary) > 0:
currentBinary = binary[0:4]
decimal = 0
for i in range(len(currentBinary)):
decimal += int(currentBinary[i]) * 2 ** i
hex += f(decimal)
binary = binary[4:len(binary)]
hex = hex[::-1]
return hex
binary = input("Enter a binary String: ")
print(binaryToHex(binary))
# 11101100101001 should equal 3B29
| false |
b28fb1d735adb395be69b8371e06aa480f778e6a | noel-maldonado/Data-Programming | /HW Assignments/Chapter_6/Exercise_5.py | 1,076 | 4.53125 | 5 | # (Sort three numbers) Write the following function to display three numbers in
# increasing order:
# def displaySortedNumbers(num1, num2, num3):
# Write a test program that prompts the user to enter three numbers and invokes the
# function to display them in increasing order. Here are some sample runs:
def displaySortedNumbers(i1, i2, i3):
max = ''
min = ''
mid = ''
if i1 > i2 > i3:
max = str(i1)
min = str(i3)
mid = str(i2)
elif i2 > i3 > i1:
max = str(i2)
min = str(i1)
mid = str(i3)
elif i3 > i1 > i2:
max = str(i3)
min = str(i2)
mid = str(i1)
elif i3 > i2 > i1:
max = str(i3)
min = str(i1)
mid = str(i2)
elif i2 > i1 > i3:
max = str(i2)
min = str(i3)
mid = str(i1)
elif i1 > i3 > i2:
max = str(i1)
min = str(i2)
mid = str(i3)
print("The sorted numbers are ", min, mid, max)
i1, i2, i3 = eval(input('Enter three digits (seprate with a comma): '))
displaySortedNumbers(i1, i2, i3)
| true |
51521e711e14ae69c829167af95bc123b295cdca | alishalopes87/hb-coding-challenges | /palindrome_number.py | 804 | 4.40625 | 4 |
# Determine whether an integer is a palindrome.
# An integer is a palindrome when it reads the same backward as forward.
# Example 1:
# Input: 121
# Output: true
# Example 2:
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
# Input: 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Follow up:
# Coud you solve it without converting the integer to a string?
def palindrome_numnber(nums):
index = 0
nums = str(nums)
for num in range(len(nums)-1,-1,-1):
if nums[num] == nums[index]:
index += 1
else:
return False
return True
print(palindrome_numnber(121))
print(palindrome_numnber(-121))
print(palindrome_numnber(10)) | true |
744c3822fd9ff91168419e683f2b6a9846ea7ffd | alishalopes87/hb-coding-challenges | /wordlengths.py | 1,640 | 4.3125 | 4 | """Get dictionary of word-length: {words}.
Given a phrase, return dictionary keyed by word-length, with the value for
each length being the set of words of that length.
For example::
>>> answer = word_lengths("cute cats chase fuzzy rats")
This should return {4: {'cute', 'cats'}, 5: {'chase', 'fuzzy', 'rats'}},
but since both dictionaries and sets are unordered, we can't just check if
it matches that exact string, so we'll test more carefully::
>>> sorted(answer.keys())
[4, 5]
>>> answer[4] == {'cute', 'cats', 'rats'}
True
>>> answer[5] == {'chase', 'fuzzy'}
True
Punctuation should be considered part of a word, so you only need to
split the string on whitespace::
>>> answer = word_lengths("Hi, I'm Balloonicorn")
>>> sorted(answer.keys())
[3, 12]
>>> answer[3] == {'Hi,', "I'm"}
True
>>> answer[12] == {"Balloonicorn"}
True
"""
def word_lengths(sentence):
"""Get dictionary of word-length: {words}."""
#iterate over setence
#check currents length
#check if word length is in dictionary
#if it is add word to that values set
#if not add set with that value in it
#return dictionary
word_length_to_words = {}
s = sentence.split(" ")
for word in s:
length = len(word)
if length in word_length_to_words:
word_length_to_words[length].add(word)
else:
word_length_to_words[length] = {word}
return word_length_to_words
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. NOTHING ESCAPES YOU!\n")
| true |
3864eec8da5463d3eabab111fb14014fce008c41 | sweet23/oreillyPython1 | /Chap11-DefineFunctions/return_value.py | 1,499 | 4.21875 | 4 | __author__ = 'outofboundscommunications'
#To change this template use Tools | Templates.
#
def structure_list(text):
"""Returns a list of punctuation & location of
the word 'Python' in a sample of text"""
punctuation_marks = "!?.,:;"
punctuation = []
for mark in punctuation_marks:
if mark in text:
punctuation.append(mark)
return punctuation, text.find('Python')
text_block = """\
Python is used everywhere nowadays.
Major users including Google, Yahoo!, CERN and NASA (a team of 40 scientists and engineers
are using Python to test the systems supporting the Mars Space Lander project).
ITA, the company that produces the route search engine? used by Orbitz, CheapTickets,
travel agents and many international and national airlines, uses Python extensively.
This snippet of text taken from chapter 1."""
print(text_block)
print('-'*80)
#counter for # instances of the word python
counter =0
for line in text_block.splitlines():
print(line)
p,l = structure_list(line)
if p:
print("Contains:", p)
else:
print("No punctuation in this line of text")
if ',' in p:
print("This line contains a comma")
if '?' in p:
print("this line contains a question mark.")
if l >= 0:
print("Python is first used at {0}".format(l))
#increment counter
counter +=counter
print(counter)
print('-'*80)
print('-'*80)
print("the number of times python was found in the text was: ", counter))
| true |
9f429432a6a5ed3c0c1e20ea914f85a9836f8090 | sweet23/oreillyPython1 | /Chap14-OOP/14Quiz1-2.py | 1,225 | 4.3125 | 4 | """
Quiz 1 and 2 questions and answers
"""
"""Quiz 1 """
Question1_1 = "How do you define a class called 'Friend' in Python?"
Answer1_1 = "class Friend: "
Question1_2 = "How do you instantiate 'Friend' as an object, and save it to the variable 'f'? "
Answer1_2 = "f=Friend"
Question1_3 = "How would you add an attribute called 'title' with a value of 'buddy' to the f object \
you created in the previous question?"
Answer1_3 = "f.title = 'buddy'"
""" Quiz 2"""
Question2_1="What is the name of the __xx__ method that lets you represent the value of a class as a string?"
Answer2_1="It is the __str__() method"
Question2_2="Where can you store an instantiated object?"
Answer2_2 = "You can store an instantiated object locally or globally."
#function that prints out each question to the screen
def printQuestion(num,question):
print(60*'-')
print('\n', 'Question#:',num)
print(question,'\n')
def printAnswer(answer):
print(%s % answer)
printQuestion(Question1_1)
printAnswer(Answer1_1)
printQuestion(Question1_2)
printAnswer(Answer1_2)
printQuestion(Question1_3)
printAnswer(Answer1_3)
printQuestion(Question2_1)
printAnswer(Answer2_1)
printQuestion(Question2_2)
printAnswer(Answer2_2)
| true |
8264e427bffafeb9bb71e4b008e8945b0bd9a669 | sweet23/oreillyPython1 | /Chap14-OOP/Obj1-doggies.py | 2,901 | 4.4375 | 4 | """
Objective 1:
This project tests more of your understanding of classes and objects.
Create a new Python source file named doggies.py.
Write a class named Dog. Dog's __init__() method should take two parameters, name and breed, in addition to the implicit self.
Bind an empty list to a dogs global variable (dogs should not be an attribute of the Dog class).
Using a while loop, get user input for name and breed. The loop should terminate when the user enters a blank name.
For each name and breed entered, create an instance of the Dog class with name and breed as arguments. Append the object to the dogs list.
Each time around the loop, print the current dogs list (the name and breed of each dog).
notes from instructor after 1st submission:
Good work tackling __str__ which will govern what print(dog) does. Your version:
def __str__(self):
return "Dog Name: %s\nDog Breed: %s" % (self.name, self.breed)
in general terms there's nothing amiss i.e. you're free to represent a dog instance however
you wish, sticking to string output but...
for this particular project, wouldn't name:breed as in "Rover:Mutt" make the most sense?
Then it's up to enumerate, as you were starting to use, to supply the consecutive integers.
That's not a Dog's business anyway (Dogs can't count, we all know that), so just have
__str__ give that little piece of the puzzle and embellish? Good approach.
No need for Dog to have any methods beyond __init__ (birth) and __str__ (show me as a string).
That's enough for this project.
Also, if one didn't bother with __str__ you would still have access to
dog.name
and
dog.breed
as instance attributes e.g.
for ...
print("{0} {1}:{2}".format( ))
using these as arguments.
__str__ is icing on the cake more than essential / required.
Good work so far.
-Kirby
"""
#Bind an empty list to a dogs global variable (dogs should not be an attribute of the Dog class).
dogs = []
#Write a class named Dog. Dog's __init__() method should take two parameters, name and breed, in addition to the implicit self.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def __str__(self):
return "%s:%s" % (self.name, self.breed)
#Using a while loop, get user input for name and breed.
while True:
dogName = input("Provide Dog Name:")
#The loop should terminate when the user enters a blank name.
if dogName == '':
break
dogBreed = input("Provide dog breed:")
#For each name and breed entered, create a Dog object.
myDog = Dog(dogName,dogBreed)
#Append the object to the dogs list
dogs.append(myDog)
print("DOGS")
#for dog in dogs:
# print(dog.name,dog.breed)
for i,dog in enumerate(dogs):
print("{0}:{1}:{2}".format(i,dog.name,dog.breed))
print('------------------')
| true |
2bc91c6d6cb060ad21b8debe458a530c41e51f68 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc151_reverse_words_in_string.py | 1,174 | 4.1875 | 4 | '''
https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
Example 1:
Input: "the sky is blue"
Output: "blue is sky the"
Example 2:
Input: " hello world! "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words
to a single space in the reversed string.
'''
class Solution:
def reverseWords(self, s: str) -> str:
sSplit = s.split(" ")
outStr = ""
for i in range(len(sSplit)-1, -1, -1):
word = sSplit[i]
if word:
outStr += (word + " ")
return outStr[:-1]
def test1(self, alg):
input1 = "the sky is blue"
input2 = " hello world! "
input3 = "a good example"
inputs = [input1, input2, input3]
print("test1 results:")
for inp in inputs:
res = self.reverseWords(inp)
print("input: {}\tres: {}".format(inp, res))
s = Solution()
alg = s.reverseWords
s.test1(alg) | true |
8f5253f218c8dba51fe8c87411ea56a8d35f9d46 | mcxu/code-sandbox | /PythonSandbox/src/leetcode/lc114_flatten_binary_tree_to_linked_list.py | 2,133 | 4.21875 | 4 | '''
114. Flatten Binary Tree to Linked List
*flatten in-place without returning the root
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.value = self.val
self.left = None
self.right = None
class Solution:
'''
Let n = num nodes in tree.
Time complexity: O(n), because the algorithm recurses over n nodes.
Space complexity: O(1), because there is a constant number of additional pointers needed (tmpRight, and tmpLeft).
'''
def flatten(self, root):
if root == None:
return None
if root.left != None:
tmpRight = root.right
root.right = root.left
root.left = None
tmpLeft = root.right
while tmpLeft.right != None:
tmpLeft = tmpLeft.right
tmpLeft.right = tmpRight
self.flatten(root.left)
self.flatten(root.right)
return None
def tree1(self):
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
return root
def tree2(self):
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right = TreeNode(5)
root.right.right = TreeNode(6)
return root
def tree3(self):
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
return root
def test1(self):
root = self.tree1()
self.flatten(root) #root flattened
print("root: ", root.val)
print("root.right: ", root.right.val)
def test2(self):
root = self.tree2()
self.flatten(root)
rf = root
print("rf root: ", rf.val)
print("rf.left: ", rf.left)
print("rf.right: ", rf.right.val)
print("rf.right.left: ", rf.right.left)
print("rf.right.right: ", rf.right.right.val)
sol = Solution()
sol.test1()
#sol.test2()
| true |
2fa39633d2e8310342a26a166d56b0b24cc35055 | mcxu/code-sandbox | /PythonSandbox/src/misc/inversions_in_arrray.py | 1,527 | 4.1875 | 4 | """
Count inversions in an array using a merge sort method.
Basically count how "unordered" an array is.
"""
class Solution:
def countInversions(self, arr):
mergedArr, totalCount = self.mergeSortAndCount(arr)
print("mergedArr: ", mergedArr)
return totalCount
def mergeSortAndCount(self, arr):
print("----- mergeSortAndCount: arr: ", arr)
if len(arr) <= 1:
return arr, 0
leftSubarray, leftCount = self.mergeSortAndCount(arr[:len(arr)//2])
rightSubarray, rightCount = self.mergeSortAndCount(arr[len(arr)//2:])
# merge the 2 halves
mergeCount = 0
mergedArr = []
i, j = 0, 0
while i < len(leftSubarray) and j < len(rightSubarray):
print(f"i:{i}, j:{j}")
if leftSubarray[i] <= rightSubarray[j]: # already correct order
mergedArr.append(leftSubarray[i])
i += 1
else:
mergedArr.append(rightSubarray[j]) # fix inverted order
j += 1
mergeCount += len(leftSubarray)-i
print("mergeCount: ", mergeCount)
mergedArr += leftSubarray[i:]
mergedArr += rightSubarray[j:]
totalCount = leftCount + rightCount + mergeCount
return mergedArr, totalCount
def test(self):
# arr = [4, 3, 2, 1] # expected = 6
arr = [2, 1, 4, 3, 5] # expected = 2
res = self.countInversions(arr)
print("res: ", res)
s = Solution()
s.test() | true |
4518b7d983e1ef14dc9b0e2c4796e79a3713ca49 | mcxu/code-sandbox | /PythonSandbox/src/daily_coding_problem/dcp5_inner_functions_car_cdr.py | 1,459 | 4.375 | 4 | """
This problem was asked by Jane Street. [Medium]
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair.
For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Implement car and cdr.
"""
class DCP5():
def cons(self, a, b):
print("cons: a={}, b={}".format(a,b))
def pair(f):
print("cons:pair: a={}, b={}".format(a,b))
return f(a, b)
return pair
'''
pass in the function definition of pair, but need a function to take place of f to return first or last element.
Applies to both car and cdr
'''
def car(self, pair):
print("in car")
def f(a, b):
print("car:first: a={}, b={}".format(a,b))
return a
return pair(f)
def cdr(self, pair):
print("in cdr")
def f(a, b):
print("cdr:last: a={}, b={}".format(a,b))
return b
return pair(f)
def test_cons(self):
pair = self.cons(3,4)
print("pair: {}".format(pair))
# pass in the function definition of 'pair'
a = self.car(pair)
print("test_cons: a: {}".format(a))
b = self.cdr(pair)
print("test_cons: b: {}".format(b))
def main():
p5 = DCP5()
p5.test_cons()
if __name__ == "__main__":
main() | true |
0781d8da5635e27dc88b6e145e4aaf32d1f7c4e8 | zhendeliu/unsw-2019-t1 | /unsw-it-9021/python-code/Pre-final/pre_final_exam_mysolution/exercise_8.py | 2,495 | 4.28125 | 4 |
dictionary_file = 'dictionary.txt'
def number_of_words_in_dictionary(word_1, word_2):
'''
"dictionary.txt" is stored in the working directory.
>>> number_of_words_in_dictionary('company', 'company')
Could not find company in dictionary.
>>> number_of_words_in_dictionary('company', 'comparison')
Could not find at least one of company and comparison in dictionary.
>>> number_of_words_in_dictionary('COMPANY', 'comparison')
Could not find at least one of COMPANY and comparison in dictionary.
>>> number_of_words_in_dictionary('company', 'COMPARISON')
Could not find at least one of company and COMPARISON in dictionary.
>>> number_of_words_in_dictionary('COMPANY', 'COMPANY')
COMPANY is in dictionary.
>>> number_of_words_in_dictionary('COMPARISON', 'COMPARISON')
COMPARISON is in dictionary.
>>> number_of_words_in_dictionary('COMPANY', 'COMPARISON')
Found 14 words between COMPANY and COMPARISON in dictionary.
>>> number_of_words_in_dictionary('COMPARISON', 'COMPANY')
Found 14 words between COMPARISON and COMPANY in dictionary.
>>> number_of_words_in_dictionary('CONSCIOUS', 'CONSCIOUSLY')
Found 2 words between CONSCIOUS and CONSCIOUSLY in dictionary.
>>> number_of_words_in_dictionary('CONSCIOUS', 'CONSCIENTIOUS')
Found 3 words between CONSCIOUS and CONSCIENTIOUS in dictionary.
'''
with open(dictionary_file) as ff:
words= ff.readlines()
if word_1.islower() or word_2.islower():
if word_1 == word_2:
print(f'Could not find {word_1} in dictionary.')
else:
print(f'Could not find at least one of {word_1} and {word_2} in dictionary.')
return
p = None
q = None
for i in range(len(words)):
if words[i].strip() == word_1:
p = i
if words[i].strip() == word_2:
q = i
if q and p:
c = abs(q-p)
if c == 0:
print(f'{word_1} is in dictionary.')
else:
print(f'Found {c+1} words between {word_1} and {word_2} in dictionary.')
else:
if word_1 == word_2 :
print(f'Could not find {word_1} in dictionary.')
else:
print(f'Could not find at least one of {word_1} and {word_2} in dictionary.')
# REPLACE THE PREVIOUS LINE WITH YOUR CODE
#number_of_words_in_dictionary('CONSCIOUS', 'CONSCIOUSLY')
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
ebb04b5609ca302ee5282adc74924c7e95c58da8 | santia-bot/python | /trabajos de la clase/clase 13 marzo.py | 840 | 4.28125 | 4 | print("clase de lista")
"""
nombre
telefono
correo
sintaxis: lista = []
sintanxis: tupla = ()
"""
#lista = ["guadalupe", 32, "55523456", "diazsantix@gmail.com", False ]
#print(lista)
#slicing // buscar
lista2 = ["python", "java", "c++", "PHP", "MySQL", "C#"]
print("llamar un elemento:", lista2[0])
print("numeros de elementos en lista", len(lista2))
sub = lista2[1::3]
#sub = lista2[:: -2] /brincos al reves
#sub = lista2[:: -1] #alreves
#sub = lista2[1::3] #brincos
#sub = lista2[::2]# 2 en 2 /buscar mas
#lista[:-1] #se imprimer el ultimo
print("\n sublista:", sub,)
lista2.append("POO")
print(lista)
"""
tuplas
"""
tupla = ("guadalupe", "antonio", "pilio", 32, "30076375609")
print("llamar un elemento:", tupla[0])
print("numeros de elementos",len(tupla))
print( "\n subtupla:",subt )
#print(tupla[-2])
#tupla.append("juan") no se puede agregar | false |
697216b565e643ea803ad0ff8629c6e2e3643d83 | sevln/PyProjects | /FactorCalculator/FactorCalculator.py | 1,776 | 4.4375 | 4 | # FACTOR CALCULATOR
# Asks user to input positive integer
# Calculates and prints out the factors of the integer in order from lowest to highest
import math
# calculates and prints out factors of integer input by user
# factors will always include 1 and the integer
# n = integer input by user
# DEBUGGING FUNCTION
def debug(my_list):
for item in my_list:
print(item)
def factor(n):
lim = math.floor(math.sqrt(n)) # finding max whole number needed to find all factors
# print("lim: %d " % lim) # DEBUGGING
# finding factors
fact1 = [1] # for small half of factors, including 1
fact2 = [n] # for large half of factors, including n
# iterate through possible factors, starting at 2
for i in range(2, lim + 1, 1):
# print("i: %d" % i) # DEBUGGING
if n % i == 0:
x = int(n / i) # calculating second factor value
fact1.append(i) # adding small factor to first list
# debug(fact1) # DEBUGGING
if x != i: # adding large factor only if not a square factor
fact2.append(x)
# debug(fact2) # DEBUGGING
str1 = ','.join(str(f) for f in fact1)
str2 = ','.join(str(f) for f in reversed(fact2))
print(str1 + "," + str2)
print("\n")
return
# main function asks user to input integer for factoring
# calls factor function and outputs factors of integer input by user
def main():
loop = True
# continuous looping of program
while loop:
num = int(input("Enter a positive integer you'd like factored: ")) # asks user for integer to factor
factor(num) # factoring number entered by user
# calling main function
if __name__ == "__main__":
main()
| true |
39233f6f4817d2fd40666b85816a0435123cd218 | TomaszMazurekWSB/WSB-Python | /.github/workflows/adapter_design_pattern.py | 2,164 | 4.1875 | 4 | # This is a demo code for Adapter design pattern. This design
# pattern is used when we are required to join two incompatible interfaces.
# It basically uses the concept of polymorphism to convert the interface
# of a class into another interface based on requirement.
# Creating the first interface
class EuropeanSocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
def earth(self): pass
# Adaptee implementing the first interface
class Socket(EuropeanSocketInterface):
def voltage(self):
return 230
def live(self):
return 1
def neutral(self):
return -1
def earth(self):
return 0
# Target interface which is normally incompatible with the
# first interface (i.e. EuropeanSocketInterface)
class USASocketInterface:
def voltage(self): pass
def live(self): pass
def neutral(self): pass
# The Adapter, which implements the target interface
class Adapter(USASocketInterface):
__socket = None
def __init__(self, socket):
self.__socket = socket
def voltage(self):
return 110
def live(self):
return self.__socket.live()
def neutral(self):
return self.__socket.neutral()
# Client class which requires the connection between adapter
# and adaptee to properly function
class ElectricKettle:
__power = None
def __init__(self, power):
self.__power = power
def boil(self):
if self.__power.voltage() > 110:
print("Kettle on fire!")
else:
if self.__power.live() == 1 and \
self.__power.neutral() == -1:
print("Coffee time!")
else:
print("No power.")
# Main function
# In this implementation the adapter relies on the object implementation.
def main():
# Initializing plugins
socket = Socket()
adapter = Adapter(socket) # Creating a bridge between the two incompatible interfaces
kettle = ElectricKettle(adapter) # utilizing the interfaces
# Running the function to checif bridge is successfully working or not
kettle.boil()
return 0
# Used to call the main method
if __name__ == "__main__":
main() | true |
24640c538929b0a1de1163ee64cd57064aac829b | bri-cottrill/Old-Python-HW | /wrap_file.py | 848 | 4.28125 | 4 |
"""
02/13/19 Week 5 HW - Generators II.
Get user input for file to open, then pass to wrap_filetext()
Assignment Prompt:
Rewrap text from the filename passed so that it fits an 80 column window without breaking any words.
Use a generator that yields the next line of text, containing as many words as possible.
"""
import textwrap
def wrap_filetext(filename):
"""Yield the wrapped line of the file. Max 80 characters per line."""
try:
open_file = open(filename)
except:
print("File cannot be opened: ", filename)
print("Goodbye.")
exit()
wrapper = textwrap.TextWrapper(width=80)
yield from (wrapper.fill(text=' '.join(line.split(" "))) for line in open_file)
entered_file = input("Enter the file name you want to wrap: ")
for wrap_line in wrap_filetext(entered_file):
print(wrap_line)
| true |
5cb26fe266f115515fcca5b27bf2d4b8bd6ecfb5 | HarshithaKP/Python-practice-questions- | /19.py | 1,091 | 4.21875 | 4 | # Implement a program using CLA for simple arithmetic calculator exmaple:
# operand operator operand ie. 10 + 10 / 30 * 20
import sys
import getopt
def addition(num1,num2):
summ=num1+num2
print("Sum of two numbers is :",summ)
def subtraction(num1,num2):
subt=num1-num2
print("Sum of two numbers is :",subt)
def multiplication(num1,num2):
mul=num1*num2
print("Sum of two numbers is :",mul)
def divisionion(num1,num2):
div=num1/num2
print("Sum of two numbers is :",div)
def main():
(myopts,args)=getopt.getopt(sys.argv[1:],"n:p:m:"["number1=","operator=","number2="])
print("Myopt values :",myopts)
print("Args values :",args)
for o,a in myopts:
if o in('-n',"--number1"):
print("operand1 is ",a)
n=int(a)
elif o in('-m',"--number2"):
print("Opwrand2 is ",a)
m=int(a)
elif o in('-p',"--operator"):
print("Operator is ",a)
operator=a
if(operator=='+'):
addition(num1,num2)
if(operator=='-'):
subtraction(num1,num2)
if(operator=='*'):
multiplication(num1,num2)
if(operator=='/'):
division(num1,num2)
if __name__ == '__main__':
main()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.