blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b9b22be77a2ec061bba9dea6a8967e6f18e1da3c | cumtqiangqiang/leetcode | /top100LinkedQuestions/5_longest_palindromic_sub.py | 783 | 4.125 | 4 | '''
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
def longestPalindrome(s: str) -> str:
start = 0
end = 0
for i in range(len(s)):
len1 = getTheLengthOfPalindrome(s,i,i)
len2 = getTheLengthOfPalindrome(s,i,i+1)
maxLen = max(len1,len2)
if maxLen > end - start:
start = i - (maxLen - 1)//2
end = i + maxLen//2
return s[start:end+1]
def getTheLengthOfPalindrome(s,left,right):
while(left >= 0 and right <= len(s) and s[left:left+1] == s[right:right+1]):
left -= 1
right += 1
return right - left -1
if __name__ == '__main__':
s = longestPalindrome("acbbcd")
print(s) | true |
f1386a1b5ff8705938dbdd96f11c954fdf1dfd3c | diceitoga/regularW3PythonExercise | /Exercise8.py | 339 | 4.125 | 4 | #Exerciese 8: 8. Write a Python program to display the first and last colors from the following list. Go to the editor
#color_list = ["Red","Green","White" ,"Black"]
color_list = ["Red","Green","White" ,"Black"]
lengthof=len(color_list)
print("First Item: {}".format(color_list[0]))
print("Last Item: {}".format(color_list[lengthof-1]))
| true |
cf2a4e7217f251ae3b854f5c5c44eaa3ea3f140b | diceitoga/regularW3PythonExercise | /Ex19_is.py | 413 | 4.21875 | 4 | #Ex 19: Write a Python program to get a new string from a given string where "Is" has been added to the front.
#If the given string already begins with "Is" then return the string unchanged
print("test")
sentence_string = input("Please enter a short sentence and I will add something: ")
first_l = sentence_string.split(' ')
if first_l[0] == 'Is':
print(sentence_string)
else:
print("Is " + sentence_string)
| true |
84fee185f3fbf9a59cf1efe89ca7ff5472e97691 | diceitoga/regularW3PythonExercise | /Ex21even_odd.py | 388 | 4.46875 | 4 | #Ex21. Write a Python program to find whether a given number (accept from the user) is even or odd,
#print out an appropriate message to the user.
def even_odd(num):
even_odd = ''
if num%2==0:
even_odd = 'even'
else:
even_odd = 'odd'
return even_odd
what_isit =even_odd(int(input("Please enter an integer between 1-100 and I will tell you if even or odd: ")))
print(what_isit)
| true |
d83882634e4db5e59edfbb1c760ef0483010fd3b | joqhuang/si | /lecture_exercises/gradepredict.py | 2,003 | 4.40625 | 4 | # discussion sections: 13, drop 2
# homeworks: 14, drop 2
# lecture exercise: 26, drop 4
# midterms: 2
# projects: 3
# final project: 1
# get the data into program
# extract information from a CSV file with all the assignment types and scores
# return a data dictionary, where the keys are assignment groups and values are lists of scores
def get_data():
pass
# identify and drop the lowest grades for discussion, homework, lecture
# takes a list of scores and drops the lowest number specified
def drop_lowest(list_of_scores, num_to_drop):
pass
#take the list for all the scores in a single assignment group and returns the group total
def compute_group_total(list_of_scores):
pass
# adds up total points across categories
# convert from points to percentage
# convert to letter grade
def compute_grade(total_score):
pass
def test_functions():
#test drop_lowest
list1 = [10,9,8,7,6]
expected_return1 = [10,9,8]
expected_return1 = [10]
#test compute_group_total
list2= [1,1,1,1]
expected_return3 = 4
passed = 0
failed = 0
if drop_lowest(list1,2)==expected_return1:
#test passed
passed += 1
else:
#test tailed
failed += 1
print("failed test 1")
if drop_lowest(list1,4)==expected_return2:
#test passed
passed += 1
else:
#test tailed
failed += 1
print("failed test 2")
if compute_group_total(list2) == expected_return3:
passed += 1
else:
failed += 1
print("failed test 3")
data_dict = get_data()
# homework_scores = drop_lowest(data_dict['homeworks'],2)
# lecture_scores = drop_lowest(data_dict['lectures'],4)
# discussion_scores = drop_lowest(data_dict['discussion'],2)
# etc for each assignment types
# use compute_group_total for each group, and append those values to a list
# use compute_group_total on the list of group totals to calculate the total_score
# grade = compute_grade(total_score)
# print(grade)
| true |
0abe0e63e9cd588267c456a87ea6ce6068e3da15 | Tonyqu123/data-structure-algorithm | /Valid Palindrome.py | 720 | 4.3125 | 4 | # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
#
# For example,
# "A man, a plan, a canal: Panama" is a palindrome.
# "race a car" is not a palindrome.
#
# Note:
# Have you consider that the string might be empty? This is a good question to ask during an interview.
#
# For the purpose of this problem, we define empty string as valid palindrome.
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) != 0:
result = [char.lower() for char in s if char.isalnum()]
return result == result[::-1]
else:
return True | true |
8c7569bf644859b9a51d0a6b06935c0dcbbfd509 | chococigar/Cracking_the_code_interview | /3_Stacks_and_Queues/queue.py | 598 | 4.1875 | 4 | #alternative method : use lists as stack
class Queue(object) :
def __init__(self):
self.items = []
def isEmpty(self):
return (self.items==[])
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
self.items.pop() #first in first out. last item is first.
def size(self):
return len(self.items)
def show(self):
print("top "),
for elem in self.items:
print elem, ", ",
print("bottom (first out)")
s = Queue()
s.enqueue(1)
s.enqueue(2)
s.enqueue(3)
s.enqueue(4)
s.enqueue(5)
s.show()
| true |
93b706571c7b3451f5c677cc7d9ddb1dffa67f13 | blkbrd/python_practice | /helloWorld.py | 2,330 | 4.15625 | 4 | print ("hello World")
'''
#print('Yay! Printing.')
#print("I'd much rather you 'not'.")
#print('I "said" do not touch this.')
print ( "counting is fun")
print ("hens", 25 + 30 / 6)
print ("Is it greater?", 5 > -2)
#variables
cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers,
"in each car.")
#strings
my_name = 'Lillian'
my_age = 24 /3 # not a lie
my_height = 67 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Blonde'
print(f"Let's talk about {my_name}.")
print(f"She's {my_height} inches tall.")
print(f"She's {my_weight} pounds heavy.")
#print("Actually that's not too heavy.")
print(f"She's got {my_eyes} eyes and {my_hair} hair.")
print(f"Her teeth are usually {my_teeth} depending on the coffee.")
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
types_of_people = 10
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
print(f"I also said: '{y}'")
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {}"
print(joke_evaluation.format(hilarious))
w = "This is the left side of..."
e = "a string with a right side."
print(w + e)
print("Its fleece was white as {}.".format('snow'))
print("." * 10) # what'd that do?
formatter = "{} and a {} and a {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"a",
"b",
"c",
"d"
))
'''
x = input("something: ")
#print((int)x + 4) #how do i take int input????
| true |
64f31b62c4a464b495cf051d73c26b67b37cc8bb | padma67/guvi | /looping/sum_of_first_and_last_digit_of_number.py | 342 | 4.15625 | 4 | # Program to find First Digit and last digit of a Number
def fldigit():
number = int(input("Enter the Number: "))
firstdigit = number
while (firstdigit >= 10):
firstdigit = firstdigit // 10
lastdigit = number % 10
print("sum of first and last digit of number is {0}".format(firstdigit+lastdigit))
fldigit()
| true |
df2c4134cb5454aac257dcb270cc651595b3a8c4 | padma67/guvi | /looping/Calculator.py | 865 | 4.1875 | 4 | #Calculator
#get the input value from user
num1=float(input("Enter the number 1:"))
num2=float(input("Enter the number 2:"))
print("1.Add")
print("2.Sub")
print("3.Div")
print("4.Mod")
print("5.Mul")
print("6.Expo")
#get the function operator from uuer
ch=float(input("Enter your choice:"))
c=round(ch)
if(c==1):
print("The output of ",num1,"and",num2,"is",num1+num2)
elif(c==2):
print("The output of ",num1,"and",num2,"is",num1-num2)
elif(c==3):
if(num2==0):
print("The output of ",num1,"and",num2,"is Infinity")
else:
print("The output of ",num1,"and",num2,"is",num1/num2)
elif(c==4):
print("The output of ",num1,"and",num2,"is",num1%num2)
elif(c==5):
print("The output of ",num1,"and",num2,"is",num1*num2)
elif(c==6):
print("The output of ",num1,"and",num2,"is",num1**num2)
else:
print("Invalid choice")
| true |
451744ff93bd4ee503af5d2f28e1bf8d89f16517 | padma67/guvi | /looping/Print_even_numbers_from_1_to_100.py | 264 | 4.1875 | 4 | #To print all even numbers between 1 to 100
def Even():
#declare the list for collect even numbers
even=[]
i=1
while(i<=100):
if(i%2==0):
even.append(i)
i=i+1
print("even numbers between 1 to n",even)
Even()
| true |
6e135b53bbde0cd65bdf7c36815195dd29e6ec66 | Nitin26-ck/Scripting-Languages-Lab | /Part B/Lab 5/Prg5_file_listcomprehension.py | 2,064 | 4.1875 | 4 | """
Python File Handling & List Comprehension
Write a python program to read contents of a file (filename as argument) and store the number of occurrences of each word in a dictionary.
Display the top 10 words with the most number of occurrences in descending order.
Store the length of each of these words in a list and display the list.
Write a one-line reduce function to get the average length and one-line list comprehension to display squares of all odd numbers and display both.
"""
import sys
import os
from functools import reduce
dict = {}
wordLen = []
if(len(sys.argv) != 2):
print ("Invalid Arguments")
sys.exit()
if(not(os.path.exists(sys.argv[0]))):
print ("Invalid File Path")
sys.exit()
if(sys.argv[1].split('.')[-1] != "txt"):
print ("Invalid File Format. Only TXT files allowed")
sys.exit()
with open(sys.argv[1]) as file:
for line in file:
for word in line.split():
dict[word] = dict.get(word,0) + 1
print (dict)
# Display the top 10 words with most number of occurrences in descending order.
# Food for thought - Does a dictionary maintain order? How to print 10 words with most frequency?
# Ans - extract dict items as Tuples and sort them based on value in dictionary
#(second item of the tuple / index 1)
sortedDict = sorted(dict.items(), key=lambda dictItem: dictItem[1], reverse=True)
for i in range(len(sortedDict)):
print(sortedDict[i])
for i in range(10):
try:
wordTuple = sortedDict[i]
wordLen.append(len(wordTuple[0]))
print (wordTuple[0], ", Frequency: " , wordTuple[1] , ", Length " , len(wordTuple[0]))
except IndexError:
print ("File has less than 10 words")
break
print ("Lengths of 10 most frequently occuring words:")
print (wordLen)
# Write a one-line reduce function to get the average length
sum = reduce(lambda x,y: x+y, wordLen)
print ("Average length of words: " , sum/len(wordLen))
# Write a one-line list comprehension to display squares of all odd numbers
squares = [x**2 for x in wordLen if x%2 != 0]
print ("Squres of odd word lengths: ")
print (squares)
| true |
221fdeb75e2f6db401901b5755e991bdffdcee75 | Nitin26-ck/Scripting-Languages-Lab | /Part B/Lab 1/Prg1c_recursion_max.py | 809 | 4.15625 | 4 | """
Introduction to Python : Classes & Objects, Functions
c) Write a recursive python function that has a parameter representing a list of integers
#and returns the maximum stored in the list.
"""
#Hint: The maximum is either the first value in the list or the maximum of the rest of
#the list whichever is larger. If the list only has 1 integer, then its maximum is this
#single value, naturally. Demonstrate with some examples.
def Max(list):
if len(list) == 1:
return list[0]
else:
m = Max(list[1:])
return m if m > list[0] else list[0]
def main():
try:
list = eval(input("Enter a list of numbers: "))
print ("The largest number is: ", Max(list))
except SyntaxError:
print ("Please enter comma separated numbers")
except:
print ("Enter only numbers")
main()
| true |
901e5ae13f821c2e3da9df9b46d9a1d7e7cc003c | KodingKurriculum/learn-to-code | /beginner/beginner_3.py | 1,789 | 4.78125 | 5 | # -*- coding: utf-8 -*-
"""
Beginner Script 3 - Lists, and Dictionaries
Functions allow you to group blocks of code and assign it a name. Functions
can be called over and over again to perform specific tasks and return values
back to the calling program.
"""
"""
1.) Lists (also known as an Array) are great for storing a series of information.
You can iterate the list to access its contents, or specify a single value. Python
is zero-based, in that each position in the array is given a number from 0 to the
last element.
c
Add your name to the list, then have the script print your name.
"""
my_list = ['Karl', 'Karly', 'Kristoph', 'Kurt']
# print(...)
"""
2.) You may iterate the list using the "for loop" again.
Iterate the list of names and print out.
"""
# for name in ...:
"""
2.) Dictionaries are even more useful in that they can store key/value pairs of
information. As you may notice, the dictionary below looks a lot like an Excel
header with a list of values below.
Add my_list to the dictionary
"""
my_dict = {
"Numbers": [1, 2, 3, 4, 5],
"Fruit": ["Apple", "Orange", None, "Orange", "Peach"]
}
"""
3.) Dictionaries have key/value pairs which is useful for looking information up
based on a known key. You can do this using the syntax my_dict['key'].
Look up the list of fruits from my_dict, and print the first fruit out.
"""
# fruits = ...
"""
4.) Python is an object-oriented language, and every variable has a group of
functions that you may call. To iterate the list of dictionary key/value
pairs, we need to call the dictionary's .items() function, such as my_dict.items().
Iterate the list of key/value pairs and print them out.
"""
def printValues(dict):
# for key, value in ...:
# print("My favorite {0} is {1}".format(key, value))
| true |
0f882e8b74773b888de20be38564c13642cd306a | ijuarezb/InterviewBit | /04_LinkedList/K_reverse_linked_list.py | 2,527 | 4.125 | 4 | #!/usr/bin/env python3
import sys
#import LinkedList
# K reverse linked list
# https://www.interviewbit.com/problems/k-reverse-linked-list/
#
# Given a singly linked list and an integer K, reverses the nodes of the
#
# list K at a time and returns modified linked list.
#
# NOTE : The length of the list is divisible by K
#
# Example :
#
# Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2,
#
# You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5
#
# Try to solve the problem using constant extra space.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def reverseList(self, A, B):
# swap the List >> in Groups << of B items
head = last = None
while A:
start = A
prev = A
A = A.next
for i in range(1, B):
next = A.next
A.next = prev
prev = A
A = next
if last:
last.next = prev
last = start
if not head:
head = prev
if last:
last.next = None
return head
def print_list(self, head):
temp = head
while temp:
print(temp.val, end=' ')
temp = temp.next
print("")
# swap K pairs
def swapPairs(self, A, B):
fake_head = ListNode(0)
fake_head.next = A
tmp, i = fake_head, 0
while tmp and tmp.next and tmp.next.next and i < B:
nxt = tmp.next
tmp.next = tmp.next.next
nxt.next = tmp.next.next
tmp.next.next = nxt
tmp = tmp.next.next
i += 1
return fake_head.next
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == '__main__':
s = Solution()
# Given linked list 1 -> 2 -> 3 -> 4 -> 5 -> 6 and K=2,
# You should return 2 -> 1 -> 4 -> 3 -> 6 -> 5
n = ListNode(1)
n.next = ListNode(2)
n.next.next = ListNode(3)
n.next.next.next = ListNode(4)
n.next.next.next.next = ListNode(5)
n.next.next.next.next.next = ListNode(6)
s.print_list(n)
#h = s.swapPairs(n, 2)
h = s.reverseList(n, 3)
s.print_list(h)
| true |
0e8330781cac465d3bae07379fa9d2435940d03e | Ekimkuznetsov/Lists_operations | /List_split.py | 309 | 4.25 | 4 | # LIsts operations
# For each line, split the line into a list of words using the split() method
fname = input("Enter file name: ")
fh = open(fname)
fst = list()
for line in fh:
x = line.split()
for word in x:
if word not in fst:
fst.append(word)
fst.sort()
print(fst) | true |
e6ecd5211b15b6cb201bdd2e716a7b4fec2db726 | markcurtis1970/education_etc | /timestable.py | 1,693 | 4.5 | 4 | # Simple example to show how to calculate a times table grid
# for a given times table for a given length.
#
# Note there's no input validation to check for valid numbers or
# data types etc, just to keep the example as simple. Plus I'm not
# a python developer :-)
# Ask user for multiplier and max range of times table
# the input statement asks for a value and loads it into the variable
# on the left
tt_num = input("Enter times table number: ") # this is the times table number you want
tt_len = input("Enter times table length: ") # this is the length of the above times table
# loop 1: we execute this loop every time up to the times table number.
# Note the range statement will execute up to 1 less than the maximum set,
# for more info see: https://docs.python.org/2/library/functions.html#range
# this is what makes each row
for tt_val in range(1,tt_num + 1):
# reset the results each time we execute this loop to the starting
# value of the row, note the str() changes the integer to a string type
# so we can do things like concatenation later
results = str(tt_val)
# loop 2: we execute this loop up to the value of the times table length
# this is what makes each column in a given row. Note we start the range
# at 2, this is because the intial value is already loaded into the string
# variable above when we reset it
for multiplier in range(2,tt_len + 1):
result = tt_val * multiplier # calculate the result
results = str(results) + "\t" + str(result) # concatenate the string, the "\t" is a tab character
# print the results out once all columns are calculated and before moving to the next row
print results
| true |
1a024d3e345afbcc0b8cfa354e14416401f9c565 | dogac00/Python-General | /generators.py | 1,253 | 4.46875 | 4 | def square_numbers(nums):
result = []
for i in nums:
result.append(i*i)
return result
my_nums = square_numbers([1,2,3,4,5])
print(my_nums) # will print the list
# to convert it to a generator
def square_numbers_generator(nums):
for i in nums:
yield i*i
my_nums_generator = square_numbers_generator([1,2,3,4,5])
print(my_nums_generator) # will print the generator object
print(next(my_nums_generator))
print(next(my_nums_generator))
print(next(my_nums_generator))
print(next(my_nums_generator))
print(next(my_nums_generator)) # do it manually by next
# can't do it one more time because it will give the error StopIteration
# since it has 5 elements
# another way is this
for num in my_nums_generator:
print(num)
# much more readable with generators
# another way is with the list comprehenstion
my_nums_list_comprehension = [x*x for x in [1,2,3,4,5]]
# you can create a generator as taking out brackets and putting paranthesis
my_nums_comprehension_generator = (x*x for x in [1,2,3,4,5])
print(my_nums_comprehension_generator) # will print the generator object
print(list(my_nums_comprehension_generator))
# you lose the advantages of performance and memory
# when you pass the generator to a list like above
| true |
f7eaadb3ee801b8011e2fddd03a055902f2da614 | sohanjs111/Python | /Week 3/For loop/Practice Quiz/question_2.py | 608 | 4.375 | 4 | # Question 2
# Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with
# the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all
# integers before it. For example, the factorial of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!)
# is equal to 1.
def factorial(n):
result = 1
for x in range(1, n):
result = result * x
return result
for n in range(0,10):
print(n, factorial(n+1))
| true |
7a22126b7d66730558314ad8295c087559ee4b41 | sohanjs111/Python | /Week 4/Graded Assessment/question_1.py | 1,463 | 4.5 | 4 | # Question 1
# The format_address function separates out parts of the address string into new strings: house_number and street_name,
# and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the
# street name which may contain numbers, but never by themselves, and could be several words long. For example,
# "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function.
def format_address(address_string):
# Declare variables
house_no = ''
street_name = ''
# Separate the address string into parts
address_words = address_string.split(" ")
# Traverse through the address parts
for word in address_words:
# Determine if the address part is the
# house number or part of the street name
if word.isdigit():
house_no = word
else:
street_name += word
street_name += " "
# Does anything else need to be done
# before returning the result?
# Return the formatted string
return "house number {} on street named {}".format(house_no, street_name)
print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"
print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"
print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"
| true |
6adef0926886b9f6406f056fb9faef6640068338 | sohanjs111/Python | /Week 4/Lists/Practice Quiz/question_6.py | 957 | 4.40625 | 4 | # Question 6
# The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the
# sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'),
# ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works
# as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that.
def guest_list(guests):
for i in guests:
g_name = i[0]
g_age = i[1]
g_job = i[2]
print("{} is {} years old and works as {}".format(g_name, g_age, g_job))
guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])
#Click Run to submit code
"""
Output should match:
Ken is 30 years old and works as Chef
Pat is 35 years old and works as Lawyer
Amanda is 25 years old and works as Engineer
"""
| true |
3918f8ff48585ae65b1949cc709a8da345d26b93 | sohanjs111/Python | /Week 4/Strings/Practice Quiz/question_2.py | 593 | 4.3125 | 4 | # Question 2
# Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y
# km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2km".
def convert_distance(miles):
km = miles * 1.6
result = "{} miles equals {:.1f} km".format(miles, km)
return result
print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km
| true |
69fd417b735877ae844880c2f8ed10f80d33413a | khayes25/recursive_card_sorter | /merge_sort.py | 1,634 | 4.125 | 4 | """
Merge Sort Algorithm
"""
#Class Header
class Merge_Sort :
def merge_sort(list, left, right) :
if(left < right) :
middle = (left + right) / 2
merge_sort(list, left, middle)
merge_sort(list, middle + 1, right)
merge(list, left, middle, right)
def sort(list) :
merge_sort(list, 0, len(list) - 1)
"""
Merges two partitions of an array together, in the correct order.
"""
def merge(list, left, middle, right) :
lower_counter = 0
upper_counter = 0
merge_counter = left
lower_size = middle - left + 1
upper_size = right - middle
temp_lower = []
temp_upper = []
for i in range(0, lower_size) :
temp_lower.insert(i, list[left + 1])
for i in range(0, upper_size) :
temp_upper.insert(i, list[middle + 1 + I])
while(lower_counter < lower_size and upper_counter < upper_size) :
if(temp_lower[lower_counter] <= temp_upper[upper_counter]) :
list[merge_counter] = temp_lower[lower_counter]
lower_counter += 1
else :
list[merge_counter] = temp_upper[upper_counter]
upper_counter += 1
merge_counter += 1
while(lower_counter < lower_size) :
list[merge_counter] = temp_lower[lower_counter]
lower_counter += 1
merge_counter += 1
while(upper_counter < upper_size) :
list[merge_counter] = temp_upper[upper_counter]
upper_counter += 1
merge_counter += 1
| true |
b16802cea3e32892e7953167eb4932457c6e41bb | mr-akashjain/Basic-Python-Stuff-For-Fun | /pigLatin.py | 2,301 | 4.125 | 4 | from time import sleep
sentence = input("Hi, They call me latin pig translator. Enter a sentence to have fun with me:")
sleep(4)
print("Thanks for the input!! Fasten your seatbelt as you are about to enter into my world")
sleep(3)
print("I know my world is small, but it is mine!")
sleep(2)
say_something = input("Are you having Fun or not? Type(F/NF)")
if say_something in "Ff":
print("You are great!")
sleep(1)
print("Now comes the translation")
sleep(1)
#real code
# split sentence into words
words=sentence.strip().lower().split()
new_words=[]
#check for each word'
for word in words:
#check if the word start with a vowel
if word[0] in "aeiou":
#add 'Yay' to the word and add the word to a new list
new_word = word +"Yay"
new_words.append(new_word)
else:
vowel_pos = 0
for letter in word:
if letter not in "aeiou":
vowel_pos = vowel_pos+1
else:
break
new_word = word[vowel_pos:]+word[:vowel_pos]+"Ay"
new_words.append(new_word)
new_sentence = " ".join(new_words)
print(new_sentence)
else:
print("You are rude!")
sleep(1)
print("It is my duty to serve. wait for another 2 seconds to get the translation")
sleep(1)
print("But don't get any ideas,coz I don't like you")
sleep(2)
#real code
# split sentence into words
words=sentence.strip().lower().split()
new_words=[]
#check for each word'
for word in words:
#check if the word start with a vowel
if word[0] in "aeiou":
#add 'Yay' to the word and add the word to a new list
new_word = word +"Yay"
new_words.append(new_word)
else:
vowel_pos = 0
for letter in word:
if letter not in "aeiou":
vowel_pos = vowel_pos+1
else:
break
new_word = word[vowel_pos:]+word[:vowel_pos]+"Ay"
new_words.append(new_word)
new_sentence = " ".join(new_words)
print(new_sentence)
| true |
2bc6e15c932be59832de9e40960dc14c4de17c4f | AidaQ27/python_katas_training | /loops/vowel_count.py | 777 | 4.21875 | 4 | """
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.
---
We are starting with exercises that require iteration through
the elements of a structure, so it will be good to dedicate
some time to learn how they work
https://www.learnpython.org/en/Loops
Link to codewars exercise
http://www.codewars.com/kata/vowel-count
"""
def get_count(input_str):
num_vowels = 0
# your code here
return num_vowels
# Test methods below
assert get_count("magic") == 2, "Vowel count is not correct"
assert get_count("abracadabra") == 5, "Vowel count is not correct"
assert get_count("let's get lost") == 3, "Vowel count is not correct"
| true |
42b2eac7097ededd9d87d2746afaeb5f8fc9b240 | Nalinswarup123/python | /class 6/bio.py | 658 | 4.125 | 4 | '''biologists use seq of letter ACTC to model a genome. A gene is a substring
of gnome that starts after triplet ATG and ends before triplet TAG , TAA and
TGA.
the length of Gene string is mul of 3 and Gene doesnot contain any of the triple
TAG , TAA and TGA.
wap to ask user to enter a genone and display all genes in genone.
if no gene is found in seq then display no gene found.'''
s=input('enter model')
for i in range(len(s)):
if(s[i:i+3]=="ATG"):
for j in range(i+3,len(s)):
if(s[j:j+3]!="TAG" or s[j:j+3]!="TAA" or s[j:j+3]!="TGA"):
print(s[i+3:j])
else:
print('no gene found')
| true |
470cd5e72d7a9147a6d2fc4835040fb3446f1dcc | Nalinswarup123/python | /calss 1/distance between two points.py | 275 | 4.125 | 4 | #distance between two points
print('enter first point')
x,y=int(input()),int(input())
print('enter second point')
a,b=int(input()),int(input())
x=((x-a)**2+(y-b)**2)**0.5
print('distance between the given points=',x)
#print('{} is the required distance'.format(x))
| true |
6692daa627b01842e018d078fac7b64354d9a968 | smritta10/PythonTraining_Smritta | /Task3/Task3_all_answers.py | 1,906 | 4.125 | 4 | Task -3
#Question 1
diff_list= [10,'Smritta', 10.5,'1+2j', 20,'Singh', 113.0, '3+4j', 100, 'Python_learning']
print(diff_list)
-----------------------------------------------------
#Question 2
list1= [10,20,30,40,50]
s1= list1[ :5] #actual list
s2= list1[ : :-1] # lists items in reverse order
s3= list1[1:5:2] # lists item from 0 to 4 skipping 2nd item
print('Different slicing results: ', s1, ',', s2, ',', s3)
--------------------------------------------------
# Question 3
L1= [2,4,6,8]
total= sum(L1) # find the sum
print('Sum of all items in list is: ', total)
result= 1
for i in L1:
result= result *i
print('Multiplication output is:', result)
-------------------------------------------------------
#Question 4
myList= [2,4,6,8,10]
print('Max number from the list is:', max(myList))
print('Min number from the list is:', min(myList))
-----------------------------------------------------
#Question 5
x= filter(lambda x: x%2==0,[5,10,15,20,25,30])
print(list(x))
-------------------------------------------------
#Ex-6
l= []
for i in range(1,31):
l.append(i**2)
print('First 5 elements square is: ', l[:5])
print('Last 5 elements square is: ', l[-5:])
-------------------------------------------------
#Ex-7
list1= [2,4,6,8,10]
list2= [1,3,5]
list1.pop()
print('List after removing last item:', list1)
list1.extend(list2)
print('Final list after adding a list:', list1)
-------------------------------------------------
#Ex-8
d= {} # empty dictionary
dict1= {1:10, 2:20}
dict2= {3:30, 4:40}
d.update(dict1)
d.update(dict2)
print('Concatenated dictonary is:', d)
-------------------------------------------------
#Ex-9
num= int(input('Input a number:'))
dict= {}
for i in range(1,num+1):
dict[i]= i*i
print('My dictionary is:', dict)
--------------------------------------------------
#Ex-10
item = input('Enter a list of numbers: ')
list1= item.split(',')
print(list1)
| true |
c91f0044d88593f20382a5dd1122504d9fbf8c1d | sindhupaluri/Python | /count_string_characters.py | 425 | 4.34375 | 4 | # Please write a program which counts and returns the numbers of each character in a string input.
# count_characters( "abcdegabc" )
# { 'a':2, 'c':2, 'b':2, 'e':1, 'd':1, 'g':1 }
def count_characters(string):
char_count = {}
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
count_characters("abcdegabc")
| true |
05b0deda5e25686a6082b289b46594a1b57e7ea3 | RAmruthaVignesh/PythonHacks | /Foundation/example_*args_**kwargs.py | 845 | 4.53125 | 5 | #When the number of arguments is unknown while defining the functions *args and **kwargs are used
import numpy as np
def mean_of_numbers(*args):
'''This function takes any number of numerical inputs and returns the mean'''
args = np.array(args)
mean = np.mean(args)
return mean
print "The mean of the numbers :" , mean_of_numbers(2,3,4.1,5,8)
def string_concat(*args,**kwargs):
'''This function takes any number of arguments and keyword arguments.
Converts into string and concatenates them'''
string_input_args= [str(i) for i in args]
args_out = ''.join(string_input_args)
input_kwargs = [kwargs[j] for j in kwargs]
kwargs_out = ''.join(input_kwargs)
return args_out+kwargs_out
string_out= string_concat(1,2, a="Hi" , b= "howdy?" )
print "The concatenated string output are " , string_out
| true |
f24bcde3c27bf62a63df4e2e2d6d76925ac51352 | RAmruthaVignesh/PythonHacks | /Foundation/example_list_comprehension.py | 651 | 4.71875 | 5 | #Example 1 : To make a list of letters in the string
print "This example makes a list of letters in a string"
print [letter for letter in "hello , _world!"]
#Example 2: Add an exclamation point to every letter
print "\nExample 2: Add an exclamation point to every letter"
print [letter+"!" for letter in "hello , world !"]
#Example 3 : To generate multiplication table of 9
print "\nExample 3: A multiplication table for the 9's"
print [num*9 for num in range(1,13)]
#Example 4 : To print letters if they are not o
print "\nExample 4: Make a list of letters in a string if they're not 'o'"
print [letter for letter in "hello_world" if letter!="o"] | true |
9095e434cabe1afd4d287c4db9885bbf0d7b4515 | RAmruthaVignesh/PythonHacks | /OOPS/class_inheritance_super()_polygons.py | 1,891 | 4.78125 | 5 | #This example explains the super method and inheritance concept
class polygons(object):
'''This class has functions that has the functionalities of a polygon'''
def __init__(self,number_of_sides):#constructor
self.n = number_of_sides
print "The total number of sides is" , self.n
def interior_angle(self):
'''This function calculates the interior angle of a polygon'''
return (180*(self.n-2))/self.n
def exterior_angle(self):
'''This function calculates the exterior angle of a polygon'''
return 360/self.n
def number_of_diagonals(self):
'''This function calculates the number of diagonals in a polygon'''
return ((self.n**2) - (3*self.n))/2
class rectangle(polygons):
'''This class inherits all the functionalities of a polygon'''
def __init__(self,length,breadth):
number_of_sides = 4
self.l = length
self.b = breadth
super(rectangle,self).__init__(number_of_sides)
def interior_angle(self):
'''This function calculates the interior angle of a rectangle'''
return super(rectangle,self).interior_angle()
def area(self):
'''This function calculates the area'''
return self.l*self.b
class square(rectangle):
'''This class inherits all the functionalities of rectangle class'''
def __init__(self,side):
self.side=side
super(square,self).__init__(self.side,self.side)
def interior_angle(self):
return super(square,self).interior_angle()
def area(self):
return super(square,self).area()
class rhombus(square):
pass
#Testcases
rect= rectangle(5,4)
print "The interior angle of the rectangle is" ,rect.interior_angle()
sq = square(5)
print "The interior angle of the square is" ,sq.interior_angle()
rh = rhombus(10)
print "The area of the rhombus is" ,rh.area()
| true |
7e06219cc161ddfb37e3f72d261c9c256ea20414 | RAmruthaVignesh/PythonHacks | /MiscPrograms/number_of_letters_in_word.py | 354 | 4.3125 | 4 | #get the word to be counted
word_to_count = 'hello_world!'
print ("the word is" , word_to_count)
# iniliatize the letter count
letter_count = 0
#loop through the word
for letter in word_to_count:
print("the letter", letter, "#number" , letter_count)
letter_count = letter_count+1
print ("there are", letter_count, " letters in", word_to_count) | true |
0fff4ced9ebbb6852543fb009386e49bee3c352a | AlanDTD/Programming-Statistics | /Week 2/Week 2 exercises - 2.py | 909 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 20:05:57 2021
@author: aland
"""
#Loops and input Processing
nums = tuple(input("Enter at least 5 numbers separated by commas!"))
print(len(nums))
print(nums)
sum_num = 0
count = 0
if type(nums) == tuple: #Checks if ithe value is a tuple
while len(nums) < 5: #Checks the tuples lengeth is at least 5
print("You do not have enough number")
nums = tuple(input("Please try again, at least 5")) #reruns the loop until the right number
else:
for i in range(len(nums)): #iterates and sums the numbers
if type(nums[i]) == int:
sum_num = sum_num + nums[i]
else:
count = count + 1
print("The total sum of the numbers are %d with and %d NaN" %(sum_num, count))
else:
print("This is not a tuple")
nums = tuple(input("Please use commas to seprate"))
| true |
ed04c33b0bd58feb0e53c7970ee6ec5de1511481 | mvessey/comp110-21f-workspace | /lessons/for_in.py | 382 | 4.46875 | 4 | """An example of for in syntax."""
names: list[str] = ["Madeline", "Emma", "Nia", "Ahmad"]
# example of iterating through names using a while loop
print("While output:")
i: int = 0
while i < len(names):
name: str = names[i]
print(name)
i += 1
print("for ... in output")
# the following for ... in loops is the same as the while loop
for name in names:
print(name) | true |
78f53c4a130daf34adc2ef48ec7e37be90c0a3b1 | klcysn/free_time | /climb_staircase.py | 452 | 4.3125 | 4 | # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
n = int(input("How many steps are there ? : "))
def steps(n):
return n if n <= 3 else (steps(n-1) + steps(n-2))
steps(n) | true |
94ebe7be385aa68e463c7cdc89bd1e257b9ecdbe | klcysn/free_time | /fizzbuzz.py | 799 | 4.71875 | 5 | # Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz".
# If the number is a multiple of 3 the output should be "Fizz".
# If the number given is a multiple of 5, the output should be "Buzz".
# If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz".
# If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below.
# The output should always be a string even if it is not a multiple of 3 or 5.
def fizzy() :
num = int(input("Please enter your number to see FizzBuzz : "))
print("Fizz") if num % 3 == 0 and num % 5 != 0 else print("Buzz")\
if num % 3 != 0 and num % 5 == 0 else print("FizzBuzz") if num % 3 == 0 and num % 5 == 0\
else print(num)
fizzy()
| true |
f82a0f9537ee9ec944bdf9e95ea691a5f06e1bf3 | Chetancv19/Python-code-Exp1-55 | /Lab2_5.py | 701 | 4.125 | 4 | #Python Program to Check Prime Number
#chetan velonde 3019155
a = int(input("Enter the number for checking whether it is prime or not:"))
if a > 1:
for x in range(2, a):
if a % x == 0:
print(str(a) + " is not a prime number.")
break
else:
print(str(a) + " is a prime number.")
#main princple - every number has it two factors, 1 and the number itself-->then divisibilty test
#we initialize the code by checking the value of the input integer... then use range() for checking the divisibility of that
#input number
#if all the test cases are passed for divisibility check from 2 to the input integer, the number is declared as not a prime number | true |
56987b36b796816bbf61315b11be60fc6bed2aee | ljkhpiou/test_2 | /ee202/draw.py | 642 | 4.1875 | 4 | import turtle
myPen = turtle.Turtle()
myPen.shape("arrow")
myPen.color("red")
#myPen.delay(5) #Set the speed of the turtle
#A Procedue to draw any regular polygon with 3 or more sides.
def drawPolygon(numberOfsides):
exteriorAngle=360/numberOfsides
length=2400/numberOfsides
myPen.penup()
myPen.goto(-length/2,-length/2)
myPen.pendown()
for i in range(0,numberOfsides):
myPen.forward(length)
myPen.left(exteriorAngle)
# Collect events until released
#with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener_m:
# listener_m.join()
drawPolygon(6)
| true |
08435281ef189434c121be0f66540830b0e2f006 | NectariosK/email-sender | /email_sender.py | 2,438 | 4.375 | 4 | #This piece of code enables one to send emails with python
#Useful links below
'''
https://www.geeksforgeeks.org/simple-mail-transfer-protocol-smtp/
https://docs.python.org/3/library/email.html#module-email
https://docs.python.org/3/library/email.examples.html
'''
'''
import smtplib #simple mail transfer protocol (smtp)
from email.message import EmailMessage
email = EmailMessage()
email['from'] = 'NAME' #Name of sender
email['to'] = 'EMAIL ADDRESS' #Email address the email will be sent to
email['subject'] = 'WINNER'
email.set_content('I am a Python Master.') #Well, atleast I think I am :)
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:#hosts port value differ/check your email server
smtp.ehlo() #protocol of the method ##here I connected to the server
smtp.starttls()#to connect securely to the server ##connected to the server
smtp.login('EMAIL ADDRESS', 'PASSWORD')#login to your account
smtp.send_message(email)#send the email
print('All good boss!')
'''
#MORE ON SENDING EMAILS
'''
This is an improvement of the program above.
Instead of just sending a generic email, I want to customize it to each individual
Imagine having a database of users with their email addresses and first names.
Ideally I woudld be able to customize the email to each specific person.
And that can be done by using an html based email.
So I can send text emmails(that just have text) or even something more dynamic like html
'''
import smtplib
from email.message import EmailMessage
from string import Template #making good use of the string.template class
from pathlib import Path #this is similar to the os.path and it enables me to access the 'index.html' file(attached to project)
html = Template(Path('index.html').read_text()) #read_text() to read the 'index.html' path
email = EmailMessage()
email['from'] = 'NAME'
email['to'] = 'EMAIL ADDRESS'
email['subject'] = 'You won 1,000,000 dollars!'#Familiar spam email subject?
email.set_content(html.substitute({'name': 'TinTin'}), 'html')
'''
Assigned 'name' which is in the 'index.html' file as TinTin-could me anything really.
The second parameter 'hmtl' confirms that this is in hmtl
'''
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login('EMAIL ADDRESS', 'PASSWORD')
smtp.send_message(email)
print('All good boss!') | true |
8d64c60833a9b781e2b4e1243e1e987f08030c41 | dwbelliston/python_structures | /generators/example.py | 683 | 4.4375 | 4 | # Remember, an Iterable is just an object capable of returning its members one at a time.
# generators are used to generate a series of values
# yield is like the return of generator functions
# The only other thing yield does is save the "state" of a generator function
# A generator is just a special type of iterator
# Like iterators, we can get the next value from a generator using next()
# for gets values by calling next() implicitly
def simple():
yield 1
yield 2
yield 3
og = simple()
print(og)
print(next(og))
print(next(og))
print(next(og))
def get_primes(number):
while True:
if is_prime(number):
yield number
number += 1
| true |
24d69d7df270af8673070ef7079cbcd3254d9bd7 | valakkapeddi/enough_python | /comprehensions_and_generators.py | 1,353 | 4.6875 | 5 | # Comprehension syntax is a readable way of applying transforms to collection - i.e., creating new collections
# that are modified versions of the original. This doesn't change the original collection.
# For instance, given an original list like the below that contains both ints and strings:
a_list = [1, 2, 3, 4, 'a', 'b', 'c']
print(a_list)
# You can use a comprehension to filter the list, pulling out only the integers.
ints_list = [element for element in a_list if isinstance(element, int)]
print(ints_list)
# Comprehensions work by running the code inside the []'s for each element in the list - this code gets
# executed immediately when the comprehension is declared. For large collections, this may not be what you want.
# Generators are sort of like comprehensions in that they can transform collections into other collections, but
# unlike comprehensions, the generator expression gets executed only when you access its elements with an iterator
# or a for-loop.
ints_comprehension = (element for element in a_list if isinstance(element, int))
print(ints_comprehension) # note that it doens't print a list - just the comprehension object.
# You can access the elements of a comprehension using an iterator, or a for loop.
print(next(ints_comprehension))
print(next(ints_comprehension))
for each in ints_comprehension:
print(each)
| true |
861db59c044985dc0b8e4d71dbff92d480b40ef1 | Jones-Nick-93/Class-Work | /Binary Search Python.py | 1,284 | 4.25 | 4 | #Nick Jones
#DSC 430 Assignment 7 Time Complexity/Binary Search
#I have not given or received any unauthorized assistance on this assignment
#YouTube Link
import random
'''function to do a binary search to see if 2 #s from a given list sum to n'''
def binary_search(array, to_search, left, right):
# terminating condition
if right < left:
return -1
# compute mid
mid = (left+right)//2
# element found
if array[mid] == to_search:
return mid
# current element is greater than element to search
elif array[mid] > to_search:
# move left
return binary_search(array, to_search, left, mid-1)
# current element is less than element to search
else:
# move right
return binary_search(array, to_search, mid + 1, right)
# ask user for i
i = int(input("Enter i: "))
# ask user for n
n = int(input("Enter n: "))
# generate a random list of i items
numbers = []
for j in range(i):
numbers.append(random.randint(0, 100))
# for every element in numbers
for number in numbers:
# if there is a element in list which is n-number
if binary_search(numbers, n-number, 0, len(numbers)) != -1:
print("Found:", number, n-number)
exit(0)
print("Not found") | true |
e41b72f54d45718b0680fbbb7f61a3d0761f527f | Ameen-Samad/number_guesser | /number_ guesser.py | 1,426 | 4.15625 | 4 | import random
while True:
secret_number = random.randrange(1, 10, 1)
limit = 3
tries = 0
has_guessed_correctly = False
while not has_guessed_correctly:
user_guess = int(input("Guess a number: "))
print(f"You have guessed {user_guess}")
limit = limit - 1
tries = tries + 1
print(f"You have {limit} more tries left")
difference = secret_number - user_guess
difference = abs(difference)
print(f"This is your {tries} attempt")
if difference == 0:
print("You have guessed correctly!")
has_guessed_correctly = True
exit()
else:
if limit == 0:
print("Game over")
print("Do you want to try again?")
to_continue = input("yes/no ")
if to_continue.strip() == "yes":
to_continue = True
else:
to_continue = False
if not to_continue:
exit()
else:
has_guessed_correctly = True
if difference <= 2:
print("You are very close!")
elif difference <= 5:
print("Ypu are halfway there!")
else:
print("You are more than halfway there!")
print("You have guessed incorrectly, try again!")
print("\n")
| true |
307e85576dc78d29ecf9077c70776c3498e1a60c | LizaPersonal/personal_exercises | /Programiz/sumOfNaturalNumbers.py | 684 | 4.3125 | 4 | # Python program to find the sum of natural numbers up to n where n is provided by user
def loop_2_find_sum():
num = int(input("Enter a number: "))
if num < 0:
num = int(input("Enter a positive number"))
else:
sum = 0
# use while loop to iterate until zero
while num > 0:
sum += num
num -= 1
print("The sum is", sum)
def equation_2_find_sum():
num = int(input("Enter a number: "))
if num < 0:
num = int(input("Enter a positive number"))
else:
sum = num * (num + 1) / 2
print("The sum is", sum)
if __name__ == '__main__':
loop_2_find_sum()
equation_2_find_sum() | true |
35ab0ae28ae798f5fd4317432d082e164b5815ef | zenthiccc/CS5-ELECTIVE | /coding-activities/2ndQ/2.5-recursive-binary-search.py | 1,311 | 4.15625 | 4 | # needle - the item to search for in the collection
# haystack - the collection of items
# NOTE: assume the haystack is ALWAYS sorted, no need to sort it yourself
# the binary search function to be exposed publicly
# returns the index if needle is found, returns None if not found
def binary_search(needle, haystack):
if len(haystack) == 0:
return None;
else:
return _binary_search_rec(needle, haystack, 0, len(haystack) - 1)
# the recursive binary search function (not public)
# returns the index if needle is found, returns None if not found
def _binary_search_rec(needle, haystack, start_index, end_index):
# IMPLEMENT!
if start_index > end_index:
return None
else:
mid_index = (start_index + end_index) // 2
if needle == haystack[mid_index]:
return mid_index
elif needle < haystack[mid_index]:
return _binary_search_rec(needle, haystack, start_index, mid_index-1)
else:
return _binary_search_rec(needle, haystack, mid_index+1, end_index)
# SAMPLE TESTS:
print(binary_search(2, [])) # None
print(binary_search(2, [2, 4, 6])) # 0
print(binary_search(2, [1, 2, 3])) # 1
print(binary_search(10, [4, 6, 10, 7, 9])) # 2
print(binary_search(4, [4, 6, 10, 7, 9])) # 0
print(binary_search(8, [3, 4, 6, 7])) # None
| true |
e3b267c428b62ae5e579a8d9b2446a85443ba889 | hyerynn0521/CodePath-SE101 | /Week 1/fizzbuzz.py | 683 | 4.46875 | 4 | #
# Complete the 'FizzBuzz' function below.
#
# This function takes in integer n as a parameter
# and prints out its value, fizz if n is divisible
# by 3, buzz if n divisible by 5, and fizzbuzz
# if n is divisible by 3 and 5.
#
"""
Given an input, print all numbers up to and including that input, unless they are divisible by 3, then print
"fizz" instead, or if they are divisible by 5, print "buzz". If the number is divisible by both, print "fizzbuzz".
"""
def FizzBuzz(n):
# Write your code here
for i in range(1, n+1):
if i%3 == 0 and i%5 == 0:
print("fizzbuzz")
elif i%3 == 0:
print("fizz")
elif i%5 == 0:
print("buzz")
else:
print(i)
| true |
52673f2e5435fb7d724b5028a3f64c61398d3c47 | hyerynn0521/CodePath-SE101 | /Week 5/longest_word.py | 816 | 4.4375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'longestWord' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING_ARRAY words as parameter.
# This function will go through an array of strings,
# identify the largest word, and return that word.
#
'''
given array of strings (that could have multiple words) return the longest word.
'''
def longestWord(sentences):
# Write your code here
longest = ""
longest_length = 0
for strings in sentences:
words = strings.split(" ")
for word in words:
if len(word) > longest_length:
longest = word
longest_length = len(word)
return longest
if __name__ == '__main__':
| true |
48108b1d24bc92d1d52af57f50fed1f7e06b45a9 | brivalmar/Project_Euler | /Python/Euler1.py | 202 | 4.125 | 4 | total = 0
endRange = 1000
for x in range(0, endRange):
if x % 3 == 0 or x % 5 == 0:
total = total + x
print "The sum of numbers divisible by 3 and 5 that are less than 1000 is: %d " % total
| true |
96d1013baf191fdc17c8e134d7e68886803aa689 | Vagelis-Prokopiou/python-challenges | /codingbat.com/String-2/end_other.py | 719 | 4.125 | 4 | #!/usr/bin/python3
# @Author: Vagelis Prokopiou
# @Email: drz4007@gmail.com
# @Date: 2016-04-02 17:33:14
# @Last Modified time: 2016-04-02 17:55:41
# Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string.
# end_other('Hiabc', 'abc') → True
# end_other('AbC', 'HiaBc') → True
# end_other('abc', 'abXabc') → True
def end_other(a, b):
a = a.lower()
b = b.lower()
if a == b:
return True
if (a[(-len(b)):] == b) or (b[(-len(a)):] == a):
return True
else:
return False
print(end_other('xyz', '12xyz'))
| true |
dc0aaec53f5565f1396c8cb1907070f4b1f9527d | divyaprakashdp/DSA-with-Python | /merge_sort.py | 1,422 | 4.3125 | 4 | def merge_sort(listToSort):
"""
sorts a list in descending order
Returns a new sordted list
"""
if len(listToSort) <= 1:
return listToSort
leftHalf, rightHalf = split(listToSort)
left = merge_sort(leftHalf)
right = merge_sort(rightHalf)
return merge(left, right)
def split(listToSplit):
"""
Divide the unsorted list at midpoint into sublists
Return two sublists left and right
"""
mid = len(listToSplit) // 2
left = listToSplit[:mid]
right = listToSplit[mid:]
return left, right
def merge(leftList, rightList):
"""
Merges two lists(arrays), sorting them in process
:returns a new merged list
"""
l = []
i = 0
j = 0
while i < len(leftList) and j < len(rightList):
if leftList[i] < rightList[j]:
l.append(leftList[i])
i += 1
else:
l.append(rightList[j])
j += 1
while i < len(leftList):
l.append(leftList[i])
i += 1
while j < len(rightList):
l.append(rightList[j])
j += 1
return l
def verify_Sorted(listToTest):
n = len(listToTest)
if n == 0 or n == 1:
return True
else:
return listToTest[0] < listToTest[1] and verify_Sorted(listToTest[1:])
aList = [56, 23, 45, 98, 100, 112, 7, 21]
a = merge_sort(aList)
print(a)
print("Is the list sorted:- ", verify_Sorted(a))
| true |
27e6c78de9ae2f6ff0c91d470bbf175bd9b7e7cc | mashpolo/leetcode_ans | /700/leetcode706/ans.py | 1,235 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@desc:
@author: Luo.lu
@date: 2019-01-09
"""
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.key = []
self.value = []
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: void
"""
if key in self.key:
index = self.key.index(key)
self.value[index] = value
else:
self.key.append(key)
self.value.append(value)
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
if key not in self.key:
return -1
else:
return self.value[self.key.index(key)]
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: void
"""
if key in self.key:
self.value.pop(self.key.index(key))
self.key.remove(key)
| true |
36a29f204892487912c3e60c6766a68a3a23a7b5 | iQaiserAbbas/artificial-intelligence | /Lab-01/Lab-01.py | 921 | 4.125 | 4 | __author__ = "Qaiser Abbas"
__copyright__ = "Copyright 2020, Artificial Intelligence lab-01"
__email__ = "qaiserabbas889@yahoo.com"
# Python Program - Calculate Grade of Student
print("Please enter 'x' for exit.");
print("Enter marks obtained in 5 subjects: ");
subject1 = input();
if subject1 == 'x':
exit();
else:
subject1 = int(subject1);
subject2 = int(input());
subject3 = int(input());
subject4 = int(input());
subject5 = int(input());
sum = subject1 + subject2 + subject3 + subject4 + subject5;
average = sum/5;
if(average>=85 and average<=100):
print("Your Grade is A+");
elif(average>=80 and average<85):
print("Your Grade is A-");
elif(average>=75 and average<80):
print("Your Grade is B+");
elif(average>=71 and average<75):
print("Your Grade is B-");
elif(average>=51 and average<=60):
print("Your Grade is C+");
else:
print("Your Grade is F"); | true |
f2c41e4f2cbef4b9d331b423a27dd93e259b0329 | cardigansquare/codecademy | /learning_python/reverse.py | 221 | 4.1875 | 4 | #codeacademy create function the returns reversed string without using reversed or [::-1]
def reverse(text):
new_text = ""
for c in text:
new_text = c + new_text
return new_text
print reverse("abcd!") | true |
556e83e3f35ac103b07d064083e1288293ebc1f9 | roseORG/GirlsWhoCode2017 | /GWC 2017/story.py | 1,154 | 4.25 | 4 | start = '''
Rihanna is in town for her concert. Help her get to her concert...
'''
print(start)
done = False
left= False
right= False
while not done:
print("She's walking out of the building. Should she take a left or right?")
print("Type 'left' to go left or 'right' to go right.")
user_input = input()
if user_input == "left":
print("You decided to go left and ran into the paprazzi.") # finished the story by writing what happens
done = True
left= True
elif user_input == "right":
print("You decided to go right and ran into fans.") # finished the story writing what happens
done = True
right= True
else:
print("Wrong Option")
done = False
done = False
while left:
print("paprazzi are here!")
print("Do you want to fight the paprazzi or run?")
user_input = input()
if user_input == "fight":
print("Let's get it!")
left = False
elif user_input == "run":
print("You broke your ankle")
left = False
else:
print("Wrong Option")
left= True
| true |
17dccb7a8621b306bbae0dd58f64c23e17c746c8 | shamramchandani/Code | /Python/chapter 3.py | 410 | 4.15625 | 4 | def collatz(num):
if num%2 == 0:
print(num / 2)
return (num / 2)
else:
print((num *3) +1)
return (num *3) +1
try:
number = int(input("Please enter a number"))
print(number)
if number <= 1:
print('Please input a number greater than 1')
else:
while number > 1:
number = collatz(number)
except (NameError, ValueError):
print('Error: Please Enter a Number') | true |
771aafb570437f9bdbd5bc60ea6b4106b22c2541 | hperry711/dev-challenge | /chapter2_exercises.py | 1,534 | 4.21875 | 4 | # Exercises for chapter 2:
# Name: Hunter Perry
# Exercise 2.1.
# zipcode = 02492 generates a SyntaxError message because "9" is not within the octal number system. When an integer is lead with a zero in Python it generates the Octal representation for that number. >>> zipcode = 02132 only contains numbers between 0 and 7 therefore generating 1114 as the octal representation.
# Exercise 2.2.
# Below is the statement in the Python interpreter.
>>> 5
5
>>> x = 5
>>> x + 1
6
# Below is the statement modified into a print statement.
>>> print 5
5
>>> x = 5
>>> print x + 1
6
# Exercise 2.3.
width = 17
height = 12.0
delimiter = '.'
# 1. width/2 - Value = 8, Type = Integer
# 2. width/2.0 - Value = 8.5, Type = Variable
# 3. height/3 - Value = 4, Type = Integer
# 4. 1 + 2 * 5 - Value = 11, Type = Integer
# 5. delimiter * 5 - Value = '.....', Type = String
# Exercise 2. 4.
# 1.
>>> r = 'radius'
>>> v = 'volume'
>>> v = 1.333 * pi * 5 ** 3
>>> v
523.4678759043992
# 2.
>>> p = 'cover price'
>>> d = 'discount'
>>> s1 = 'shipping cost'
>>> s2 = 'shipping cost for additional copy'
>>> n = 'number of copies'
>>> t = 'total'
>>> p =24.95
>>> p = 24.95
>>> d = .6
>>> s1 = 3.00
>>> s2 = .75
>>> n = 60
>>> t = ((n - 1) * (p * d + s2) + (p * d + s1))
>>> t = ((60 - 1) * (24.95 * .6 + .75) + (24.95 * .6 + 3.00))
>>> t
945.4499999999999
# 3.
>>> t = 'return time'
>>> t = (412.00 / 60.00) + (8.25 / 60.00 ) + (7.20 / 60.00) + (7.20 / 60.00) + (7.20 / 60.00)+ (8.25 / 60.00 )
>>> t
7.501666666666667
# t = 7 hours 30 minutes 10 seconds | true |
b98fb37acb9ed1b4cbf2d57f516cf650bc515332 | Airbomb707/StructuredProgramming2A | /UNIT1/Evaluacion/eval02.py | 304 | 4.15625 | 4 | #Evaluation - Question 7
#Empty array
#A length variable could be added for flexible user inputs
lst=[]
#Storing Values
for n in range(3):
print("Enter value number ", n+1)
num=int(input("> "))
lst.append(num)
#Built-in Max() Function in Python
print("The largest number was: ", max(lst))
| true |
d9fad0b9f0dda940f073f6f461fd01c145eb5ba1 | ZammadGill/python-practice-tasks | /task8.py | 319 | 4.21875 | 4 | """ Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers """
def squareOddNumber(numbers_list):
odd_numbers_square = [n * n for n in numbers_list if n % 2 != 0]
print(odd_numbers_square)
numbers = [1,2,3,4,5,6,7,8,9]
squareOddNumber(numbers)
| true |
cb611e5efb7fe55ca6e79a43a2eccfffd86b4834 | Hrishikeshbele/Competitive-Programming_Python | /minimum swaps 2.py | 1,891 | 4.34375 | 4 | '''
You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements.
You need to find the minimum number of swaps required to sort the array in ascending order.
Sample Input 0
4
4 3 1 2
Sample Output 0
3
Explanation 0
Given array
After swapping we get
After swapping we get
After swapping we get
So, we need a minimum of swaps to sort the array in ascending order.
Explaination:
we will create 2 dictonaries. 1 whose keys will be index and values will be current elm at that index and 2nd will have elm values as key and its current position as value.
now we will loop through keys of 1st dict and if we find that key of curr elm is not equal to its value which means elm at that pos is not sorted. Loop through dictionary a
and whenever key doesn't match value use dictionary to find the current index of correct value.
Example 2:3, means index 2 has value 3. But it should actually hold 2 as value. So we use b[2], which gives us the current index of 2 in dictionary a.
b[2] gives us 4. Which means 2 is currently in index 4. So we swap index 2 and index 4 in dictionary a and increase the number of swaps count.
Then we update dictionary b accordingly. That is if 2:3 is swapped with 3:4 in dictionary a, we will swap 3:2 with 4:3
'''
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
pos={}
val={}
ans=0
for i in range(len(arr)):
pos[i+1]=arr[i]
val[arr[i]]=i+1
for i in pos:
if pos[i]!=i:
pos[val[i]],val[pos[i]]= pos[i],val[i]
ans+=1
return ans
print(pos,val)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = list(map(int, input().rstrip().split()))
res = minimumSwaps(arr)
fptr.write(str(res) + '\n')
fptr.close()
| true |
2e3998204f8cf62aeb969ff28cd45b217b480bf0 | Hrishikeshbele/Competitive-Programming_Python | /merge2binarytree.py | 1,623 | 4.125 | 4 | '''
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node.
Otherwise, the NOT null node will be used as the node of new tree.
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
'''
'''
idea here is check the node of both the trees.If both trees are empty then we return empty. The root value will be t1.val + t2.val if node
in both tree are present.The left child will be the merge of t1.left and t2.left, except these trees are empty if the parent is empty
similar for right child.we store resultant tree into t1 to save space.
'''
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
#recurtion solution
if t1 and t2:
t1.val=t1.val+t2.val
t1.left=self.mergeTrees(t1.left,t2.left)
t1.right=self.mergeTrees(t1.right,t2.right)
return t1
else:
return t1 or t2
| true |
224e2c2e3835534e75d9816249aaf06625e70ada | Hrishikeshbele/Competitive-Programming_Python | /Letter Case Permutation.py | 1,326 | 4.1875 | 4 | '''
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. You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
approach:
let's see recursion tree for ex. a1b1. at each level we have choices based on which we get new strings.
a1b1
/ \ (choice on a, whether to take small or capital a)
a A
| | (choice on 1, note that we have only one choice on 1 i.e to take it )
a1 A1
/ \ / \ (choice on b)
a1b a1B A1b A1B
| | | | (choice on 1)
a1b1 a1B1 A1b1 A1B1 (our ans)
'''
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
def rec(s,ans,res):
if not s:
res.append(ans)
return
if s[0].isdigit():
rec(s[1:],ans+s[0],res)
elif s[0].isalpha():
rec(s[1:],ans+s[0].upper(),res)
rec(s[1:],ans+s[0],res)
return res
return rec(S.lower(),'',[])
| true |
afab2fe8f815cda591267691c0667a75a6182296 | Hrishikeshbele/Competitive-Programming_Python | /Leaf-Similar Trees.py | 767 | 4.25 | 4 | '''
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Input: root1 = [1,2], root2 = [2,2]
Output: true
approach : we find root nodes of both tree and compare them
'''
class Solution(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
def leafs(root):
if root:
if not root.left and not root.right:
return [root.val]
return leafs(root.left)+leafs(root.right)
else:
return []
return leafs(root1)==leafs(root2)
| true |
34b090968b06ee05bd9ebfb94547b9ba63e32b2b | Hrishikeshbele/Competitive-Programming_Python | /Invert the Binary Tree.py | 1,079 | 4.3125 | 4 | '''
Given a binary tree, invert the binary tree and return it.
Look at the example for more details.
Example :
Given binary tree
1
/ \
2 3
/ \ / \
4 5 6 7
invert and return
1
/ \
3 2
/ \ / \
7 6 5 4
'''
### we exchange the left and right child recursively
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return the root node in the tree
def invertTree(self, A):
if A is None:
return
#exchanging the childs
A.left,A.right=A.right ,A.left
self.invertTree(A.left)
self.invertTree(A.right)
return A
##Invert from leaf up
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
| true |
9af9bc53e43238029d5c791bbc1cd37d26920e7a | Hrishikeshbele/Competitive-Programming_Python | /Jewels and Stones.py | 1,027 | 4.125 | 4 | '''
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a
type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a
different type of stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
explaination: a is present 1 time and A is present 2 times in a S string
'''
solution1:
#brute force
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count=0
for i in J:
for j in S:
if i==j:
count+=1
return count
solution2:
#here we are summing up count of each elm of J in S , x.count(y) find count of y in x
def numJewelsInStones(self, J, S):
return sum(map(S.count, J))
| true |
23275fede27675ba37f35a8e9117af1395c3aa72 | nirajkvinit/pyprac | /recursiveBinarySearch.py | 472 | 4.15625 | 4 | # Binary search using recursion
def binarySearchRecursive(arr, low, high, value):
mid = low + int((high + low) / 2)
if arr[mid] == value:
return mid
elif arr[mid] < value:
return binarySearchRecursive(arr, mid + 1, high, value)
else:
return binarySearchRecursive(arr, low, mid - 1, value)
def binarySearch(arr, value):
return binarySearchRecursive(arr, 0, len(arr), value)
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8,9]
print(binarySearch(arr, 5)) | true |
a4c94ed077075a01ef12f176fbccff19ef24a0fc | nirajkvinit/pyprac | /100skills/dictgen.py | 386 | 4.3125 | 4 | '''
With a given number n, write a program to generate a dictionary that
contains (i, i*i) such that i is an number between 1 and n (both included). and
then the program should print the dictionary.
'''
def dictgen():
n = int(input("Enter a number: "))
d = dict()
for i in range(1, n+1):
d[i] = i**i
return d
if __name__ == "__main__":
print(dictgen())
| true |
606fe3d50350078588bbbf2a1f07e3c46b9c66e9 | Padma-1/100_days-coding | /Abundant_number.py | 332 | 4.1875 | 4 | #A number is abundant if sum of the proper factors of the number is greater than the given number eg:12-->1+2+3+4+6=16-->16>12 i.e., 12 is Abundant number
n=int(input())
sum=0
for i in range(1,n//2+1):
if n%i==0:
sum+=i
if sum>n:
print("Abundant number")
else:
print("not Abundant number")
| true |
b63c5ad4a138de403ef34297f1e05d4668c20339 | Padma-1/100_days-coding | /sastry_and_zukerman.py | 674 | 4.15625 | 4 | ###Sastry number:A number N is a Sastry Number if N concatenated with N + 1 gives a perfect square.eg:183
##from math import sqrt
##def is_sastry(n):
## m=n+1
## result=str(n)+str(m)
## result=int(result)
## if sqrt(result)==int(sqrt(result)):
## return True
## return False
##n=int(input())
##print(is_sastry(n))
#Zukarman numbers:Zuckerman Number is a number which is divisible by the product of its digits eg:115
def is_Zukerman(n):
mul=1
while n:
r=n%10
n=n//10
mul*=r
#print(mul)
if temp%mul==0:
return True
return False
n=int(input())
temp=n
print(is_Zukerman(n))
| true |
96af38fcaf676e67b50112b713af0b4d4fa08022 | aswanthkoleri/Competitive-codes | /Codeforces/Contests/Codeforces_Global_Round_3/Quicksort.py | 2,073 | 4.34375 | 4 | def partition(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
# print("Pivot 1 = ",pivot)
# What we are basically doing in the next few steps :
# 1. Whenever we find an element less than the pivot element we swap it with the element starting from the 0th index.
# 2. Point to note is that there can be unnecessary swapping as the 0th index element can itself be less than the pivot.
# 3. Finally when we arrange all the elements less than pivot in one side, the index right after that is the exact position for the pivot
# 4. Swap the pivot with that position.This way we can get the correct position of an element in the sorted array.
# 5. After that we will find the correct position for the pivot in the elements before and after the current pivot got.
for j in range(low , high):
# If current element is smaller than or
# equal to pivot
# print(arr[j],pivot,arr[j]+pivot)
if arr[j] < pivot:
# increment index of smaller element
i = i+1
arr[i],arr[j] = arr[j],arr[i]
# print("Pivot 2 = ",pivot,arr[high])
# if (arr[i+1]+arr[high])%2!=0:
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr,low,high):
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr,low,high)
# print("array=",arr,"i+1= ",pi)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
if __name__=="__main__":
# Write the main function here
n=int(input())
ar=list(map(int,input().split()))
# print(ar)
quickSort(ar,0,len(ar)-1)
# print(ar)
for i in ar:
print(i,end=" ")
# # Find the minimum number and the index
# minimum=min(ar)
| true |
44e4a22c1318e44f75e74af86558246f9acecd83 | lavish205/hackerrank | /time_conversion.py | 913 | 4.3125 | 4 | """PROBLEM STATEMENT
Given a time in AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.
Input Format
A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12.
Output Format
Convert and print the given time in 24-hour format, where 00≤hh≤23.
Sample Input
07:05:45PM
Sample Output
19:05:45
Explanation
7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45.
"""
time = raw_input()
h,m,s = time.split(':')
sec = s[:-2]
form = s[-2:]
if form =='AM':
if h == '12':
h = '00'
print h+':'+m+':'+sec
elif h == '12':
print h+':'+m+':'+sec
else:
h = str(int(h) + 12)
print h+':'+m+':'+sec | true |
255a630ce8ac960c214b6758e771233d36f0a6bc | Mo-Shakib/DSA | /Data-Structures/Array/right_rotate.py | 565 | 4.53125 | 5 | # Python program to right rotate a list by n
# Returns the rotated list
def rightRotate(lists, num):
output_list = []
# Will add values from n to the new list
for item in range(len(lists) - num, len(lists)):
output_list.append(lists[item])
# Will add the values before
# n to the end of new list
for item in range(0, len(lists) - num):
output_list.append(lists[item])
return output_list
# Driver Code
rotate_num = 3
list_1 = [1, 2, 3, 4, 5, 6]
print(rightRotate(list_1, rotate_num)) | true |
124bbb8ba9da101c72ffae44f897a2b8d71a4261 | G00398792/pforcs-problem-sheet | /bmi.py | 674 | 4.5625 | 5 | # bmi.py
# This program calculates your Body Mass Index (BMI).
# author: Barry Gardiner
#User is prompted to enter height and weight as a float
# (real number i.e. 1.0) number. The users weight is divided
# by the height in metres to the power of 2. The output
# is printed to the screen. The code "{:.2f}'.format(BMI)"
# specifies the format of the string. "2f" represents a floating
# point number to a precision of 2 decimal places.
height = float(input("Please Enter Your Height In Centimetres:"))
weight = float(input("Please Enter Your Weight in kilograms:"))
bmi = ((weight) / ((height/100))**2)#Formula: weight (kg) / [height (m)]2
print('BMI is {:.2f}.'.format(bmi)) | true |
f70c9a371369cb3ec1cd1f484c877704fa30b799 | mre9798/Python | /lab 9.1.py | 233 | 4.3125 | 4 | # lab 9.1
# Write a recursive function to find factorial of a number.
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
n=int(input("Enter the nnumber : "))
print("Factorial is ",fact(n)) | true |
65abd6e3940706315542de8ba291bdd93b2c1dab | bajram-a/Basic-Programing-Examples | /Conditionals/Exercise2.4.py | 505 | 4.25 | 4 | """Write a program that requires from the user to input coordinates x and y for the circle center
and the radius of that circle, then another set of coordinates for point A.
The program then calculates whether A is within the circle"""
from math import sqrt
Cir_x = float(input())
Cir_y = float(input())
r = float(input())
Ax = float(input())
Ay = float(input())
d = sqrt((Ax - Cir_x)**2 + (Ay - Cir_y)**2)
if d <= r:
print("A is within the circle")
else:
print("A isn't within the circle")
| true |
c5ff2f18e9728e2e015be69bf7389b11c54f55ba | fantods/python-design-patterns | /creational/builder.py | 1,258 | 4.4375 | 4 | # decouples creation of a complex object and its representation
# helpful for abstractions
# Pros:
# code is more maintainable
# object creation is less error-prone
# increases robustness of application
# Cons:
# verbose and requires a lot of code duplication
# Abstract Building
class Building(object):
def __init__(self):
self.build_floor()
self.build_size()
def build_floor(self):
raise NotImplementedError
def build_size(self):
raise NotImplementedError
def __repr__(self):
return 'Floor: {0.floor}, Size: {0.size}'.format(self)
# Concrete Buildings
class House(Building):
def build_floor(self):
self.floor = 'One'
def build_size(self):
self.size = 'Big'
class Flat(Building):
def build_floor(self):
self.floor = 'More than One'
def build_size(self):
self.size = 'Small'
def construct_building(cls):
building = cls()
building.build_floor()
building.build_size()
return building
house = House()
print(house)
# Floor: One, Size: Big
flat = Flat()
print(flat)
# Floor: More than One, Size: Small
# use external constructor
complex_house = construct_building(House)
print(complex_house)
# Floor: One, Size: Big | true |
77f8837147e6516faa44883791fc94cfe6f4e02b | BloodiestChapel/Personal-Projects | /Python/HelloWorld.py | 461 | 4.1875 | 4 | # This is a standard HelloWorld program.
# It is meant for practice.
import datetime
print('Hello World!')
print('What is your name?')
myName = input()
myNameLen = len(myName)
print('It is good to meet you, ' + myName)
print('Your name is ' + str(myNameLen) + ' characters long.')
print('What is your age?')
date = datetime.datetime.now()
myAge = input()
birthYear = int(date.year) - int(myAge) - 1
print('You were born, at least, in ' + str(birthYear)) | true |
7d6e84349dcb9c8ca76a35192e1bbbc5a6301142 | TheRockStarDBA/PythonClass01 | /program/python_0050_flow_control_nested_for_loop.py | 1,158 | 4.1875 | 4 | '''
Requirement:
There are 4 numbers: 1/2/3/4.
List out all 3 digits numbers using these 4 numbers.
You cannot use the same number twice in the 3 digits numbers.
'''
#Step 1) How to generate 1 digit number?
for i in range(1,5):
print(i, end=' ')
print('\n-------------------------------------')
#Step 2) How to generate 2 digits number?
# Nested loop: for/while loop inside another for/while loop.
for i in range(1,5):
for j in range(1, 5):
num = i * 10 + j
print(num, end=' ')
print('\n-------------------------------------')
#Step 3) How to generate 3 digits number?
# Nested loop: for/while loop inside another for/while loop, inside another for/while loop.
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
num = i * 100 + j * 10 + k
print(num, end=' ')
print('\n-------------------------------------')
#Step 4) It has another condition - the 3 numbers should be different.
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and i != k and j != k:
num = i * 100 + j * 10 + k
print(num, end=' ')
| true |
ad3979824471e652f79e74cf93ca18366b922436 | TheRockStarDBA/PythonClass01 | /program/python_0020_flow_control_if.py | 1,262 | 4.28125 | 4 | # Every python program we've seen so far is sequential exection.
# Code is executed strictly line after line, from top to bottom.
# Flow Control can help you skip over some lines of the code.
# if statement
today = input("What day is today?")
print('I get up at 7 am.')
print('I have my breakfast at 8 am.')
# IMPORTANCE !!! --------------------------------------------------
#
# if <boolean expression>:
# <statement>
# <statement>
# <statement>
#
# 1) ":" at the end of the if clause
# 2) All code under if section are indented 4 spaces.
# 3) Treat the 3 print statements as a 'block', because they are indented 4 spaces.
# The 'block' will be executed if today == 'Sunday' is True, otherwise, the 'block' won't get executed.
# -----------------------------------------------------------------
if today == 'Sunday': # today == 'Sunday' is a boolean expression. The boolean expression will always have a bool value - True / False
print("I attend Mr Fan's Python lesson at 9 am.")
print("I start working on my homework at 10:30 am.")
print("Homework is done at 11:30 am.")
print("I have my lunch at 12 pm.")
print("I play football with my friends at 5 pm.")
print("I have my dinner at 7 pm.")
print("I go to bed at 10 pm.")
| true |
e9fcd04639d97eef36e0891c5a4e8ad7513bd9c1 | TheRockStarDBA/PythonClass01 | /program/python_0048_practice_number_guessing_name.py | 1,575 | 4.40625 | 4 | '''
Requirement:
Build a Number guessing game, in which the user selects a range, for example: 1, 100.
And your program will generate some random number in the range, for example: 42.
And the user needs to guess the number.
If his answer is 50, then you need to tell him. “Try Again! You guessed too high”
If his answer is 20, then you need to tell him. “Try Again! You guessed too low”
When he finally guesses it, you need to tell him, how many times he guesses.
'''
'''
Solution:
Step 1) Get lower bound / upper bound from console
Step 2) Use random module to generate a number in the range as the answer
Step 3) Loop to ask the user "what's the correct answer?", and tell him/her higher or lower. If it is correct, exit.
'''
import random
# Step 1) Get lower bound / upper bound from console
lower = int(input("Enter positive lower bound: "))
upper = int(input("Enter positive upper bound: "))
# Step 2) Use random module to generate a number in the range as the answer
answer = random.randint(lower, upper)
count = 0
# Step 3) Loop to ask the user "what's the correct answer?", and tell him/her higher or lower. If it is correct, exit.
while True:
# Step 3.1) Get user guess
guess_result = int(input("Guess a number: "))
# Step 3.2) update the count
count += 1
# Step 3.3) check user guess
if answer == guess_result:
print(f"Congrats! You did it {count} try.")
break
elif answer > guess_result:
print("Try again! You guessed too low.")
else:
print("Try again! You guessed too high.") | true |
45d32d880019054cbcc22f71c5cf0b62bc605ecf | TheRockStarDBA/PythonClass01 | /program/python_0006_data_type_str.py | 613 | 4.15625 | 4 |
# str - 字符串
str1 = "Hello Python!"
str2 = 'I am str value, "surrounded" by single quote.'
str3 = "I am another str value, 'surrounded' by doulbe quotes."
print('variable str1 type is:', type(str1), 'str1=', str1)
print('variable str2 type is:', type(str2), 'str2=', str2)
print('variable str3 type is:', type(str3), 'str3=', str3)
# '+' sign joins str variables and get a new str
first_name = 'Tom'
last_name = 'Hanks'
full_name = first_name + " " + last_name
print("My favourite actor is", full_name)
# '*' sign duplicates str variable and get a new str
separate_line = "*" * 50
print(separate_line) | true |
caf77761eb946bc292c8f0c9802bc0bfd75160a4 | TheRockStarDBA/PythonClass01 | /program/python_0031_practice_input_if_elif_else_bmi_calculator.py | 1,132 | 4.53125 | 5 | # Requirement: get input from the user about height in meters and weight in kg.
# Calculate his bmi based on this formula:
# bmi = weight / (height ** 2)
# Print information based on user's bmi value
# bmi in (0, 16) : You are severely underweight
# bmi in [16, 18.5) : You are underweight
# bmi in [18.5, 25) : You are healthy
# bmi in [25, 30) : You are overweight
# bmi in [30, max) : You are severely overweight
height = float(input("Enter height in meters: "))
weight = float(input("Enter weight in kg: "))
bmi = weight / (height ** 2)
print(f"Your BMI is {bmi:.3f}")
# IMPORTANT !!! -------------------------------------------
# There are 2 ways to express bmi in a range [16, 18.5)
# [Solution 1] elif bmi >= 16 and bmi < 18.5:
# [Solution 2] elif 16 <= bmi < 18.5:
# ---------------------------------------------------------
if bmi < 16:
print("You are severely underweight")
elif 16 <= bmi < 18.5:
print("You are underweight")
elif bmi >= 18.5 and bmi < 25:
print("You are healthy")
elif 25 <= bmi < 30:
print("You are overweight")
else:
print("You are severely overweight")
| true |
e9a945d21935f5bb2e66d9323eeb5e26b5a97ec6 | TheRockStarDBA/PythonClass01 | /program/python_0039_library_random.py | 1,221 | 4.5625 | 5 |
# IMPORTANT !!! ----------------------------------
# Import the random module into your python file
# ------------------------------------------------
import random
# IMPORTANT !!! ----------------------------------
# random.randint(1, 10) is composed of 4 parts.
#
# 1) random : module name
# 2) . : separate module name and function name
# 3) randint : randint is a function
# it is under random module
# it will return a random number in range [1, 10]
# 4) (1, 10) : both 1 and 10 are parameters.
# What is parameter? Parameter is some value you pass to a function.
# ------------------------------------------------
# Util method / Util class - 工具类
i = 0
while i < 100:
random_int = random.randint(1, 100) # random.randint(1, 3) returns a random int in range[1,3]
print(random_int)
i += 1
i = 0
while i < 100:
random_number = random.random() # random.random() return a random float in range [0, 1)
print(random_number)
i += 1
i = 0
while i < 100:
random_number = random.uniform(1.2, 7.8) # random.uniform(1.2, 7.8) returns a random float in range[1.2, 7.8)
print(random_number)
i += 1 | true |
587e9f60c46a7db78e6e1f78885eb0b405f16239 | Alamin11/JavaScript-and-Python | /lecture02/sequeces.py | 652 | 4.15625 | 4 | from typing import OrderedDict, Sequence
# Mutable and Ordered
# Mutable means can be changed the Sequence
# Orderd means can not be changed the sequence because order matters
#string = oredered
name = "Farjana"
print(name[0])
print(name[6])
print(name)
#Lists=mutable and ordered
listName = ["Farjana", "Toma", "Nuntu", "Tuntun pakhi", "Jhunjhun pakhi"]
print(listName)
print(listName[0])
print(listName[1])
print(listName[2])
print(listName[3])
print(listName[4])
# Add a new name to the list:
listName.append("Ami")
print(listName[5])
# Delete a name from the list
listName.remove(listName[5])
print(listName)
# Sort the list
listName.sort()
print(listName)
| true |
71cdaa322abe4a1f266d5ce9704c11f3a759892c | alisaffak/GlobalAIHubPythonHomework | /proje.py | 2,720 | 4.1875 | 4 | student_name = "Ali".upper()
student_surname = "Şaffak".upper()
all_courses = ["Calculus","Lineer Algebra","Computer Science","DSP","Embeded Systems"]
selected_courses = set()
student_grades = {}
def select_courses():
j = 1
for i in all_courses:
print("{}-{}".format(j,i))
j +=1
print("6-No course selection")
print("Please select at least 3 courses. ")
selected = input("Enter the course's number:")
if selected == "1":
selected_courses.add(all_courses[0])
elif selected == "2":
selected_courses.add(all_courses[1])
elif selected == "3":
selected_courses.add(all_courses[2])
elif selected == "4":
selected_courses.add(all_courses[3])
elif selected == "5":
selected_courses.add(all_courses[4])
else:
print("ınvalid input")
def exam():
for i in selected_courses:
print(i)
select = input("choose the course you will take the exam: ")
if select in selected_courses:
midterm = input("Enter the midterm notes: ")
final = input("Enter the final notes: ")
project = input("Enter the project notes: ")
student_grades["midterm"] = int(midterm)
student_grades["final"] = int(final)
student_grades["project"] = int(project)
else:
print("Invalid input")
exam()
def calculate_notes():
grade = student_grades["midterm"]*0.3 + student_grades["final"]*0.5 + student_grades["project"]*0.2
if grade >= 90 :
print("AA")
elif 70 <= grade < 90 :
print("BB")
elif 50 <= grade < 70 :
print("BB")
elif 30 <= grade < 50 :
print("BB")
else:
print("FF")
print("You failed the lesson")
tries = 3
while (tries > 0):
name = input("Please enter your name: ").upper()
surname = input("Please enter your surname: ").upper()
if name == student_name and surname == student_surname:
print("WELCOME!")
while len(selected_courses) < 3 :
select_courses()
exam()
calculate_notes()
elif name != student_name and surname == student_surname:
tries -= 1
print("Opps! You have last {} entries".format(tries))
elif name == student_name and surname != student_surname:
tries -= 1
print("Opps! You have last {} entries".format(tries))
elif name != student_name and surname != student_surname:
tries -= 1
print("Opps! You have last {} entries".format(tries))
else:
print("Please try again later!")
break
| true |
6a8f962aebd5ddd10742d907de30819d82ae5d1e | LaRenegaws/wiki_crawl | /lru_cache.py | 2,955 | 4.125 | 4 | import datetime
class Cache:
"""
Basic LRU cache that is made using a dictionary
The value stores a date field that is used to maintain the elements in the cache
Date field is used to compare expire an element in the cache
Persisted field is a boolean that determines whether it can be deleted
"""
def __init__(self, size):
self.cache_size_limit = size
self.__cache = {}
def update(self, key, value=None, persisted=False):
"""
if inputs are key and value then adds the key and value to the cache
if inputs are only key, then only updates the access date for the element in the cache
"""
if value == None:
if not self.exists(key):
raise LookupError("The element does not exist in the cache")
self.__cache[key]["date"] = datetime.datetime.utcnow()
else:
date = datetime.datetime.utcnow()
if self.size() == self.cache_size_limit:
self.delete_oldest_entry()
self.__cache[key] = { "date": date, "value": value, "persisted": persisted }
def delete_oldest_entry(self):
# Deletes the dictionary element that was the last element to be updated
oldest = datetime.datetime.utcnow()
oldest_key = None
for key in self.__cache:
if self.__cache[key]["date"] < oldest and not self.__cache[key]["persisted"]:
oldest = self.__cache[key]["date"]
oldest_key = key
del self.__cache[oldest_key]
def find(self, key):
# Returns the value that is associated with the key
# Otherwise returns False
if not self.exists(key):
# raise LookupError("The element does not exist in the cache")
return False
else:
return self.__cache[key]["value"]
def size(self):
return len(self.__cache)
def exists(self, key):
# Returns a boolean whether the key exists in the cache
return key in self.__cache
class WikiCache(Cache):
"""
For the purpose of the wiki_crawl,
the key represents the article title
and the value is the number of links until philosophy
There is a pattern of certain wiki links appearing frequently prior
to reaching Philosophy. As a result, I will initiallly seed the cache
with the most common links that I've noticed to improve performance.
The seeded entries would then not be expirable in the cache
"""
def __init__(self, size=100):
Cache.__init__(self, size)
self.seed_wiki_cache()
def seed_wiki_cache(self):
common_links = {
"Critical thinking - Wikipedia": 6,
"Polity - Wikipedia": 4,
"Geometry - Wikipedia": 4,
"Fact - Wikipedia": 5,
"Mathematics - Wikipedia": 3,
"Ontology - Wikipedia": 2,
"Premise - Wikipedia": 3,
"Logic - Wikipedia": 2,
"Quantity - Wikipedia": 2,
"Argument - Wikipedia": 1,
"Property (philosophy) - Wikipedia": 1,
"Psychology - Wikipedia": 12
}
for key in common_links:
self.update(key, common_links[key], True)
| true |
448aa1aead420c84febe08b1d5dcecff30b28d85 | canlasd/Python-Projects | /Assignment3.py | 450 | 4.1875 | 4 | wind=eval(input("Enter Wind Speed"))
if wind>=74 and wind <=95:
print ("This is a category 1 hurricane")
elif wind<=96 and wind <=110:
print ("This is a category 2 hurricane")
elif wind<=111 and wind <=130:
print ("This is a category 3 hurricane")
elif wind<=131 and wind <=155:
print ("This is a category 4 hurricane")
elif wind>=156:
print ("This is a category 5 hurricane")
| true |
1b25840045d4858f9eec3deeda08f2373376ee25 | osanseviero/Python-Notebook | /ex31.py | 626 | 4.375 | 4 | #Program 31. Using while loops
def create_list(size, increment):
"""Creates a list and prints it"""
i = 0
numbers = []
while i < size:
print "New run! "
print "At the top i is %d" % i
numbers.append(i)
i = i + increment
print "Numbers now: ", numbers
print "At the bottom i is %d\n \n" % i
print "The numbers: "
for num in numbers:
print num
#Some testing
print "Test 1"
create_list(6, 1)
print "\n\n\nTest 2"
create_list(3, 1)
print "\n\n\nTest 3"
create_list(20,3)
#User interface
size = int(raw_input("Enter the top: "))
jump = int(raw_input("Enter the increment: "))
create_list(size, jump)
| true |
006a4070da536f4d42c65d93e0e5eb67db3b06b6 | mirgags/pear_shaped | /fruit_script.py | 1,896 | 4.21875 | 4 | # An interactive script that prompts the user to accept or reject fruit
# offerings and then asks if they want any other fruit that wasn't offered.
# Responses are stored in the fruitlist.txt file for later reading.
yeses = ['YES', 'OK', 'SURE', 'YEAH', 'OKAY', 'SI']
nos = ['NO', 'NOPE', 'NAH', 'UH-UH']
fruits = []
# imports list of fruits fro text file
with open('fruitlist.txt', 'r') as fruitlist:
for line in fruitlist:
fruits.append(line.rstrip())
# checks response input against list of approved responses.
def wants_fruit(answer, yeses, nos):
more_fruit = ""
for yes in yeses:
if answer.upper() == yes:
more_fruit = 'yes_fruit'
for no in nos:
if answer.upper() == no:
more_fruit = 'no_fruit'
if not (more_fruit == 'yes_fruit' or more_fruit =='no_fruit'):
more_fruit = wants_fruit(raw_input("I'm sorry I didn't catch that, do you want some other fruit? > "), yeses, nos)
return more_fruit
# adds requested fruit to list
def add_fruit(fruits):
fruits.append(raw_input("What is it? > "))
print "Oh ok, I'll bring some %s next time." % fruits[-1]
return fruits
# beginning of interactivw program
for fruit in fruits:
answer = raw_input("Would you like some %s? (yes/no) > " % fruit).upper()
for yes in yeses:
if answer == yes:
print "Here you go."
answer = raw_input("Is there any fruit you like that I didn't offer? > ")
more_fruit = ""
while more_fruit != 'no_fruit':
more_fruit = wants_fruit(answer, yeses, nos)
if more_fruit == 'yes_fruit':
fruits = add_fruit(fruits)
more_fruit = ""
answer = raw_input("Is there any fruit you like that I didn't offer? > ")
fruits.sort()
# opens and writes list to text file
writefile = open('fruitlist.txt', 'w')
for fruit in fruits:
writefile.write("%s\n" % fruit)
writefile.close()
| true |
1864a160dec53b2c9585bf05928daeafc23ff066 | andrewdaoust/project-euler | /problem004.py | 825 | 4.1875 | 4 | """
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def palindrome_check(n):
s = str(n)
length = len(s)
for i in range(int(len(s)/2)):
j = -i - 1
if s[i] != s[j]:
return False
return True
def run():
palindrome_numbers = []
for i in range(999, 99, -1):
palindrome = False
for j in range(i, 99, -1):
num = i * j
palindrome = palindrome_check(num)
# print(i, j, num, palindrome)
if palindrome:
palindrome_numbers.append(num)
return max(palindrome_numbers)
if __name__ == '__main__':
sol = run()
print(sol) | true |
c6ecdc710116054197d6d8f14f50f7af44700829 | andrewdaoust/project-euler | /problem001.py | 487 | 4.3125 | 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.
"""
import numpy as np
def run():
mult_3_5 = []
for i in range(1, 1000):
if i % 3 == 0:
mult_3_5.append(i)
elif i % 5 == 0:
mult_3_5.append(i)
sol = np.sum(mult_3_5)
return sol
if __name__ == '__main__':
sol = run()
print(sol)
| true |
688b44387560371c3262dd115f377c87f06eabb5 | nickmallare/Leet-Code-Practice | /35-search-insert-position.py | 851 | 4.1875 | 4 | """
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
head = 0
tail = len(nums) - 1
while(head <= tail):
index = (head + tail) //2
val = nums[index]
if val == target:
return index
#take the "middle" value and take the left or right side based on the middle number
if val > target:
tail = index - 1
else:
head = index + 1
return head
| true |
f911c2170e7dcb50d4d0eef0eebe550926af2c87 | Frank-LSY/Foundations-of-AI | /HW1/Puzzle8/bfs.py | 1,650 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 17:01:00 2019
vanilla breadth first search
- relies on Puzzle8.py module
@author: Milos Hauskrecht (milos)
"""
from Puzzle8 import *
#### ++++++++++++++++++++++++++++++++++++++++++++++++++++
#### breadth first search
def breadth_first_search(problem):
queue =deque([])
root=TreeNode(problem,problem.initial_state)
queue.append(root)
while len(queue)>0:
next=queue.popleft()
if next.goalp():
del(queue)
return next.path()
else:
new_nodes=next.generate_new_tree_nodes()
for new_node in new_nodes:
queue.append(new_node)
print('No solution')
return NULL
problem=Puzzle8_Problem(Example1)
output= breadth_first_search(problem)
print('Solution Example 1:')
print_path(output)
wait = input("PRESS ENTER TO CONTINUE.")
problem=Puzzle8_Problem(Example2)
output= breadth_first_search(problem)
print('Solution Example 2:')
print_path(output)
wait = input("PRESS ENTER TO CONTINUE.")
problem=Puzzle8_Problem(Example3)
output= breadth_first_search(problem)
print('Solution Example 3:')
print_path(output)
wait = input("PRESS ENTER TO CONTINUE.")
problem=Puzzle8_Problem(Example4)
output= breadth_first_search(problem)
print('Solution Example 4:')
print_path(output)
# Solution to Example 5 may take too long to calculate using vanilla bfs
# problem=Puzzle8_Problem(Example5)
# output= breadth_first_search(problem)
# print('Solution Example 5:')
# print_path(output)
| true |
4ad120e7f53162c10541c354acd1a30bc30cbeae | Nihila/python_programs | /begginer/positiveornegative.py | 797 | 4.25 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Administrator
#
# Created: 04/02/2018
# Copyright: (c) Administrator 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
pass
stringVar.count('x') - counts the number of occurrences of 'x' in stringVar
stringVar.find('x') - returns the position of character 'x'
stringVar.lower() - returns the stringVar in lowercase (this is temporary)
stringVar.upper() - returns the stringVar in uppercase(this is temporary)
stringVar.replace('a', 'b') - replaces all occurrences of a with b in the string
stringVar.strip() - removes leading/trailing white space from string | true |
327720b380ef7d2fa891f67c916ba51f91c74769 | pandey-ankur-au17/Python | /coding-challenges/week03/Assignment/AssignmentQ2while.py | 540 | 4.125 | 4 | def by_while_loop():
print("by using while loop ")
n = int(input("Enter the number of lines : "))
line = 1
while (line <= n):
print(" " * (n - line), end="")
digit = 1
while digit <= line:
print(digit, end="")
if line == digit:
rev_digit = line-1
while rev_digit >= 1:
print(rev_digit, end="")
rev_digit = rev_digit-1
digit = digit+1
print()
line = line+1
by_while_loop() | true |
158bdd6828bc4a720f962b5d329b5b8f8f5a045f | pandey-ankur-au17/Python | /coding-challenges/week04/day01/ccQ2.py | 366 | 4.46875 | 4 | # Write a function fibonacci(n) which returns the nth fibonacci number. This
# should be calcuated using the while loop. The default value of n should be 10.
def fibonacci(n=10):
n1=0
n2=1
count=0
while count<n:
print(n1)
nth=n1+n2
n1=n2
n2=nth
count=count+1
#n=int(input("Enter the numbers:"))
fibonacci()
| true |
c830897d5aa2bd691af45ccb59f3bcaa22307d75 | pandey-ankur-au17/Python | /coding-challenges/week07/AssignmentQ1.py | 991 | 4.15625 | 4 | # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
# Note:
# Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
# In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.
# Example 1:
# Input: n = 00000000000000000000000000001011
# Output: 3
# Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
class Solution(object):
def hammingWeight(self, n):
count = 0
while(n):
count+=1;
n = n&(n-1);
return count
n=int(input("Binary only:"))
print(hammingWeight(1,n))
| true |
58bfff25bede8b43e9e236d83d9326a8f0b4b125 | pandey-ankur-au17/Python | /coding-challenges/week07/day04/ccQ3.py | 591 | 4.25 | 4 | # Given an array with NO Duplicates . Write a program to find PEAK
# ELEMENT
# Return value corresponding to the element of the peak element.
# Example :
# Input : - arr = [2,5,3,7,9,13,8]
# Output : - 5 or 13 (anyone)
# HINT : - Peak element is the element which is greater than both
# neighhbours.
def Peak_value(arr):
s=arr.sort()
for i in range(len(arr)):
if arr[-1]>0:
print(arr[-1])
return arr[-1]
elif arr[i] >arr [i-1] and arr[i] >arr[i+1]:
print(arr[i])
return arr[i]
arr = [2,5,3,7,9,13,8]
Peak_value(arr) | true |
632564d4d1d0ed5f9c4cc1a8d9a36b67ab263810 | alishalabi/binary-search-tree | /binary_search_tree.py | 2,888 | 4.25 | 4 | """
Step 1: Build a binary search tree, with add, remove and in methods.
Step 2: Perform DFS's and BFS
"""
class BinaryTreeNode:
def __init__(self, data, left_child=None, right_child=None):
self.data = data
self.left_child = left_child
self.right_child = right_child
self.is_leaf = True
class BinarySearchTree:
def __init__(self, root=None):
self.root = root
def add(self, node, current_node=None):
# Base case: empty binary tree, add as root
if self.root == None:
self.root = node
print("Adding root")
return self
# else:
if current_node == None:
current_node = self.root
# Item already exists, return nothing
if node.data == current_node.data:
print("Node data already in Binary Search Tree")
return self
# Begin traversal at root node
# See if data belongs on left or right of current node
# Left:
# print(f"Node.data: {node.data}")
# print(f"Current_node.data: {current_node.data}")
if node.data < current_node.data:
# No left value, add node
if current_node.left_child == None:
current_node.left_child = node
# Left value exists, recursively call add
# with left child as current
else:
print(f"Current node's left child: {current_node.left_child.data}")
return self.add(node, current_node.left_child)
# Right:
elif node.data > current_node.data:
# No right value, add node
if current_node.right_child == None:
current_node.right_child = node
# Right value exists, recursively call add
# with right child as current
else:
print(f"Current node's right child: {current_node.right_child.data}")
return self.add(node, current_node.right_child)
nodeA = BinaryTreeNode(4)
nodeB = BinaryTreeNode(2)
# print(nodeB)
nodeC = BinaryTreeNode(5)
nodeD = BinaryTreeNode(1)
nodeE = BinaryTreeNode(3)
test_tree = BinarySearchTree()
test_tree.add(nodeA)
# print(f"Tree Root's data (should be 4): {test_tree.root.data}")
test_tree.add(nodeB)
# print(nodeA.left_child)
print(f"Root's left child (should be 2): {test_tree.root.left_child.data}")
# print(f"Left's left's data (should be None): {test_tree.root.left_child.left_child}")
test_tree.add(nodeC)
print(f"Root's right child (should be 5): {test_tree.root.right_child.data}")
print(f"Root's right's right (should be None): {test_tree.root.right_child.right_child}")
test_tree.add(nodeD)
test_tree.add(nodeE)
print(f"Root's left's left (should be 1): {test_tree.root.left_child.left_child.data}")
print(f"Root's left's right (should be 3): {test_tree.root.left_child.right_child.data}")
| true |
0bb123d4261f05d1c3b1654c10cff9300a408135 | pancakewaffles/Stuff-I-learnt | /Python Refresher/Python for Security Developers/Module 2 Apprentice Python/Activities/Apprentice_Final_Activity.py | 1,475 | 4.125 | 4 | import operator
saved_string = ''
def remove_letter(): #Remove a selected letter from a string
base_string = str(raw_input("Enter String: "));
letter = str(raw_input("Letter to remove: "));
i = len(base_string) -1 ;
while(i < len(base_string) and i >= 0):
if(base_string[i] == letter):
base_string = base_string[:i] + base_string[i+1::];
i -= 1;
print base_string;
def num_compare(): #Compare 2 numbers to determine the larger
a = int(raw_input("First number: "));
b = int(raw_input("Second number: "));
if(a>b):
return "%d is larger than %d." % (a,b);
elif(a<b):
return "%d is larger than %d." % (b,a);
else:
return "%d is equal to %d." %(a,b);
def print_string(): #Print the previously stored string
print saved_string;
return
def calculator(): #Basic Calculator (addition, subtraction, multiplication, division)
return
def accept_and_store(): #Accept and store a string
input_string = raw_input("Enter your string: ");
global saved_string;
saved_string = str(input_string);
return
def main(): #menu goes here
opt_list = [accept_and_store,
calculator,
print_string,
num_compare,
remove_letter];
while(True):
choice = int(raw_input(" Enter your choice : "));
opt_list[choice]();
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.