blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
012ab172576e4caa22fa0661ae304825a6e0f3a5 | Linh-T-Pham/Study-data-structures-and-algorithms- | /merge_ll.py | 2,625 | 4.15625 | 4 | """ Merge Linked Lists
Write a function that takes in the heads of two singly Ll that are
in sorted order, respectively. The function should merge the lists
in place(i.e, it should not create a brand new list and return the head
of the merged list; the merged list should be in sorted order)
Each linked list node has an integer value as well as a next node pointing
to the next node in the list or to None/Null if its the tail of the list.
You can assume that input linked lists will always have at least one node;
in other words, the heads will be never be None/Null.
"""
class Node:
def __init__(self, value):
self.value = value
self.next = None # last item
# if
# h1 > h2
# insert head_two.data before head_one.data
# pointer2 += 1
# else:
# h1 < h2:
# insert head_two.data after head_one.data
# head_one 1-2-6-7-8
# head_two 4-5-10-11-12
# out put 4
"""
"""
def merge_ll(head1, head2):
p1prev = None
p1 = head1
p2 = head2
while p1 is not None and p2 is not None:
if p1.value < p2.value:
# p1 = p1.next
p1prev = p1
p1 = p1.next
elif p1.value > p2.value:
if p1 is not None: # What happen when P1 is not None
p1prev.next = p2 # because p1pev is None so it does not make sense
# to assign p1prev = p2
p1prev = p2
p2 = p2.next
p1prev.next = p1
if p1 is None:
p1prev.next = p2
if head1.value < head2.value:
return head1
else:
return head2
head_one = Node(2)
head_one.next = Node(6)
head_one.next.next = Node(7)
head_one.next.next.next = Node(8)
head_two = Node(1)
head_two.next = Node(3)
head_two.next.next = Node(4)
head_two.next.next.next = Node(5)
head_two.next.next.next.next = Node(9)
head_two.next.next.next.next.next = Node(10)
# def merge_ll(head_one, head_two):
# point1 = head_one
# point2 = head_two
# point1_prev = None # previous node in the first linked list
# # 1 -> 6 ->7
# while point1 is not None and point2 is not None:
# if point1 < point2:
# point1_prev = point1 #none #6
# point1 = point1.next #1 #7
# else:
# # p2 comes before p1
# # so p1prev shoudl point to p2
# if point1_prev is not None:
# point1_prev = point2
# point_prev = point1 # before overwite p2
# point2 = point2.next
# point1_prev.next = point1
| true |
1cca158cb53fe6acf0e9c972240e43af6f30efe1 | Linh-T-Pham/Study-data-structures-and-algorithms- | /recursion2.py | 596 | 4.5 | 4 | """Write a function, reverseString(str), that takes in a string.
The function should return the string with it's characters in reverse order.
Solve this recursively!
Examples:
>>> reverseString("")
''
>>> reverseString("c")
'c'
>>> reverseString("internet")
'tenretni'
>>> reverseString("friends")
'sdneirf'
"""
def reverseString(Str):
if Str == "":
return Str
return reverseString(Str[1:]) + Str[0]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** Awesome!. GO GO GO!\n") | true |
7cb17368d61a76b8bda586fdb12c656cf9f4f37f | Timothy-py/Python-Challenges | /Factorial.py | 986 | 4.40625 | 4 | # A Python program to print the factorial of a number
# L1 - This line of code creates a variable named 'multiplier' which will
# be used to save the successive multiplications and it
# is initialized to 1 because it will be used to do the first multiplication
# L3 - Prompt the user to enter a number and save the number in a variable named 'number'
# L5 - The for loop is used to take each number in the range of number entered from 1 to number inclusive
# L6 - This line is the same as writing multiplier = multiplier * i, which implies that it takes the value of i and
# multiplied it with multiplier(which is initially 1) and in turn save the result in the multiplier variable
# L7 - The print() function is used to print the output with the help of the format() method, the curly braces
# {} are called placeholders
multiplier = 1
number = int(input('Enter the number here :'))
for i in range(1, number+1):
multiplier *= i
print('{}! is = {}'.format(number, multiplier)) | true |
ca3c224af2531b5777378548a13d2cb2e980bd8a | aloysiogl/CES-22_solutions | /Bimester1/Class1/ex6/exercise6.py | 1,316 | 4.40625 | 4 | #!/usr/bin/python3
import turtle
from time import sleep
# Question
# Use for loops to make a turtle draw these regular polygons (regular means all sides the same
# lengths, all angles the same):
# ◦ An equilateral triangle
# ◦ A square
# ◦ A hexagon (six sides)
# ◦ An octagon (eight sides)
# Function for drawing polygons
def drawPoly(nSides, turtle, side = 50):
# Turtle speed
turtle.speed(1)
# Turtle style
turtle.color("blue")
turtle.shape("turtle")
turtle.pencolor("black")
turtle.pensize(3)
# Using degrees units
turtle.degrees()
# Showing turtle
turtle.showturtle()
# Drawing the polygon
for i in range(0, nSides):
turtle.forward(side)
turtle.left(360/nSides)
# End animation
turtle.left(360)
# Hiding turtle
turtle.hideturtle()
# Getting screen
wn = turtle.Screen()
# Setting screen parameters
wn.bgcolor("lightblue")
wn.title("Tartaruga do Aloysio")
# Creating turtle
aloysio = turtle.Turtle()
# Drawing polygons
# Triangle
drawPoly(3, aloysio, 200)
sleep(3)
wn.reset()
# Square
drawPoly(4, aloysio, 180)
sleep(3)
wn.reset()
# Hexagon
drawPoly(6, aloysio, 100)
sleep(3)
wn.reset()
# Octagon
drawPoly(8, aloysio, 80)
sleep(3)
wn.reset()
# Keeping the window open
wn.mainloop()
| true |
7d7fe99aa3c635252af1a6d74b987fd0ec42c5ba | aloysiogl/CES-22_solutions | /Bimester1/Class6/decorators/decorators.py | 1,014 | 4.3125 | 4 | #!/usr/bin/python3
def round_area(func):
"""
This decorators rounds the area
:param func: area function
:return: the rounded area function
"""
def round_area_to_return(side):
"""
This function calculates the rounded area to 2 decimal digits
:param side: the side of the square
:return: the area
"""
return round(func(side), 2)
return round_area_to_return
@round_area
def get_square_area_with_decorator(side):
"""
This function calculates the area of a square using the round decorator
:param side: the side of the square
:return: the area
"""
return side*side
def get_square_area_without_decorator(side):
"""
This function calculates the area of a square
:param side: the side of the square
:return: the area
"""
return side*side
print("Result with decorator", get_square_area_with_decorator(5.1234))
print("Result without decorator", get_square_area_without_decorator(5.1234))
| true |
f34db4522943068e6e25c0984a6bc52859e92c3a | kbalog/uis-dat630-fall2016 | /practicum-1/tasks/task4.py | 1,090 | 4.5625 | 5 | # Finding k-nearest neighbors using Eucledian distance
# ====================================================
# Task
# ----
# - Generate n=100 random points in a two dimensional space. Let both
# the x and y attributes be int values between 1 and 100.
# - Display these points on a scatterplot.
# - Select one of these points randomly (i.e., pick a random index).
# - Find the k closest neighbors of the selected record (i.e., the k records
# that are most similar to it) using the Eucledian distance.
# The value of k is given (i.e., hard-coded).
# - Display the selected record and its k closest neighbors in a distinctive
# manner on the plot (e.g., using different colors).
# Solution
# --------
# We import the matplotlib submodule **pyplot**, to plot 2d graphics;
# following a widely used convention, we use the `plt` alias.
import matplotlib.pyplot as plt
# The number of random points we want.
n = 100
# The number of nearest neighbors.
k = 5
# Generate random points with x and y coordinates.
# TODO
# Find k-nearest neighbors.
# TODO
# Plot data.
# TODO
| true |
dac2cb25d763900c9b477c0ec27f813b500e2d89 | newbieeashish/datastructures_algo | /ds and algo/linkedlist,stack,queue/falttenLL.py | 2,556 | 4.34375 | 4 | '''Suppose you have a linked list where the value of each node
is a sorted linked list (i.e., it is a nested list).
Your task is to flatten this nested list—that is,
to combine all nested lists into a single (sorted) linked list.'''
#creating nodes and linked List
class Node:
def __init__(self,value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self,head):
self.head = head
def append(self,value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def merge(list1, list2):
merged = LinkedList(None)
if list1 is None:
return list2
if list2 is None:
return list1
list1_elt = list1.head
list2_elt = list2.head
while list1_elt is not None or list2_elt is not None:
if list1_elt is None:
merged.append(list2_elt)
list2_elt = list2_elt.next
elif list2_elt is None:
merged.append(list1_elt)
list1_elt = list1_elt.next
elif list1_elt.value <= list2_elt.value:
merged.append(list1_elt)
list1_elt = list1_elt.next
else:
merged.append(list2_elt)
list2_elt = list2_elt.next
return merged
class NestedLinkedList(LinkedList):
def flatten(self):
return self._flatten(self.head)
def _flatten(self,node):
if node.next is None:
return merge(node.value,None)
return merge(node.value,self._flatten(node.next))
linked_list = LinkedList(Node(1))
linked_list.append(3)
linked_list.append(5)
second_linked_list = LinkedList(Node(2))
second_linked_list.append(4)
merged = merge(linked_list, second_linked_list)
node = merged.head
while node is not None:
# This will print 1 2 3 4 5
print(node.value)
node = node.next
# Lets make sure it works with a None list
merged = merge(None, linked_list)
node = merged.head
while node is not None:
# This will print 1 2 3 4 5
print(node.value)
node = node.next
nested_linked_list = NestedLinkedList(Node(linked_list))
nested_linked_list.append(second_linked_list)
flattened = nested_linked_list.flatten()
node = flattened.head
while node is not None:
#This will print 1 2 3 4 5
print(node.value)
node = node.next
| true |
a6412b37f0cbd97d812d04f6edb564fb43c19b31 | newbieeashish/datastructures_algo | /ds and algo/Sorting_algos/counting_inversions.py | 2,026 | 4.15625 | 4 | '''Counting Inversions
The number of inversions in a disordered list is the number of pairs of elements that are inverted (out of order) in the list.
Here are some examples:
[0,1] has 0 inversions
[2,1] has 1 inversion (2,1)
[3, 1, 2, 4] has 2 inversions (3, 2), (3, 1)
[7, 5, 3, 1] has 6 inversions (7, 5), (3, 1), (5, 1), (7, 1), (5, 3), (7, 3)
The number of inversions can also be thought of in the following manner.
Given an array arr[0 ... n-1] of n distinct positive integers, for indices i and j, if i < j and arr[i] > arr[j] then the pair (i, j) is called an inversion of arr.
Problem statement
Write a function, count_inversions, that takes an array (or Python list) as input, and returns a count of the total number of inversions present in the input.'''
def count_inversions(items):
if len(items) <= 1:
return items,0
mid = len(items)//2
left = items[:mid]
right = items[mid:]
inversion_left = 0
inversion_right = 0
left, inversion_left = count_inversions(left)
right, inversion_right = count_inversions(right)
merged, inversions = merge(left,right)
return merged, inversion_left+inversion_right+inversions
def merge(left,right):
merged = []
inversions = 0
left_index = 0
right_index =0
while left_index < len(left) and right_index < len(right):
if left[left_index] > right[right_index]:
merged.append(right[right_index])
inversions +=1
right_index +=1
else:
merged.append(left[left_index])
left_index +=1
merged += left[left_index:]
merged += right[right_index:]
return merged,inversions
def test_function(test_case):
arr = test_case[0]
solution = test_case[1]
if count_inversions(arr)[1] == solution:
print("Pass")
else:
print("Fail")
arr = [2, 5, 1, 3, 4]
solution = 3
test_case = [arr, solution]
test_function(test_case)
| true |
d25ae8395ca06e243b00f3041c19c90c9402377a | mahasahyoun/python-for-everybody | /ch-2/gross-pay.py | 586 | 4.1875 | 4 | """
Write a program to prompt the user for hours and rate per hour using input to
compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program
(the pay should be 96.25). You should use input to read a string and float() to
convert the string to a number. Do not worry about error checking or bad user data.
"""
# Get inputs as strings
strHrs = input("Enter Hours:")
strRate = input("Enter Rate:")
# Convert inputs from string to number
floatHrs = float(strHrs)
floatRate= float(strRate)
# Compute gross pay
grossPay = floatHrs * floatRate
print("Pay:", grossPay)
| true |
6e161afe596049d1f120fbc2e8ad3f7cd41e411c | patrickForster/Sandbox | /password_entry.py | 388 | 4.25 | 4 | # password checker
MIN_LENGTH = 4
print("Please enter a valid password")
print("Your password must be at least", MIN_LENGTH, "characters long")
password = input("> ")
while len(password) < MIN_LENGTH:
print("Not enough characters!")
password = input("> ")
hidden_password = len(password)*'*'
print("Your {}-character password is valid: {}".format(len(password), hidden_password))
| true |
f7b19217b3ef9895ba0151e729e668e2f7e962cf | ericdong66/leetcode-50 | /python/48.search_insert_position.py | 1,101 | 4.1875 | 4 | # Given a sorted array 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 may assume no duplicates in the array.
#
# Here are few examples.
# [1,3,5,6], 5 -> 2
# [1,3,5,6], 2 -> 1
# [1,3,5,6], 7 -> 4
# [1,3,5,6], 0 -> 0
#
# Time: O(log(n))
# Space: O(1)
import argparse
class Solution(object):
@staticmethod
def search_insert(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
middle = left + (right - left) // 2
if nums[middle] >= target:
right = middle - 1
else:
left = middle + 1
return left
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--list', dest='list', required=True, nargs='+',
help='list of integer')
parser.add_argument('--target', dest='target', required=True,
help='target number')
args = parser.parse_args()
print(Solution.search_insert(args.list, args.target))
| true |
222c0630766643a98e24c8218c8bf148fd2c514d | h3llopy/web-dev-learning | /Learn Python the Hard Way/exercises/ex03.py | 812 | 4.53125 | 5 | print "I will now count my chickens:"
# These print out the answer after a string.
# The numbers are turned into floating point numbers with a decimal point and zero at the end for accuracy.
print "Hens", 25.0 + 30.0 / 6.0
print "Roosters", 100.0 - 25 * 3 % 4
print "Now I will count the eggs"
# This prints out the answer. It follows PEMDAS.
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
print "Is it true that 3 + 2 < 5 - 7?"
# #This prints out either True or False.
print 3.0 + 2.0 < 5.0 - 7.0
# Without the comma after the string, you will get a TypeError.
print "What is 3 + 2?", 3 + 2
print "What 5 - 7?", 5-7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
387d986223c06ade6346901334c275f70ae5b89f | xcobaltfury3000/baby-name-generator | /Baby_name_generator.py | 2,466 | 4.40625 | 4 | print ("Hello world")
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
#since we want a random selection we import random
import random
#from random library we want to utilize choice method
print(random.choice("pullaletterfromhere"))
print(random.choice(string.ascii_lowercase))
letter_input_1 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter')
letter_input_2 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter')
letter_input_3 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter')
letter_input_4 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter')
letter_input_5 = input('choose a letter: "v" for vowel "c" for consonant "l" for any other letter')
vowels = 'aeiouy'
consonant = 'bcdfghjklmnpqrstvwxz'
letter = string.ascii_lowercase
# copy conditional loop for the rest of the letter inputs
def generator():
if letter_input_1 == "v":
letter1 = random.choice(vowels)
elif letter_input_1 == "c":
letter1 = random.choice(consonant)
elif letter_input_1 == "l":
letter1 = random.choice(letter)
else:
letter1 = letter_input_1 # allows user to put a specific letter
if letter_input_2 == "v":
letter2 = random.choice(vowels)
elif letter_input_2 == "c":
letter2 = random.choice(consonant)
elif letter_input_2 == "l":
letter2 = random.choice(letter)
else:
letter2 = letter_input_2
if letter_input_3 == "v":
letter3 = random.choice(vowels)
elif letter_input_3 == "c":
letter3 = random.choice(consonant)
elif letter_input_3 == "l":
letter3 = random.choice(letter)
else:
letter3 = letter_input_3
if letter_input_4 == "v":
letter4 = random.choice(vowels)
elif letter_input_4 == "c":
letter4 = random.choice(consonant)
elif letter_input_4 == "l":
letter4 = random.choice(letter)
else:
letter4 = letter_input_4
if letter_input_5 == "v":
letter5 = random.choice(vowels)
elif letter_input_5 == "c":
letter5 = random.choice(consonant)
elif letter_input_5 == "l":
letter5 = random.choice(letter)
else:
letter5 = letter_input_5
name =letter1 + letter2+letter3+letter4+letter5
return(name)
for i in range (20): # to generate 20 different names
print(generator())
| true |
d5507e8d1e4565bf343205fcf933096abeead382 | AtharvaDahale/Python-BMI-Calculator | /Python BMI Calculator.py | 529 | 4.34375 | 4 | height = float(input("Enter your height in centimeters: "))
weight = float(input("Enter your weight in Kg: "))
height = height/100
BMI = weight/(height*height)
print("Your BMI is: ",BMI)
if (BMI > 0):
if(BMI<=16):
print("Your are severely underweight")
elif(BMI<=18.5):
print("you are underweight")
elif(BMI<=25):
print("You are healthy")
elif(BMI<=30):
print("You are overweight")
else:
print("You are severely overweight")
else:("enter valid details") | true |
82f5c6de2568a82c08a8e6f17427b6478277309b | khanmaster/eng88_python_control_flow | /control_flow.py | 1,721 | 4.3125 | 4 | # Control Flow with if, elif and else - loops
weather = "sunny"
if weather == "thinking": # if this condition is False execute the next line of code
print("Enjoy the weather ") # if true this line will get executed
if weather != "sunny":
print(" waiting for the sunshine")
if weather == "cloudy":
print(" still waiting for sunshine")
else:
print("Opps sorry something went wrong .. please try later") # If false this line will get executed
# add a condition to use elif when the condition is False
#Loops are used to ITERATE through data
#Lists, Dict, sets
list_data = [1, 2, 3, 4, 5]
print(list_data)
#First iteration
for list in list_data:
if list == 3:
print("I found 3")
if list == 2:
print(" now I found 2")
if list == 5:
print(" this is the last number and I found it as well - 5")
else:
print("Better Luck next time")
# Second Iteration
student_1 = {
"name": "Shahrukh",
"key": " value ",
"stream": "Cyber Security ", # string
"completed_lessons": 3, # int
"complete_lessons_names": ["variables", "operators", "data_collections"] # list
}
for data in student_1.values():
if data == " value ":
break
print(data)
#
#
#
#
#
# user_prompt = True
#
# while user_prompt:
# age = input("What is your age? ")
# if age.isdigit():
# user_prompt = False
# else:
# print("Please provide your answer in digits")
#
# print(f"Your age is {age}")
# While loops
user_prompt = True
while user_prompt:
age = input("Please enter your age? ")
if age.isdigit():
user_prompt = False
else:
print("Please provide your answer in digits")
print(f"Your age is {age}")
| true |
404d754f6ee9882e6eac12318f3847c3c46d2a9f | s-anusha/automatetheboringstuff | /Chapter 8/madLibs.py | 1,814 | 4.78125 | 5 | #! python3
# madLibs.py
'''
Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
The program would find these occurrences and prompt the user to replace them.
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
The following text file would then be created:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
'''
# Usage: python madLibs.py input_file [output_file]
import sys, re
if len(sys.argv) < 2:
print('Usage: python madLibs.py input_file [output_file]')
infile = open(sys.argv[1], 'r')
if len(sys.argv) > 2:
outfile = open(sys.argv[2], 'w')
else:
outfile = open('output.txt', 'w')
wordRegex = re.compile(r'\w+')
for line in infile:
for word in line.split():
source = wordRegex.search(word)
if source.group() == 'ADJECTIVE':
print('Enter an adjective:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'NOUN':
print('Enter a noun:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'ADVERB':
print('Enter an adverb:')
newWord = raw_input()
line = line.replace(word, newWord)
elif source.group() == 'VERB':
print('Enter an verb:')
newWord = raw_input()
line = line.replace(source.group(), newWord)
outfile.write(line)
infile.close()
outfile.close()
print('Output:')
outfile = open('output.txt', 'r')
print outfile.read()
outfile.close()
| true |
85d73fc37042cddd112601a2f4a8f013bf569685 | s-anusha/automatetheboringstuff | /Chapter 13/brute-forcePdfPasswordBreaker.py | 1,721 | 4.5 | 4 | #! python3
# brute-forcePdfPasswordBreaker
'''
Say you have an encrypted PDF that you have forgotten the password to, but you remember it was a single English word. Trying to guess your forgotten password is quite a boring task. Instead you can write a program that will decrypt the PDF by trying every possible English word until it finds one that works. This is called a brute-force password attack. Download the text file dictionary.txt from http://nostarch.com/automatestuff/. This dictionary file contains over 44,000 English words with one word per line.
Using the file-reading skills you learned in Chapter 8, create a list of word strings by reading this file. Then loop over each word in this list, passing it to the decrypt() method. If this method returns the integer 0, the password was wrong and your program should continue to the next password. If decrypt() returns 1, then your program should break out of the loop and print the hacked password. You should try both the uppercase and lower-case form of each word. (On my laptop, going through all 88,000 uppercase and lowercase words from the dictionary file takes a couple of minutes. This is why you shouldn’t use a simple English word for your passwords.)
'''
# Usage: python brute-forcePdfPasswordBreaker.py file
import sys
import PyPDF2
if len(sys.argv) < 3:
print('Usage: python brute-forcePdfPasswordBreaker.py pdf_file dictionary')
sys.exit()
pdf = sys.argv[1]
pdfReader = PyPDF2.PdfFileReader(open(pdf, 'rb'))
dictionary = sys.argv[2]
file = open(dictionary, 'r')
lines = file.readlines()
for line in lines:
password = line.strip()
if pdfReader.decrypt(password) is 1:
print('Password: ' + password)
break
| true |
e242498ad2180dd426cb2aa1b4cdbe86586e96d6 | s-anusha/automatetheboringstuff | /Chapter 6/tablePrinter.py | 1,784 | 4.71875 | 5 | #! python3
# tablePrinter.py
'''
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
Your printTable() function would print the following:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
Hint: Your code will first have to find the longest string in each of the inner lists so that the whole column can be wide enough to fit all the strings. You can store the maximum width of each column as a list of integers. The printTable() function can begin with colWidths = [0] * len(tableData), which will create a list containing the same number of 0 values as the number of inner lists in tableData. That way, colWidths[0] can store the width of the longest string in tableData[0], colWidths[1] can store the width of the longest string in tableData[1], and so on. You can then find the largest value in the colWidths list to find out what integer width to pass to the rjust() string method.
'''
# Usage: python tablePrinter.py
def printTable(data):
colWidths = [0] * len(data)
for i in range(len(data)):
colWidths[i] = len(max(data[i], key=len))
amount = int(max(colWidths))
for i in range(len(data[0])):
for j in range(len(data)):
print(data[j][i].rjust(amount), end="")
print('\n')
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)
| true |
8bae9a502d852cc6497e804361ba331e80c0b82c | rafiulalam2112/Age-ganaretor | /age_generator.py | 530 | 4.34375 | 4 | print('Hello! I am Rafi Robin. This is my python project.')
print('This tool genarate your age :)')
now_year=2021
birth_year=int(input('Inter your birth year :')) #When a user input a number the value save as string. To make the input as number use int() .
age=(now_year-birth_year)
print(f'You are {age} years old :)')
if age<13:
print('You are a kid :)')
if 13<age<16:
print('You are a teen')
if age==16:
print('You and I are the same age')
if 16<age<18:
print('You are a teen')
if age>18:
print('You are an adult') | true |
5327adf41dc51315c97e8b473b5709acc6efa7c0 | elacuesta/euler | /solutions/0004.py | 620 | 4.28125 | 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 is_palindrome(n):
return list(str(n)) == list(reversed(str(n)))
def palindrome(factor_length=2):
a = 10**factor_length - 1
b = 10**factor_length - 1
while True:
p = a * b
if is_palindrome(p):
return p, a, b
a -= 1
p = a * b
if is_palindrome(p):
return p, a, b
if __name__ == '__main__':
print(palindrome(3))
| true |
0f804f75088a1504d0365012cd9ab5e2ec4b16b3 | jsonw99/Learning-Py-Beginner | /Lec04(ListAndTuple).py | 1,482 | 4.40625 | 4 | # list ################################################################
classmates = ['Micheal', 'Bob', 'Tracy']
print(classmates)
type(classmates)
len(classmates)
print(classmates[0])
print(classmates[1])
print(classmates[2])
print(classmates[3])
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
# add entry at the end
classmates.append('Adam')
print(classmates)
# add entry at specific position
classmates.insert(1, 'Jack')
print(classmates)
# delete the last entry
classmates.pop()
print(classmates)
# delete the entry at the specific position
classmates.pop(1)
print(classmates)
# change the entry at the specific position
classmates[1] = 'Sarah'
print(classmates)
# the entries of a list can be different types
L = ['Apple', 123, True]
print(L)
# the entry of a list can be another list
s = ['python', 'java', ['asp', 'php'], 'scheme']
len(s)
print(s)
print(s[2])
p = ['asp', 'php']
s = ['python', 'java', p, 'scheme']
print(p[1])
print(s[2][1])
# the empty list
L = []
len(L)
print(L)
# tuple ################################################################
# once defined, then cannot be changed
# define the empty tuple
t = ()
print(t)
# define the empty tuple with one element
t = (1,)
print(t)
# define the tuple with one element 1
t = (1)
print(t)
# define the tuple with two element 1 and 2
t = (1, 2)
print(t)
# define a 'changeable' tuple
t = ('a', 'b', ['A', 'B'])
print(t)
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)
| true |
3f693e3ac2a3ca646480defe121ca735abcf664e | jai-somai-lulla/Sem8 | /Legacy/ML/LinearRegression/grad.py | 1,201 | 4.1875 | 4 | import numpy as np
import pandas as pd
#import matplotlib.pyplot as plt
def cost_function(X, Y, B):
if(type(Y) == np.int64):
m=1
else:
m = len(Y)
J = np.sum((X.dot(B) - Y) ** 2)/(m*2)
return J
def gradient_descent(X, Y, B, alpha, iterations):
cost_history = [0] * iterations
m = len(Y)
for iteration in range(iterations):
# Hypothesis Values for entire set data
h = X.dot(B)
# Difference b/w Hypothesis and Actual Y
loss = h - Y
# Gradient Calculation
gradient = X.T.dot(loss) / m
# Changing Values of B using Gradient
B = B - alpha * gradient
# New Cost Value
cost = cost_function(X, Y, B)
cost_history[iteration] = cost
return B, cost_history
def main():
print("Linear Regrssion")
x=np.array([1,2,3,3,4,4,5,6,8,12])
x0 = np.ones(len(x))
X = np.array([x0, x]).T
Y=np.array([2,4,4,5,8,8,12,12,16,24])
B = np.array([0, 0])
print cost_function(X[0],Y[0],B)
inital_cost = cost_function(X, Y, B)
print("Initial Cost: "+str(inital_cost))
B,ch = gradient_descent(X, Y, B, 0.01, 10)
print "Weights :"+str(B)
print "Cost_History :"+str(ch)
if __name__ == "__main__":
main()
| true |
8d0778ee4429cf201fca2e368e9d8c07a1c0f25e | THE-SPARTANS10/Python-Very-Basics | /user_input.py | 211 | 4.1875 | 4 | #By default in python for user input we get everything as string
name = input("Enter your name: ")
value = input("Enter a number: ")
print("your name is " + name + " and your favourite number is: " + value)
| true |
5b269c95f2eeed5db00155b1a25feed94cd56bfe | TomiwaJoseph/Python-Scripts | /emirp_numbers.py | 745 | 4.34375 | 4 | '''
An emirp is a prime that results in a different prime when its decimal digits
are reversed.
Example:
Input: 13
Output: True (13 and 31 are prime numbers)
Input: 23
Output: False (23 is prime but 32 is not)
Input: 113
Output: True (113 and 311 are prime numbers)
'''
print()
def know_prime(number):
return number > 1 and not any(number % n ==0 for n in range(2, number))
def emirp(number):
reversed = int(str(number)[::-1])
# find if the number and its reverse is prime
return know_prime(number) and know_prime(reversed)
entry = int(input('Enter your number: '))
print(emirp(entry))
print()
print('Emirp numbers within your input range are:')
emirp_range = [i for i in range(entry) if emirp(i)]
print(emirp_range)
| true |
cfab197d408c4a376f486922b7f7c6bbd0377304 | TomiwaJoseph/Python-Scripts | /neon_numbers.py | 532 | 4.1875 | 4 | '''
A number is considered Neon if the sum of digits of the square of the number is
equal to the number itself.
Example:
Input: 9
9 * 9 == 81
8 + 1 == 9
Output: True
'''
print()
def neon(number):
squared = number ** 2
sum_of_digits = sum([int(i) for i in str(squared)])
return sum_of_digits == number
entry = int(input('Enter your number: ') or '911')
print(entry)
print(neon(entry))
print()
print('Neon numbers within your input range are:')
neon_range = [i for i in range(entry) if neon(i)]
print(neon_range) | true |
bebc9c33456253aac57a78dd4dbf58b3854b75c3 | TomiwaJoseph/Python-Scripts | /twin_prime_numbers.py | 795 | 4.15625 | 4 | '''
A Twin prime is a prime number that is either 2 less or 2 more than another prime number.
For example: (41,43) or (149,151)
Example:
Input: 0,15
Output: (3,5),(5,7),(11,13)
'''
print()
def check_prime(number):
return number > 1 and not any(number % n ==0 for n in range(2, number))
def twin_prime(number):
splitted = number.split(',')
from_, to_ = int(splitted[0]), int(splitted[1])
# find the primes in that range
find_primes = [i for i in range(from_, to_) if check_prime(i)]
# loop through the primes and find the ones with a difference of 2
twins = [(x,y) for x in find_primes for y in find_primes if y-x == 2]
return twins
# entry = int(input('Enter your range seperated with a comma: '))
entry = input() or '0,15'
print(twin_prime(entry))
print()
| true |
0c2ecd13b13a498ff90c14f10cd2d710c07c56da | TomiwaJoseph/Python-Scripts | /anti-lychrel_numbers.py | 1,245 | 4.125 | 4 | '''
An anti-Lychrel number is a number that forms a palindrome through
the iterative process of repeatedly reversing its digits and adding the
resulting numbers. For example 56 becomes palindromic after one iteration:
56+65=121. If the number doesn't become palindromic after 30 iteratioins,
then it is not an anti-Lychrel number.
Don't be surprised if nearly all the numbers you enter return true!
The first 3 non anti-lychrel numbers are 196, 295 and 394
Example:
Input: 12
Output: True (12 + 21 = 33, a palindrome)
Input: 57
Output: True (57 + 75 = 132, 132 + 231 = 363, a palindrome)
'''
print()
def anti_lychrel(number):
num_of_iter = 1
new_number = number
while 1:
split_add = new_number + int(str(new_number)[::-1])
new_number = split_add
if num_of_iter == 30:
return False
if str(split_add) == str(split_add)[::-1]:
return True
else:
num_of_iter += 1
entry = int(input('Enter your number: ') or '400')
print(anti_lychrel(entry))
print()
print('Bonus')
print('Non Anti-Lychrel numbers within your input range are:')
lychrel_range = [i for i in range(entry) if anti_lychrel(i)]
print([i for i in range(entry) if i not in lychrel_range])
| true |
a091e96b64e922d1c06701fa93a5bafe24258fd3 | jchaclan/python | /cat.py | 580 | 4.25 | 4 | # Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
cat1 = Cat('Freddy', 10)
cat2 = Cat('Manny', 8)
cat3 = Cat('Lucy', 9)
# 2 Create a function that finds the oldest cat
def getOldestCat(*args):
return max(args)
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
print(
f'The oldest cat is {getOldestCat(cat1.age, cat2.age, cat3.age)} years old')
| true |
f825c3e3fd51e813ae357890221d8287edb9f09b | brianbruggeman/lose-7drl | /lose/utils/algorithms/pathing.py | 2,765 | 4.3125 | 4 | # -*- coding: utf-8 -*-
import operator
import heapq
from .distances import log_distance
def create_dijkstra_map(graph, start, target=None, cost_func=None, include_diagonals=None):
"""Creates a dijkstra map
Args:
graph (list): a set of nodes
start (node): the starting position
target (node): the ending position; None means all nodes
cost_func (callback): the cost function or distance formula
include_diagonals (bool): Only use cardinal directions if False, else include all 8 possibilities
Returns:
dict: mapping of node: cost
"""
mapping = {
node: cost
for cost, node in dijkstra(graph, start, target=target, cost_func=cost_func, include_diagonals=include_diagonals)
}
return mapping
def dijkstra(graph, start, target=None, cost_func=None, include_diagonals=None):
"""Implementation of dijkstra's algorithm as a generator.
This one uses a priority queue for a stack.
See: https://en.wikipedia.org/wiki/Dijkstra's_algorithm
Args:
graph (list): a set of nodes
start (node): the starting position
target (node): the ending position; None means all nodes
cost_func (callback): the cost function or distance formula
include_diagonals (bool): Only use cardinal directions if False, else include all 8 possibilities
Yields:
cost, node
"""
cost_func = cost_func or log_distance
queue = []
heapq.heapify(queue)
costs = {start: 0}
heapq.heappush(queue, (costs[start], start))
yield (costs[start], start)
while queue:
node_cost, node = heapq.heappop(queue)
node_cost = costs[node]
neighbors = get_neighbors(node, include_diagonals=include_diagonals)
neighbors = [
neighbor for neighbor in neighbors
if neighbor in graph # short circuit on nodes not available
if neighbor not in costs # short circuit on nodes already calculated
]
for neighbor in neighbors:
neighbor_cost = cost_func(start, neighbor) + node_cost
yield (neighbor_cost, neighbor)
costs[neighbor] = neighbor_cost
heapq.heappush(queue, (neighbor_cost, neighbor))
if neighbor == target:
break
def get_neighbors(node=None, include_diagonals=None):
"""Creates a list of neighbors.
Yields:
point: a neighbor node
"""
if node is None:
node = (0, 0)
cardinals = [(0, 1), (0, -1), (1, 0), (-1, 0)]
diagonals = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
directions = cardinals + diagonals if include_diagonals else cardinals
for offset in directions:
yield tuple(map(operator.add, node, offset))
| true |
d69954226bd6d65bb7d9fb405a1f21c95a5c55bf | brianbruggeman/lose-7drl | /lose/utils/algorithms/distances.py | 2,737 | 4.5 | 4 | # -*- coding: utf-8 -*-
import math
from itertools import zip_longest as lzip
def manhattan_distance(x, y):
"""Calculates the distance between x and y using the manhattan
formula.
This seems slower than euclidean and it is the least accurate
Args:
x (point): a point in space
y (point): a point in space
Returns:
int: the distance calculated between point x and point y
"""
diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)]
return sum(diffs)
def euclidean_distance(x, y):
"""Calculates the distance between x and y using the euclidean
formula.
This should be the most accurate distance formula.
Args:
x (point): a point in space
y (point): a point in space
Returns:
float: the distance calculated between point x and point y
"""
distance = 0
diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)]
distance = math.sqrt(sum(diff**2 for diff in diffs))
return distance
def octagonal_distance(x, y):
"""Calculates the distance between x and y using the octagonal
formula.
This is a very fast and fairly accurate approximation of the
euclidean distance formula.
See: http://www.flipcode.com/archives/Fast_Approximate_Distance_Functions.shtml
Args:
x (point): a point in space
y (point): a point in space
Returns:
int: the distance calculated between point x and point y
"""
distance = 0
diffs = [abs((xval or 0) - (yval or 0)) for xval, yval in lzip(x, y)]
if len(diffs) != 2:
raise TypeError('This distance is only valid in 2D')
diff_min = min(diffs)
diff_max = max(diffs)
approximation = diff_max * 1007 + diff_min * 441
correction = diff_max * 40 if diff_max < (diff_min << 4) else 0
corrected_approximation = approximation - correction
distance = (corrected_approximation + 512) >> 10
return distance
def log_distance(x, y, func=None, k=None):
"""Calculates the distance between x and y using the octagonal
formula.
This wraps a distance function with a log output. If no distance
function is provided, then euclidean is used.
Args:
x (point): a point in space
y (point): a point in space
func (callback): returning the log of a distance
k (numeric): a factor [default: 1.2]
Returns:
int: the distance calculated between point x and point y
"""
if k is None:
k = 1.2
if func is None:
func = octagonal_distance
distance = func(x, y)
if distance == 0:
distance = 1 / 10**10
logged_distance = 6 * math.log(distance)
return logged_distance
| true |
4c300e2170cb75b47518e284b545201cfaafd0af | aineko-macx/python | /ch16/16_6.py | 2,019 | 4.28125 | 4 | import copy
class Time(object):
"""Represents a time in hours, minutes, and seconds.
"""
def print_time(Time):
print("%.2d: %.2d: %.2d" %(Time.hour, Time.minute, Time.second))
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
if sum.second >= 60:
sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
def secs(Time):
return Time.hour*3600 + Time.minute*60 + Time.second
def increment(Time, seconds):
newTime = copy.deepcopy(Time)
initial = secs(Time)
total = initial + seconds
hours = total//3600
rem = total%3600
minutes = rem//60
sec = rem%60
newTime.hour = hours
newTime.minute = minutes
newTime.second = sec
return newTime
def time_to_int(Time):
minutes = Time.hour*60 + Time.minute
seconds = minutes *60 + Time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def incr(Time, seconds):
int = time_to_int(Time)
temp = int + seconds
newTime = int_to_time(temp)
return newTime
def mul_time(Time, num):
intTime = secs(Time)
product = intTime*num
result = int_to_time(product)
return result
def pace(Time, dist):
pace = mul_time(Time, 1/dist)
return pace
#Main
myTime = Time()
myTime.hour = 0
myTime.minute = 10
myTime.second = 30
print_time(pace(myTime, 1.5))
"""
newTime = increment(myTime, 9999)
print_time(newTime)
ans = int_to_time(time_to_int(myTime))
print_time(ans)
newTime1 = incr(myTime, 9999)
print_time(newTime1)
start = Time()
start.hour = 9
start.minute = 45
start.second = 0
duration = Time()
duration.hour = 1
duration.minute = 35
duration.second = 0
done = add_time(start, duration)
print_time(done)
"""
| true |
f55cd76dfe5ccb409039ae8f53b69d48ffd33677 | aineko-macx/python | /ch17/17_1.py | 892 | 4.25 | 4 | class Time(object):
"""Represents the time of day.
"""
def __init__(self, hour = 0, minute = 0, second = 0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print("%.2d: %.2d %.2d" %(self.hour, self.minute, self.second))
def time_to_int(self):
return self.hour*3600 + self.minute*60 + self.second
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)
def is_after(self, other):
return self.time_to_int() > other.time_to_int()
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
start = Time()
start.hour = 9
start.minute = 45
start.second = 00
end = start.increment(1337)
start.print_time()
end.print_time()
| true |
6d9f449312a335671fd358bf0482486d59eab245 | SoniaB77/Exercise_12_Collections | /exercise12.2.py | 267 | 4.25 | 4 | tup = 'Hello'
print(len(tup))
print(type(tup))
# this is a string so the length is checking the iterables of the string which is 5.
tup = 'Hello',
print(len(tup))
print(type(tup))
# this is a tuple so it is checking the iterables but of a tuple so this outputs 1. | true |
11d167121472792a525554e7d54d1bed829a641c | ProgrammingForDiscreteMath/20170823-bodhayan | /code.py | 2,748 | 4.46875 | 4 | """
This is the code file for Assignment from 23rd August 2017.
This is due on 30th August 2017.
"""
##################################################
#Complete the functions as specified by docstrings
# 1
def entries_less_than_ten(L):
"""
Return those elements of L which are less than ten.
Args:
L: a list
Returns:
A sublist of L consisting of those entries which are less than 10.
"""
return [i for i in L if i < 10]#Add your code here
#Test
#print entries_less_than_ten([2, 13, 4, 6, -5]) == [2, 4, 6, -5]
# 2
def number_of_negatives(L):
"""
Return the number of negative numbers in L.
Args:
L: list of integers
Returns:
number of entries of L which are negative
"""
return sum(i<0 for i in L)##YOUR CODE REPLACES THIS
# TEST
#print number_of_negatives([2, -1, 3, 0, -1, 0, -45, 21]) == 3
# 3
def common_elements(L1, L2):
"""
Return the common elements of lists ``L1`` and ``L2``.
Args:
L1: List
L2: List
Returns:
A list whose elements are the common elements of ``L1`` and
``L2`` WITHOUT DUPLICATES.
"""
return list(set(L1).intersection(L2)) # your code goes here
#TEST
#print common_elements([1, 2, 1, 4, "bio", 6, 1], [4, 4, 2, 1, 3, 5]) == [1, 2, 4]
#4
def fibonacci_generator():
"""
Generate the Fibonacci sequence.
The Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, 21,...
is defined by a1=1, a2=1, and an = a(n-1) + a(n-2).
"""
i,j=1,1
while True:
yield i
i,j=j,i+j# Hint: use the ``yield`` command.
#TEST
f = fibonacci_generator()
#print f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next(),f.next()
#[f.next() for f in range(10)] #== [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
#5
def largest_fibonacci_before(n):
"""
Return the largest Fibonacci number less than ``n``.
"""
f=fibonacci_generator()
i=f.next()
j=f.next()
while j<n:
i=j
j=f.next() #Your code goes here.
return i
#TEST
#print largest_fibonacci_before(55) == 34
#6
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
def catalan_generator():
"""
Generate the sequence of Catalan numbers.
For the definition of the Catalan number sequence see `OEIS <https://www.oeis.org/A000108>`.
"""
i=0
while True:
yield fact(2*i)/(fact(i)*fact(i+1))#Your code goes here.
i+=1
#TEST
#c = catalan_generator()
#print [c.next() for i in range(10)] #== [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862]
#7
### CREATE YOUR OWN FUNCTION. Make sure it has a nice docstring.
# See https://www.python.org/dev/peps/pep-0257/
# for basic tips on docstrings.
| true |
b6c12ae165a10fa29347189009f7e60edba15f91 | 215shanram/lab4 | /lab4-exercise4.py | 1,163 | 4.25 | 4 | import sqlite3
#connect to database file
dbconnect = sqlite3.connect("lab4.db");
#If we want to access columns by name we need to set
#row_factory to sqlite3.Row class
dbconnect.row_factory = sqlite3.Row;
#now we create a cursor to work with db
cursor = dbconnect.cursor();
#execute insetr statement
cursor.execute('''insert into table2 values (1, 'door', 'kitchen')''');
cursor.execute('''insert into table2 values (2, 'temperature', 'kitchen')''');
cursor.execute('''insert into table2 values (3, 'door', 'garage')''');
cursor.execute('''insert into table2 values (4, 'motion', 'garage')''');
cursor.execute('''insert into table2 values (5, 'temperature', 'garage')''');
dbconnect.commit();
#execute simple select statement
cursor.execute('SELECT * FROM table2');
print("Display all Kitchen sensors")
cursor.execute('SELECT * FROM table2 WHERE zone = "kitchen"');
for row in cursor:
print(row['sensorID'],row['type'],row['zone'] );
print("Display all Door sensors")
cursor.execute('SELECT * FROM table2 WHERE type = "door"');
#print data
for row in cursor:
print(row['sensorID'],row['type'],row['zone'] );
#close the connection
dbconnect.close();
| true |
76b8b31d7c66daa0600fe3d738803c15899c544c | btab2273/functions | /path_exists.py | 946 | 4.3125 | 4 | # Define path_exists()
def path_exists(G, node1, node2):
"""
Breadth-first seach algorithim
This function checks whether a path exists between two nodes( node1, node2) in graph G.
"""
visited_nodes = set()
# Initialize the queue of cells to visit with the first node: queue
queue = [node1]
# Iterate over the nodes in the queue
for node in queue:
# Get neighbors of the node
neighbors = G.neighbors(node)
# Check to see if the destination node is in the set of neighbors
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
break
else:
# Add neighbors of current node that have not yet been visited
queue.extend([n for n in neighbors if n not in visited_nodes])
# Check to see if the final element of the queue has been reached
if node == queue[-1]:
print('The path does not exist between nodes {0} and {1}'.format(node1, node2))
return False
| true |
b644ba60f87f1ff5c4bdfa9311698112fd6f59a1 | paul-tqh-nguyen/one_off_code | /old_sample_code/misc/vocab/vocab.py | 1,572 | 4.40625 | 4 | #!/usr/bin/python
# Simple program for quizzing GRE vocab
import random
import os
if __name__ == "__main__":
os.system("clear")
definitions = open('./definitions1.csv', 'r') # load GRE words from .csv file
# We want to split the words by part of speech so that when quizzing, the quizzee cannot guess the answer based on the part of speech of the word in question
nouns = dict()
verbs = dict()
adjs = dict()
for defn in definitions: # Separate words by part of speech
x=defn.replace('\x00', '').split("\t")
if len(x)==3:
if ( x[1] == "n"):
nouns[x[0]] = x[2][:-1]
elif ( x[1] == "v"):
verbs[x[0]] = x[2][:-1]
elif ( x[1] == "adj"):
adjs[x[0]] = x[2][:-1]
else:
print "Failed to load entry: "+str(x)
for i in xrange(50): # Ask questions
# pick which part of speech of the word we will quiz on
# Side effect is that we will ask approximately teh same amount of questions on each part of speech
# This differs from just picking words at random since the number of words for each part of speech may nto be equal
partOfSpeech = [nouns, verbs, adjs][random.randint(0,1)]
word = random.choice(partOfSpeech.keys()) # pick word
answer = random.randint(1,4) # Which choice will be the right answer
print word+":"
for j in xrange(1,5):
print j,": ",
if (j != answer):
print random.choice(partOfSpeech.values())
else:
print partOfSpeech[word]
print ""
while ( raw_input('Guess: ')[0] != str(answer) ):
print "Try Again..."
print "\nCorrect!\n"+word+": "+partOfSpeech[word]+"\n\n\n"
| true |
654e9a81c02402214df6d7f0e3f2ba226375d205 | sanika2106/if-else | /next date print.py | 826 | 4.34375 | 4 | # Write a Python program to get next day of a given date.
# Expected Output:
# Input a year: 2016
# Input a month [1-12]: 08
# Input a day [1-31]: 23
# The next date is [yyyy-mm-dd] 2016-8-24
date=int(input("enter the date:"))
if date>=1 and date<=31:
print("now enter the month")
month=int(input("enter the month:"))
if month>=1 and month<=12:
print("plz enter the year now")
year=int(input("enter the year:"))
if year>=0 and year<=2021:
print(date+1,"/",month,"/",year)
else:
print("plz enter valid year")
else:
print("plz enter the valid month")
else:
print("plz enter valid date")
| true |
c516eed37f3a04549028b078464756a786711002 | sanika2106/if-else | /16link.py | 429 | 4.1875 | 4 | # c program to check weather the triangle is equilateral ,isosceles or scalene triangle
side1=int(input("enter the number:"))
side2=int(input("enter the number:"))
side3=int(input("enter the number:"))
if(side1==side2 and side2==side3 and side1==side3):
print("it's a equilateral triangle")
elif(side1==side2 or side2==side3 or side1==side3):
print("it's a isosceles triangle")
else:
print("it's a scalene triangle") | true |
b60fe06fd61994d24e2c6292c0266f2179d1ced9 | sanika2106/if-else | /q13.py | 658 | 4.15625 | 4 | age=int(input("enter the number"))
if age>=5 and age<=18:
print("can go to school")
elif age>=18 and age<=21:
print("""1.can go to school,
2.can vote in election""")
elif age>=21 and age<=24:
print("""1.can go to school,
2.can vote in election,
3.can drive a car""")
elif age >=24 and age<=25:
print("""1.can go to school,
2.can vote in election,
3.can drive a car,
4.can marry""")
elif age >25:
print("""1.can go to school,
2.can vote in election,
3.can drive a car,
4.can marry,
5.can legally drink""")
else:
print("can not legally drink") | true |
4c7c531576a1c5fd956a08ec5dfc454509604ec0 | sanika2106/if-else | /prime number.py | 306 | 4.21875 | 4 | #prime number
num=int(input("enter the number:"))
if num==1 or num==0:
print("not a prime number")
elif num%2!=0 and num%3!=0 and num%5!=0 and num%7!=0:
print("prime number")
elif num==2 or num==3 or num==5 or num==7 :
print("it is also a prime number")
else:
print("not a prime number")
| true |
720179901f16379215f0160e45b410f039462b33 | A-Chornaya/Python-Programs | /LeetCode/same_tree.py | 1,823 | 4.15625 | 4 | # Given two binary trees, write a function to check if they are the same or not.
# Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
'''
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorder(self, p):
result = []
if p:
result.append(self.inorder(p.left))
result.append(p.val)
result.append(self.inorder(p.right))
return result
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if self.inorder(p) == self.inorder(q):
return True
else:
return False
p = TreeNode(1)
p.left = TreeNode(2)
# p.right = TreeNode(1)
q = TreeNode(1)
# q.left = TreeNode(1)
q.right = TreeNode(1)
s = Solution()
print(s.inorder(p))
print(s.inorder(q))
print(s.isSameTree(p, q))
'''
[[[], 2, []], 1, [[], 1, []]]
[[[], 1, []], 1, [[], 1, []]]
False
'''
p = TreeNode(1)
p.left = TreeNode(2)
# p.right = TreeNode(1)
q = TreeNode(1)
# q.left = TreeNode(1)
q.right = TreeNode(1)
s = Solution()
print(s.inorder(p))
print(s.inorder(q))
print(s.isSameTree(p, q))
'''
[[[], 2, []], 1, []]
[[], 1, [[], 1, []]]
False
'''
p = TreeNode(1)
p.left = TreeNode(2)
p.right = TreeNode(1)
q = TreeNode(1)
q.left = TreeNode(2)
q.right = TreeNode(1)
s = Solution()
print(s.inorder(p))
print(s.inorder(q))
print(s.isSameTree(p, q))
'''
[[[], 2, []], 1, [[], 1, []]]
[[[], 2, []], 1, [[], 1, []]]
True
''' | true |
d5efc35e0ef0f9c25258247625e9063c8fdd5a92 | AhmedFakhry47/Caltech-Learn-from-data-cours-homework- | /PLA.py | 736 | 4.15625 | 4 | '''
A simple code (Script) to illustrate the idea behind perception
learning algorithm
'''
import numpy as np
import matplotlib.pyplot as plt
##First step is generating data
D = np.random.rand(3,1000)
threshold = .4
#target function represented in weights
f = np.array([0.2,0.8,0.5]).reshape((3,1))
Y = (np.sum((f*D),axis=0)>threshold).astype(int)
Y[Y==0] = -1
##Start Applying PLA
W = np.zeros(3) # Initialization of weights by zeros
h = 0 # The current hyposis
N = 1000 # Number of training examples
#Start learning
for _ in range(10000):
for i in range(N):
h = 1 if (np.sum(W * D[:,i]) > .4) else -1
if (h != Y[i]): #Update step in case of miss-classified points
W+= Y[i]*D[:,i]
print(W)
| true |
486705e17f2ad4eb0ad7a421deb1319818f4142d | umeshchandra1996/pythonpractice | /palindrome.py | 312 | 4.1875 | 4 | num=int(input("Enter the number "))
numcopy=num #copy num for compare whith reverse
reverse=0
while num>0:
reminder=num%10 #find reminder
reverse=(reverse*10) + reminder
num//=10
if(numcopy == reverse):
print("Yes It is a plaindrome number ")
else:
print("It is not plaindrome number ")
| true |
52b50a64102f7813ab4c7dc2a20df989963965e9 | Nsk8012/30_Days_Of_Code | /Day_5/2_List_with_value.py | 780 | 4.53125 | 5 | # Initialing the value
fruits = ['banana', 'orange', 'mango', 'lemon', 'apple']
print('Fruits:', fruits)
print('Length of Fruits List:', len(fruits))
# List can have items of different data types.
lst = ['Nishanth', 15, True, {'Country': 'India', 'City': 'Coimbatore'}]
print(lst)
# Index of list
# [a, b, c, d, e]
# 0, 1, 2, 3, 4 - In Positive Indexing
# -5,-4,-3,-2,-1 - In Negative Indexing
# calling values in list by index
ls = ['a', 'b', 'c', 'd', 'e']
print(ls[2]) # calling 3rd value in index
print(ls[-1]) # calling last value in index
# Unpacking the list by assigning the values
a, b, c, *rest = ls # the index value will be assigned to this variables seperated by ,
print(a)
print(rest) # *rest is used for collecting other values in a upacked list
| true |
265d3fe67eefc5514a347f467ef3e2d4639b174f | Nsk8012/30_Days_Of_Code | /Day_8/1_Creating_Dictionaries.py | 504 | 4.1875 | 4 | # 30_Days_Of_Code
# Day 8
# Dictionary will have key:value.
empty_dict = {}
# Dictionaries with Values
dct = {'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4'}
print(dct)
# len is used to find the length od dicitionaries
print(len(dct))
# Accessing Dictionary Items by calling keys init.
print(dct['Key1'])
print(dct['Key3'])
# also by Get() function
print(dct.get('Key2'))
# -----------------------------------------------------------------------------------------------------
| true |
719da2eb3374940257fa83a687556275a47f2351 | BlaiseGD/FirstPythonProject | /RockPapScis.py | 1,963 | 4.3125 | 4 | from random import randrange
reset = 'y'
while reset == 'y':
print("This is rock, paper, scissors against a computer!\ny means yes and n means no\nEnter 1 for rock, 2 for paper, or 3 for scissors")
#1 is rock 2 is paper 3 is scissors for compInput
computerInput = randrange(1, 4)
userInput = int(input())
if(userInput == 1 and computerInput == 3):
print("\n\nYou Win\n!")
elif(userInput == 2 and computerInput == 1):
print("\n\nYou Win!\n")
elif(userInput == 3 and computerInput == 2):
print("\n\nYou Win!\n")
elif(userInput == computerInput):
print("\n\nYou tied\n")
else:
print("\n\nYou lose!\n")
print("Your input was " + str(userInput) +"\nThe computer input was " + str(computerInput) + "\nDo you want to play again\n")
reset = input()
#The commented code is the original and is much cleaner to play
#The uncommented code is the shortest I could get it with it retaining full functionality
#from random import randrange
#import os
#clear = lambda: os.system('clear');
#reset = 'y';
#while reset == 'y':
#print("This is rock, paper, scissors against a computer!")
#print("y means yes and n means no");
#print("Enter 1 for rock, 2 for paper, or 3 for scissors")
#1 is rock 2 is paper 3 is scissors for compInput
#computerInput = randrange(1, 4);
#userInput = int(input());
#if(userInput == 1 and computerInput == 3):
# clear();
# print("You Win!");
#elif(userInput == 2 and computerInput == 1):
# clear();
# print("You Win!");
#elif(userInput == 3 and computerInput == 2):
# clear();
# print("You Win!")
#elif(userInput == computerInput):
# print("You tied");
#else:
# print("You lose!")
#print("Your input was " + str(userInput))
#print("The computer input was " + str(computerInput))
#print("Do you want to play again?");
#reset = input();
#clear();
| true |
b2d81645b2694214cc0b952a6f0abc694113c8d2 | nstrickl87/python | /working_with_lists.py | 2,909 | 4.28125 | 4 | #Looping Through Lists
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
#More WOrk in a Loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title())
#makign Numerical Lists using the range function
#Range off by one starts counting from first value and stops counting att he second value off by one
for value in range (1,5):
print(value)
#Print 1 through 5
for value in range (1,6):
print(value)
#Using range to make a list of Numbers
numbers = list(range(1,6))
print(numbers)
#List only even numbers between 1 and 10
#Starts at 2 and then adds 2 until reaches second value.
even_numbers = list(range(2,11,2))
print(even_numbers)
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
#Simple Stats with numbers
digits = list(range(0,10))
print(digits)
print(min(digits))
print(max(digits))
print(sum(digits))
#List Comprehensions a;;pws up to generate this same list in just one line of code.
squares = [value**2 for value in range (1,11)]
print(squares)
#Slicing and List
#To make a slice you indicate the first and last element you want to work with
players = ['nathan', 'caitlin','hazel', 'pat','brett','wayland']
print(players[0:3]) #First three elements in the list
#want 2nd 3rd and 4th person in a list
print(players[1:4])
#Without a starting index python assumes the start of the list
print(players[:4])
#Want all items in a list starting formt eh second item
print(players[1:])
#Negative index returns an element a certain distance from the end of the list
# Return last 3 players from listaZ
print(players[-3:])
#Looping through a slice
print("Last 3 players in the list:")
for name in players[-3:]:
print(name)
#Copying a List
family = players[:]
print(players)
print(family)
#Tupule
print("\n======== Tuples ========\n\n")
#Lists Work Well for storing sets of items that can change throughout the life of a program. The ability to modify lists is particularly
# Lists good for list of users on a website or a list of characters in a game.
#Sometimes we wantt ot create a list of items that cannot change Tuples allow for this.
#Python referes to values that cannot change as immutable. An Immutable list is a tuple
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
#Tuples are defined with () instead of the []
#Looping through Tuple
for dimension in dimensions:
print(dimension)
#Writing over a Tuple
#Although you cannot modify a Tuple., You can assign a new value to a variable that holds a tuple.
#So if we wanted to redefine the tuple we can
print("Oringinal Dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
print("New Dimensions")
for dimension in dimensions:
print(dimension)
#use tuples when we do not want values to change in a program as they are a simple data structure.
| true |
6c6293507679501315a1dcf6b5816ce937dc1d42 | BC-csc226-masters/a03-fall-2021-master | /a03_olorunpojuessangd.py | 1,267 | 4.1875 | 4 | # Author: David Olorunpoju-Essang
# Username: olorunpojuessangd
# Assignment: A03: Fully Functional Gitty Psychedelic Robotic Turtles
# Purpose: Draws a fractal tree
#Reference : https://www.youtube.com/watch?v=RWtNQ8RQkO8
#Google doc link: https://docs.google.com/document/d/1AVxiZuugCxoRw1HFxaOiRBXjW_VQFrHNXVA4CwW8-qU/edit?usp=sharing
import turtle
def draw_tree(i): #the parameter i defines when we call the function
if i<10: #Once a value of 10 is achieved the turtle reverses
return
else:
david.fd(i)
david.left(30)
draw_tree(3*i/4) #The equation determines the extensiveness and length of the branch patterns
david.right(60)
draw_tree(3*i/4)
david.left(30)
david.backward(i)
def main():
wn = turtle.Screen()
turtle.bgcolor("skyblue")
wn.title("Here is a tree")
global david
david = turtle.Turtle()
david.color("blue")
david.shape("turtle")
david.pensize(7)
david.pencolor("green")
david.penup()
david.setpos(0,-200) #lowers the turtle's placment in the screen
david.left(90)
david.speed(0)
david.pendown()
draw_tree(100)
draw_tree()
turtle.done() #Keeps the window open until the turtle has completed executing the function
main()
| true |
732fb7258b5baae253205e6fbf4c21c49948f15b | rupeshkumar22/tasks.py | /basic/fibonacci.py | 1,179 | 4.25 | 4 | from typing import List
def matrixMul(a, b):
"""
Returns the product of the given matrices
"""
# Initializing Empty Matrix
c = [[0, 0], [0, 0]]
# 2x2 matrix multiplication. Essentially O(1)
for i in range(2):
for j in range(2):
for k in range(2):
c[i][j] = (c[i][j] + (a[i][k] * b[k][j]))
# Returning the products
return c
def fibonacci(number:int) -> int:
"""
Returns the n'th fibonacci sequence number
>>> fibonacci(number=10)
55
"""
# Initializing Magic Matrix
a = [[1, 1, ], [1, 0]]
# Initializing Identity Matrix
res = [[1, 0], [0, 1]]
# Fast Exponentiation (log(n) complexity)
while number:
if number & 1:
res = matrixMul(res, a)
number >>= 1
a = matrixMul(a, a)
# Return the nth fibonacci number. Could also return res[0][1] instead.
return res[1][0]
def fibonacciSequence(number:int) -> List[int]:
"""
Returns a list of first n fibonacci numbers
>>> fibonacciSequence(number=10)
[0,1,1,2,3,5,8,13,21,34,55]
"""
return [fibonacci(num) for num in range(number + 1)]
| true |
6b63098f3c1fdeb2fe23804b79d7881edbbbd8a5 | MRajibH/100DaysOfCode | /DAY07/classes.py | 678 | 4.21875 | 4 | # OOP - Programming Paradigm
# In OOP we think about world in terms of objects
# Objects might store information or support the ability todo some operations
# OOP helps you to create new types or you can say customized types e.g. 2D Values
# class = A templete for a type of objects
class point():
# It'll called automaticly every time when creating a new point
def __init__(self, input1, input2):
self.x = input1
self.y = input2
inpt1 = input("Enter The value of X coordinate: ")
inpt2 = input("Enter The value of Y coordinate: ")
p = point(inpt1, inpt2)
print(f'the value of x coordinate is = {p.x}')
print(f'the value of y coordinate is = {p.y}')
| true |
f02d92449a70f0e6365fb7ce764bfb91cbdef928 | azarateo/bnds | /python_workspace/as/unicode.py | 207 | 4.15625 | 4 | print('Hello. This program will show you different unicode characters,'+
'well at least the ones Python 3 can print')
for x in range(32, 127):
print "Character with number %d is %s in hex %X" % (x,x,x) | true |
8bc79e0d2a65ddca96589a3659beed116986b221 | garikapatisravani/PythonDeepLearning | /ICP2/StringAlternative.py | 311 | 4.21875 | 4 | # Author : Sravani Garikapati
# program that returns every other char of a given string starting with first
# Ask user to enter a string
s = str(input("Enter a string: "))
# Use slicing to get every other character of string
def string_alternative(s):
print(s[::2])
if __name__ == '__main__':
string_alternative(s)
| true |
1dca25eb10e1ea42cfaa5efada2c760a0d177f3a | rgraveling5/SDD-Task2a---Record-Structure-Lists- | /main.py | 973 | 4.28125 | 4 |
#Record structure
#Rachael Graveling
#28/08/2020
# List to store all records
student_records = []
# Number of records
number_of_students = 3
# Loop for each student
for x in range(number_of_students):
student = []
student.append(input('Please enter name: '))
student.append(float(input('Please enter age : ')))
while student[1] < 1 or student[1] > 150 or not student[1].is_integer():
print('Error. Must be a whole number between 1 & 150')
student[1] = float(input('Please enter age : '))
student[1] = int(student[1])
student.append(float(input('Please enter height : ')))
while student[2] < 1 or student[2] > 2.5:
print('Error. Must be a number between 1 & 2.5')
student[2] = float(input('Please enter height : '))
student.append(input('What is your home town?: '))
# Add the student record to list of records
student_records.append(student)
# Print the records
for x in student_records:
print(x) | true |
1f0b4de15cf6e721462a4a7f1eb0384e082759f0 | Aneesh540/python-projects | /NEW/one.py | 1,237 | 4.125 | 4 | """ 1) implementing __call__ method in BingoCage class
which gives it a function like properties"""
import random
words = ['pandas', 'numpy', 'matplotlib', 'seaborn', 'Tenserflow', 'Theano']
def reverse(x):
"""Reverse a letter"""
return x[::-1]
def key_len(x):
"""Sorting a list by their length"""
return sorted(x, key=len)
def key_reverse(x):
"""Sorting a list by reverse spelling here reverse() f(x) is defined by us
and key should be a function without execution"""
return sorted(x, key=reverse)
print(key_reverse(words))
print(sorted(words, key = lambda y:y[::-1]))
# EVEN CLASS INSTANCE CAN BE TREATED AS FUNCTION BY IMPLEMENTING __call__ METHOD
class BingoCage:
"""Giving a random element"""
def __init__(self, items):
self.item = list(items)
random.shuffle(self.item)
def pick(self):
try:
return self.item.pop()
except:
raise LookupError("Picking from empty")
def __call__(self, *args, **kwargs):
return self.pick()
if __name__ == '__main__':
foo = BingoCage(range(2, 20, 2))
print(foo)
print("see that foo() and foo.pick() act in similar manner")
print(foo.pick())
print(foo())
| true |
44f1fc9e2a4a0d4daf2dfb19f95b68c4242dd23f | Aneesh540/python-projects | /closures/closures2.py | 761 | 4.3125 | 4 | """ A closure is a inner function that have access to variables in
the local scope in which it was created even after outer function has
finished execution"""
import logging
def outer_func(msg):
message=msg
def inner_func():
# print(message)
print(msg)
return inner_func
hello=outer_func('hello')
print('hello bcomes %s ' %(hello.__name__))
hello()
logging.basicConfig(filename='example.log',level=logging.INFO)
def logger(function):
def log_func(*args):
logging.info('Running "{}" with arguments {}'.format(function.__name__,args))
print(function(*args))
return log_func
def add(x,y):
return x+y
def sub(x,y):
return x-y
add_logger=logger(add)
sub_logger=logger(sub)
add_logger(3,4)
sub_logger(9,10)
sub_logger(33,-99)
| true |
4de9a04857f0e838acb52dba77a7ba5a98c303d7 | meghaggarwal/Data-Structures-Algorithms | /DSRevision/PythonDS/bst.py | 809 | 4.125 | 4 | from dataclasses import dataclass
@dataclass
class Bst():
data:int
left:object
right:object
def insertNode(data, b):
if b is None:
return Bst(data, None, None)
if data < b.data:
b.left = insertNode(data, b.left)
else:
b.right = insertNode(data, b.right)
return b
b = None
b = insertNode(1, b)
insertNode(2, b)
insertNode(3,b)
def traverse_in_order(root):
if root is None:
return
if root.left is not None:
traverse_in_order(root.left)
print(root.data)
if root.right is not None:
traverse_in_order(root.right)
if __name__ == "__main__":
traverse_in_order(b)
# 2 3 4 5 6 7
# void inorderTraversal(struct node * root) {
# if(!root):
# return
# inorderTraversal(root->left)
# print(root->data)
# } | true |
c24699269a2bdc789332da8b5a523930e6a0d616 | mike1806/python | /udemy_function_22_palindrome_.py | 439 | 4.25 | 4 | '''
Write a Python function that checks whether a passed string is palindrome or not.
Note: A palindrome is word, phrase, or sequence that reads the same backward as
forward, e.g., madam or nurses run.
'''
def palindrome(x):
x = x.replace(' ','') # This replaces all spaces " " with no space ''. (Fixes issues with strings that have spaces)
return x == x[::-1] # check through slicing
palindrome('nurses run')
| true |
bf9d8f5013c8791f8df90f0f9c50095ed39de6cc | cpd67/Languages | /Python/Python3/Practice3.py | 1,911 | 4.1875 | 4 | #Python program for counting the number of times a letter appears in a string.
#Also, learned that locals are NOT reassigned in for loop...
def findMax(lis):
"""Finds the max element in a list."""
index = [0]
m1 = [-999999999]
#Special use case: empty list
if len(lis) == 0:
return -1, -1
#Special use case: list of size 1
elif len(lis) == 1:
return lis[0], 0
#Normal case
else:
for n in range(len(lis)):
if lis[n] > m1[0]:
m1[0] = lis[n]
index[0] = n
#http://stackoverflow.com/questions/9752958/how-can-i-return-two-values-from-a-function-in-python
return m1[0], index[0]
#index = 4, max = 1000
lis2 = [4, 8, 16, -1, 1000]
m1, in1 = findMax(lis2)
print("The max of lis2 is:", m1)
print("The index of " + str(m1) + " is " + str(in1))
#Special use case 1
lis3 = [10000000]
m2, in2 = findMax(lis3)
print("The max of lis3 is:", m2)
print("The index of " + str(m2) + " is " + str(in2))
#index = 0, max = 10
lis4 = [10, -1]
m3, in3 = findMax(lis4)
print("The max of lis4 is:", m3)
print("The index of " + str(m3) + " is " + str(in3))
#Utility function for finding index in a sequence
def findIndex(element, sequence):
"""Finds the index of an element in a sequence."""
for n in range(len(sequence)):
if element == sequence[n]:
return n
return -1
def countReps(st1):
"""Counts the number of repetitions a letter appears in a string sequence."""
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g' 'h' 'i','j','k','l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v' 'w', 'x', 'y', 'z']
counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for n in st1:
index = findIndex(n, letters)
counts[index] += 1
mx, letterInd = findMax(counts)
lett = letters[letterInd]
print("The most frequent letter is " + str(lett) + ", its count is " + str(mx))
#Test 1
st1 = "blaah"
countReps(st1)
st2 = "cowboy beep boop boop bop"
countReps(st2)
| true |
f0cc6b193e1a77e194295927cea914fe3f1c7424 | cpd67/Languages | /Python/Python3/Practice5.py | 573 | 4.25 | 4 | #!/bin/python
# Dice Rolling Simulator
# THIS CODE ONLY WORKS WITH PYTHON3
import random
MIN = 1
MAX = 7
def rollDice():
print("Let's roll some dice!")
print("Rolling...")
print("The dice roll is: " + str(random.randrange(MIN, MAX)))
rollDice()
while True:
x = input('Would you like to roll again? ')
if x in ("y", "Y", "yes", "YES", "ye"):
print ("Okay!")
rollDice()
continue
elif x in ("n", "N", "no", "NO"):
print ("Fine. Partypooper.")
break
print ("I didn't understand that. Please try again.")
| true |
d1acf74226395891e904adb871c7adad36c15ef4 | Wattabak/quickies | /selection-sort-python/selection_sort.py | 2,371 | 4.1875 | 4 | """
Time complexity:
Worst case: [Big-O] O(n^2)
Average case: [Big-theta] ⊝(n^2)
Best case: [Big-Omega] Ω(n^2)
How it works:
- find the position of the minimum element;
- swap this element with the first one (because in the sorted array it should be the first);
- now regard the sub-array of length N-1, without the last value (which is already "in right place");
- find the position of maximum element in this sub-array (i.e. second to maximum in the whole array);
- swap it with the last element in the sub-array (i.e. with position N-2);
- now regard the sub-array of the length N-2 (without two last elements);
- algorithm ends when "sub-array" decreases to the length of 1.
About:
inefficient on large lists
worse than insertion sort
Variants:
Heapsort:
uses implicit heap data structure to speed up finding and removing the lowest datum, is faster with the same basic idea
Bingo sort:
items are ordered by repeatedly looking through the remaining items to find the greatest value and moving all items with that value to their final location.
"""
import argparse
import logging
from typing import Any, Iterable, TypeVar
logger = logging.getLogger(__name__)
def selection_sort_first_try(array: Iterable) -> Iterable:
"""Uses maximums, not minimums, also recursive, not the usual way it would be done"""
if len(array) <= 1:
return array
max_index = array.index(max(array))
array[-1], array[max_index] = array[max_index], array[-1]
array[:-1] = selection_sort(array[:-1])
return array
def selection_sort(array: Iterable) -> Iterable:
"""In place sorting algorithm that is simple but inefficient"""
for i in range(len(array)):
min_idx = i
for j in range(i+1, len(array)):
if array[min_idx] > array[j]:
min_idx = j
array[i], array[min_idx] = array[min_idx], array[i]
return array
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Sort elements using Selection Sort algorithm"
)
parser.add_argument('values', metavar='V', type=int,
nargs='+', help='values to sort')
array = parser.parse_args().values
length = len(array)
sorted_array = selection_sort(array)
print(
f"out: {sorted_array};\narray_length: {length};"
)
| true |
2b3155ea06158cec47b36bc822688f83024aeccf | do-py-together/do-py | /examples/quick_start/nested.py | 1,369 | 4.15625 | 4 | """
Nest a DataObject in another DataObject.
"""
from do_py import DataObject, R
class Contact(DataObject):
_restrictions = {
'phone_number': R.STR
}
class Author(DataObject):
"""
This DataObject is nested under `VideoGame` and nests `Contact`.
:restriction id:
:restriction name:
:restriction contact: Nested DataObject that represents contact information for this author.
"""
_restrictions = {
'id': R.INT,
'name': R.STR,
'contact': Contact
}
class VideoGame(DataObject):
"""
This DataObject is nested under nests `Author`.
:restriction id:
:restriction name:
:restriction author: Nested DataObject that represents author information for this video game.
"""
_restrictions = {
'id': R.INT,
'name': R.NULL_STR,
'author': Author
}
# Data objects must be instantiated at their **init** with a dictionary and strict True(default) or False.
instance = VideoGame({
'id': 1985,
'name': 'The Game',
'author': {
'id': 3,
'name': 'You Lose',
'contact': {
'phone_number': '555-555-5555'
}
}
}, strict=False)
print(instance)
# output: VideoGame{"author": {"contact": {"phone_number": "555-555-5555"}, "id": 3, "name": "You Lose"}, "id": 1985, "name": "The Game"}
| true |
80c95e36826f3d3aa0c32986f35024d67b8e7609 | carlagouws/python-code-samples | /How tall is the tree.py | 1,167 | 4.21875 | 4 | # ******************************************************************************************
# Description:
# Program asks the user how tall the tree is
# User inputs the height of the tree in number of rows, e.g. "9" produces a height of 9 rows
'''
How tall is the tree : 5
#
###
#####
#######
#########
#
'''
# ******************************************************************************************
# Variables:
# Number of rows (rows)
# Number of iterations (i)
# Number of hashtags = i*2 - 1
# Number of spaces = rows - i
# Receive user input and make integer
rows = int(input('How tall is the tree?: '))
# Body of pine tree
i = 1
while i <= rows:
# Insert required amount of spaces
NumSpaces = rows - i
for spaces in range(NumSpaces):
print(" ", end = "")
# Insert required amount of hashtags
NumHashtags = i*2 - 1
for hashtags in range(NumHashtags):
print("#", end = "")
# Enter
print()
# Increment iteration
i += 1
# Base of pine tree
BaseSpaces = rows - 1
for spaces in range(BaseSpaces):
print(" ", end="")
print("#") | true |
4f624c48797695f31507d40cf0c0a84b15fad99c | krishankansal/PythonScripts | /Files/e.py | 511 | 4.1875 | 4 | def count_the(filename):
''' Total number of appeareances of word 'the' in file'''
try:
f = open(filename)
contents = f.read()
appeareances = contents.lower().count('the')
print(f"The file {filename} has word 'the' appereared {appeareances}. times")
except FileNotFoundError:
msg = f"sorry! file {filename} do not exists"
print(msg)
filenames = ['boys_book.txt','abc.abc','alice.txt','margret.txt']
for filename in filenames:
count_the(filename)
| true |
dd7ad1c4bb038caab7a793e4b24ff4b657b8dc8c | Bryantmj/iteration-1 | /iteration.py | 2,203 | 4.15625 | 4 | # Make a local change
# Make another local change
# Make a change from home
# iteration pattern
# [1, 5, 7 ,8 , 4, 3]
def iterate(list):
# standard for loop with range
# for i in range(0, len(list)):
# print list[i]
# for each loop
for item in list:
print item
def print_list(list):
print ""
def add_one(list):
# standard for loop with range
for i in range (0, len(list)):
list[i] += 1
return list
def print_scores(names, scores):
for i in range(0, len(names)):
print names[i] , " scored " , scores[i]
# filter patterns - a type of iteration
# filter pattern
def congratulations(names, scores):
for i in range(0, len(names)):
if (scores[i] == 100):
print "Congrats ", names[i], "! You got a perfect score!"
# accumulation pattern - type of iteration
# keep track of other data as we go
def sum(numbers):
total = 0
for n in numbers:
total += n
return total
def max(numbers):
current_max = numbers[0]
for n in numbers:
if n > current_max:
current_max = n
return current_max
def alternating_sum(numbers):
total = 0
for i in range(0, len(numbers)):
if i == 0 or i % 2 == 1:
total += numbers[i]
else:
total -= numbers[i]
return total
# def alternating_sum(numbers):
# total = numbers[i]
# for i in range(0, len(numbers)):
# if i % 2 == 0:
# total += numbers[i]
# else:
# total -= numbers[i]
# return total
def sum_outside(numbers, min, max):
total = 0
for n in numbers:
if not (min <= n and n < max):
total += n
return total
def count_close_remainder(numbers, divisor):
count = 0
for n in numbers:
remainder = n % divisor
if remainder <= 1 or remainder == divisor-1:
count += 1
return count
def double_down(numbers, target):
result = [maybe_doubled(numbers[0], numbers[0], target)]
for i in range(1, len(numbers)):
result.append(maybe_doubled(numbers[0], numbers[1-1], target))
return result
def maybe_doubled(n, prev_n, target):
distance = abs(n - target)
if n < prev_n or distance <= 3:
return 2 * n
return n
def standarad_deviation(n, numbers, mean):
total = 0
for n in numbers:
total += n
n / len(numbers) = mean
numbers - mean = difference
difference^2 = new_mean
| true |
de773b5afd4597a2f89027b50b0f75a89a530085 | VinceSevilleno/variables | /developmentexercise2.py | 373 | 4.375 | 4 | #Vince Sevilleno
#24/09/2014
#Development Exercise 2
print("This program will convert a given value in degrees Fahrenheit into degrees Centigrade:")
print()
fahrenheit=int(input("Please enter any value of temperature:"))
centigrade=(fahrenheit-32)*(5/9)
print()
print("The value {0} degrees Fahrenheit is equal to {1} degrees Centigrade.".format(fahrenheit,centigrade))
| true |
d60cc8f46dbf6738555f7a715869f1e38e7ca033 | girl-likes-cars/MIT_programming_course | /Newton square root calculator.py | 577 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 16:52:15 2018
@author: Maysa
"""
#Set the epsilon and the square root you want to find
#Pick a random starting point for your guess (let's say, guess/2)
epsilon = 0.01
k = int(input("Give me a number whose square root you want to find! "))
guess = k/2.0
iterations = 0
while guess*guess - k >= epsilon:
guess = guess - ((guess**2 - k)/(2*guess))
iterations = iterations + 1
print("Square root of",k,"is approximately",guess)
print("It squares to equal",guess*guess)
print("Iterations:",iterations) | true |
eb4481b19aa8e9c0116ae88a69b596192a05cf9c | AlvaroMenduina/Jupyter_Notebooks | /Project_Euler/41.py | 1,564 | 4.125 | 4 | """
Project Euler - Problem 41
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
import numpy as np
import itertools
def is_prime(n):
prime = True
if n % 2 == 0 and n != 2:
return False
elif n % 2 != 0 and n != 2:
for factor in np.arange(3, int(np.sqrt(n)) + 1, 2):
if n % factor == 0:
return False
return prime
def pandigitals_n(n):
"""
Function that returns all n-pandigital numbers
generated from the digits [1, 2, ..., n]
"""
digits = list(np.arange(1, n+1))
permutations = list(itertools.permutations(digits))
pandigits = []
for perm in permutations:
s = ''
for digit in perm:
s += str(digit)
# Ignore the even numbers, as they are not prime
if s.endswith('2') == False and \
s.endswith('4') == False and\
s.endswith('6') == False and \
s.endswith('8') == False:
pandigits.append(int(s))
return pandigits
if __name__ == "__main__":
pandigitals_primes = []
for n in np.arange(1, 10):
print("\nCompute pandigital numbers up to %d" %n)
pandigitals = pandigitals_n(n)
for p in pandigitals:
if is_prime(p):
pandigitals_primes.append(p)
print("\nLargest pandigital number that is prime: ", pandigitals_primes[-1]) | true |
fcf684ff90ae780d7070caef6ecfced3749e5c8c | Charlieen/python_basic | /python_tutorial/NumberAndString.py | 2,942 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 09:13:37 2021
@author: dzgygmdhx
"""
# print(2+2)
# print(8/3)
# print(17//3)
# print(17%3)
# print(5**2)
width =20
height= 3*9
print(width * height)
# begin string '' " " \ \n r
print('I like "you", but "you" do not like me')
print("I like 'you', but 'you' do not like me")
print('I like \'you\', but "you" do not like me')
print('I like \'you\', but \'you\' do not like me')
print('I like "you",\nbut "you" do not like me')
print('I like "you",\n but "you" do not like me')
print(r'I like "you",\nbut "you" do not like me')
print(r'c:\some\home')
#string multiple lines
# End of lines are automatically included in the string, you can use a
# \ at the end of the line to avoid this
print("""\
i like you?
yes i like you
really?
sure
you can see, it is very easy way to do it
"""
)
print("hello " *3 + 'python world' + 'good!'*2)
print("hello " *3 , 'python world' , 'good!'*2)
# Two or more string literals (i e the ones enclosed between quotes)
# This is only works with two literals though,not with variables or expressions:
print('a' 'b')
print('i like you so much'
'you ?'
' are you sue? ')
word ="Python"
print(word[0])
# for i in word:
# print(i)
# for (index,i) in word:
# print(index)
# print(i)
# +---+---+---+---+---+---+
# | P | y | t | h | o | n |
# +---+---+---+---+---+---+
# 0 1 2 3 4 5 6
# -6 -5 -4 -3 -2 -1
print(word[-1])
# String inner string [] , index, slicing are all support
print(word[1:2])
print(word[:6])
# [start:end]
print(word[:2]) # index 0 1 start: 0
print(word[:-2]) # index -6 -5 -4 -3 start: -6
print(word[-5:-2]) #index -5 -4 -3
# use index when too large will get error but use slice ,no error
print(word[:1000])
# pirnt(word[1000]) # no
# String in python is immutable
print(type(word))
# 'str' object does not support item assignment
# word[1]='ddd'
print(type(1))
print(type(None))
print(type(True))
# List in python
squares=[1,4,9,16,25]
print(squares[:3])
squares[0] =1000 # list mutalbe
print(squares[:3])
print(squares[:3]+[10,20])
# TypeError: can only concatenate list (not "int") to list
# print(squares[:3]+10)
print(type(squares))
squares.append(10)
print(squares)
print(squares[:3] +[(1,2)])
squares[:-3] =[1979,1980]
print(squares)
squares[:] =[]
print(squares)
# <class 'builtin_function_or_method'>
print(type(len))
print(len(squares))
# list can be nest and can hold any class type
nestList=[1,[2,3],(2,3),{'dd':'ddd'}]
print(nestList)
# First Steps Towards Programming
# demonstrating that the expression on the rihgt-hand side are all evaluated first
# before any of the assignment take place. The right-hand side expression are evaluated
# from the left to the right
a,b,c =0,1,0
while a<10:
print(a)
print(c)
a,b,c = b,a+b,c+b+a+b
| true |
a5e324794898c9ed9a024dcb506366e9617c1694 | mvimont/FoundationsofMeasurement | /Chapter1/ThreeProceduresBasicMeasurement/Ordinal/ordinal.py | 1,948 | 4.21875 | 4 | import sys
import random
#Covers contens of Chapt 1, 1.1.1 pages 2 - 3
#Purpose here to define fundamental concepts (greater than, addition, etc) in definition/conditions used in book
#length is here used as means to illustrate attribution of quantities to qualitative observations
#transitive property
def is_greater(a, b):
if a > b:
return True
return False
#"We require a > b only if the function of a is grea ter than the functino of b
#In transitve property in this case, a and be are results of functions
#Ordinal relationships fullfilable by all numeric cases, except where a ~ b
def is_equivalent(a, b):
if not a > b and not a < b:
return True
return False
#We assign to first rod any number, a larger rod a larger number, a smaller rod a smaller, etc.
#In event a ~ b.Procedure for ordinal measuremnt is only suitable in the event precision yields allows for it
if __name__== "__main__":
a_values = random.sample(range(0, sys.maxsize), 1000)
b_values = random.sample(range(0, sys.maxsize), 1000)
ord_dict = {'a': a_values, 'b': b_values}
for value_index in range(len(ord_dict['a'])):
a = ord_dict['a'][value_index]
b = ord_dict['b'][value_index]
output_tuple = (a, b)
try:
if is_greater(a, b):
result = 1
print('a with value %s is greater than b with value %s' % output_tuple)
elif is_greater(b, a):
result = 2
print('a with value %s is less than b with value %s' % output_tuple)
elif is_equivalent(a, b):
result = 3
print('a with value %s is equal to b with value %s' % output_tuple)
else:
result = 666
assert result != 666
except AssertionError:
print('The foundations of science are a lie and humanity is doomed. DOOOOOMMMMMED')
raise
| true |
029d436bddee58022eaa2c619b3adccf19f34884 | SeanRosario/assignment9 | /lk1818/data.py | 1,129 | 4.125 | 4 | '''
This module is for data importing, transforming, and merging.
'''
import pandas as pd
import numpy as np
def load_data(): #this function reads the files and creates two data frames: countries and income in desired format.
countries = pd.DataFrame(pd.read_csv('./countries.csv'))
income = pd.DataFrame(pd.read_csv('./indicator_gapminder_gdp_per_capita_ppp.csv'))
income = income.transpose() #transpose income data set so that row indexes are years
return [countries, income]
def merge_by_year(countries, income, year):
'''
Provide a function called merge_by_year(year) to merge the countries and income data sets for any given year. The result is a DataFrame with three columns titled Country, Region, and Income.
'''
try:
int(year)
except KeyError:
print ('Invalid input type.')
else:
try:
merged_income = countries.join(income.ix[str(year)], how='inner')
except KeyError:
print ('Invalid year.')
else:
merged_income.columns = ['Country', 'Region', 'Income']
return merged_income
| true |
ed784f7a6638216dc456eccbe7adcf8172234450 | Mukesh-SSSDIIT/python2021_22 | /Sem5/Collections/List/list_basic3.py | 686 | 4.125 | 4 | list1 = ["aaa","bbb","ccc"]
list2 = [111,222,333]
list3 = list1 + list2
print(list1)
print(list2)
print(list3)
# Another way to join to lists.
# for i in list2:
# list1.append(i)
# print(list1)
# Use extend method
list1.extend(list2)
print(list1)
list4 = list([1,2,3,4])
print(list4)
list5 = [10,20,10,20,30,40,30]
# Returns the number of elements with the specified value
print(list5.count(30))
# Returns the index of the first element with the specified value
print(list5.index(20))
# Adds an element at the specified position
print(list5)
list5.insert(2,100)
print(list5)
list6 = [10,5,20,15,30]
list6.reverse()
print(list6)
list6.sort(reverse=True)
print(list6)
| true |
cac27739601b117356d19c3a8bad348ac16863a9 | bilaleluneis/LearningPython | /abstract_class.py | 1,708 | 4.375 | 4 | from abc import ABC, abstractmethod
__author__ = "Bilal El Uneis and Jieshu Wang"
__since__ = "June 2018"
__email__ = "bilaleluneis@gmail.com"
"""
Animal is an abstract class and I shouldn't be able to create instance of it, but in python there is no
abstract keyword or feature that is part of the language construct, there is API that simulate such behaviour
by extending ABC class (Abstract Base Class).I also found that I could break it and create instance of it
unless I introduce an abstract method using abstractmethod decorator in this example.
"""
class Animal (ABC):
def __init__(self, category=None):
self.category = category
super().__init__()
@abstractmethod
def speak(self):
print("not sure what sound I should make!!")
class Dog (Animal):
def __init__(self):
super().__init__()
self.category = "Canine"
def speak(self):
print("Wooof!!")
class Cat (Animal):
def __init__(self):
super().__init__()
self.category = "Feline"
def speak(self):
print("Meaw!!")
class Rat (Animal):
def __init__(self):
super().__init__()
self.category = "Rodent"
def speak(self):
print("Whatever a Rat says!!")
class NewlyDiscoveredAnimal (Animal):
def __init__(self):
super().__init__()
self.category = "new category"
def speak(self):
super().speak()
# start of running code
if __name__ == "__main__":
# animal = Animal() # if uncommented this will throw error, you cant create instance of abstract class
collectionOfAnimals: [Animal] = [Cat(), Rat(), Dog(), NewlyDiscoveredAnimal()]
for animal in collectionOfAnimals:
animal.speak()
| true |
09383d8e3d90a1801c149c2506d78660d790c983 | JuliaGu808origin/pyModul1 | /extraLabba/extra2/extra2/extra2.1.py | 341 | 4.59375 | 5 | # Write a Python program to get the dates 30 days before and after from the current date
# !可以顯示再漂亮一點
import datetime
today = datetime.datetime.now()
before = today - datetime.timedelta(days=30)
after = today + datetime.timedelta(days=30)
print(f"Today: {today}, \n30 days before: {before}, \n30 days after: {after}")
| true |
979d8e871ff93c499b1e2c5fa30084f399b60655 | JuliaGu808origin/pyModul1 | /extraLabba/extra2/extra2/extra2.2.py | 795 | 4.34375 | 4 | #########################################################
# Write a Python program display a list of the dates
# for the 2nd Saturday of every month for a given year.
#########################################################
import calendar
try:
givenYear = int(input("Which year -> "))
except:
print("Wrong year number !")
if givenYear:
for month in range(1,13):
eachMonth = calendar.monthcalendar(givenYear, month)
first_sat_month = eachMonth[0]
second_sat_month = eachMonth[1]
third_sat_month = eachMonth[2]
if first_sat_month[calendar.SATURDAY]:
saturday = second_sat_month[calendar.SATURDAY]
else:
saturday = third_sat_month[calendar.SATURDAY]
print(f"{calendar.month_abbr[month]} {saturday}")
| true |
08f51078381095f447623fed68837c911cedb949 | smraus/python-assignments | /08 startswithIs.py | 517 | 4.375 | 4 | #--------8 program to get a new string from a given string where "Is" has been added to the front-------
def main():
while True:
try:
string = input('Enter a string : ')
if string.startswith('Is'):
print('Your string' , string , 'is correct.')
else:
new_string = 'Is'+string
print('Your string' , string , 'has been formatted to' , new_string)
break
except:
print('Invalid entry.')
main()
| true |
f1a30558ce9da0d7f2f57b4782dc406b9e19f819 | smraus/python-assignments | /16 x1y1 x2y2.py | 757 | 4.3125 | 4 | #-----16 program to compute the distance between the points (x1, y1) and (x2, y2)----
from math import sqrt
def main():
while True:
try:
print('Enter the pairs in the format x,y')
x1_y1 = input('Enter x1,y1 : ')
x2_y2 = input('Enter x2,y2 : ')
first = x1_y1.split(',')
second = x2_y2.split(',')
result = calculate(first, second)
print('The distance between the points' , x1_y1 , 'and' , x2_y2 , 'is' ,result)
break
except:
print('Invalid entries, enter digits in the given format')
def calculate(f, s):
r1 = (int(s[0]))**2 - (int(f[0]))**2
r2 = (int(s[1]))**2 - (int(f[1]))**2
r3 = sqrt(r1 + r2)
return r3
main()
| true |
3d4a19f5a378a454403c21abe780ee3a62fe9cc7 | qainstructorsky2/gitleeds2021c1 | /demos/lambda.py | 416 | 4.59375 | 5 | choices = { "R":,Rock "P": Paper, "S: Scissors" }
# Get the user's choice of the three
user_choice = input("\nType R, P, or S to play against the computer: ")
# Print what the user's choice, so she knows what she picked
print user_choice
# Make sure the user input is valid
if user_choice in choices:
print "You chose %s." % user_choice
else:
print "Your choice of %s is not a valid choice." % user_choice
| true |
d02059f5953986a9aaa0680b42321c3f58336189 | rob19gr661/Python-Tutorials | /Python/2 - Reading And Writing Files/Writing_Files.py | 680 | 4.125 | 4 | """
Writing Files:
"""
# Testing the "a" operation
"""
Test_file = open("Testtest.txt", "a") # Remember that append will add something to the end of the file
Test_file.write("\nToby - Official poopscooper") # We add the typed line to the end of the document
Test_file.close()
"""
# Testing the "w" operation
# Remember that "w" will overwrite the entire file if the same filename is used
# A entirely new file can be created by simply changing the filename in the "open()" function
Test_file = open("Testtest.txt", "w")
Test_file.write("\nToby - Official poopscooper") # The typed line will be the only thing in the overwritten file
Test_file.close() | true |
b029fb0cd22c7c7a4c6ae93dc85e2d6223f804e6 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Strings/434_number_of_segments_in_string.py | 560 | 4.28125 | 4 | # Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
#
# Please note that the string does not contain any non-printable characters.
#
# Example:
#
# Input: "Hello, my name is John"
# Output: 5
def countSegments(s):
"""
:type s: str
:rtype: int
"""
# Credits: https://leetcode.com/problems/number-of-segments-in-a-string/solution/
count = 0
for i in range(len(s)):
if (i == 0 or s[i-1] == " ") and s[i] != " ":
count += 1
return count
| true |
9b0583e881f7ae10553828b4051968d8b0619a5e | AmitKulkarni23/Leet_HackerRank | /CrackingTheCodingInterview/Bit Manipulation/ith_bit_set.py | 795 | 4.15625 | 4 | """
Python program to check if ith bit is set in the binary representation of a given number
To check if the ith bit is set or not (1 or not), we can use AND operator
And the given number with 2^i. In 2 ^ i only the ith bit is set.
All the other bits are zero.
If numb & ( 2 ^ i) returns a non-zero number then the ith bit in the given number is set
How to get 2 ^ i. Use the left -shift operator <<( i.e 1 << i)
"""
def ith_bit_set(numb, i):
"""
Method to check if the ith bit is set in a given number
:param numb: integer
:param i: integer i
:return: true, iff the ith bit is set in teh given number
Example: N = 20 = {10100}2 => ith_bit_set(20, 2) returns True
"""
if numb & (1 << i):
return True
return False
print(ith_bit_set(20, 2))
| true |
fd0d1ff9f35f40b9159edd85135d069a02b562b4 | AmitKulkarni23/Leet_HackerRank | /Dynamic_Programming/rod_cutting.py | 957 | 4.15625 | 4 | # Given a rod of certain lenght and given prices of different lenghts selling in the
# market. How do you cut teh rod to maximize the profit?
###################################
def get_cut_rod_max_profit(arr, n):
"""
Function that will return maximum profit that can be obtained by cutting
teh rod into pieces and selling those pieces at market value
L -> lenght of final rod
arr -> array of prices
Credits -> https://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
Time Complexity -> O(n ^ 2)
"""
# Use dynamic programming
# Create a 2D array
cache = [0 for _ in range(n+1)]
cache[0] = 0
for i in range(1, n+1):
max_val = float("-inf")
for j in range(i):
max_val = max(max_val, arr[j] + cache[i - j -1])
cache[i] = max_val
return cache[n]
# Examples
arr = [1, 5, 8, 9, 10, 17, 17, 20]
L = len(arr)
print(get_cut_rod_max_profit(arr, L))
| true |
c5d38264a6fc929dad3989817c2965fa3c67c0e6 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Trees/226_invert_binary_tree.py | 1,294 | 4.40625 | 4 | # Invert a binary tree.
#
# Example:
#
# Input:
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# Output:
#
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# Time COmplexity : O(n) -> n is teh number of nodes in teh tree
# Space COmplexity -> O(n) -> The queue can contain all nodes in each level
# in the worst case
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# We will try to use a iterative approach
if root is None:
return None
queue = [root]
while queue:
current_node = queue.pop(0)
# Swap the nodes
temp = current_node.left
current_node.left = current_node.right
current_node.right = temp
# Add left and right nodes to teh queue if they are present
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
return root
| true |
f5e0e4edbdb2beb39e967a2edbc8d0f246649079 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Strings/844_backspace_string_compare.py | 989 | 4.25 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
#
#
#
# Example 1:
#
# Input: S = "ab#c", T = "ad#c"
# Output: true
# Explanation: Both S and T become "ac".
# Example 2:
#
# Input: S = "ab##", T = "c#d#"
# Output: true
# Explanation: Both S and T become "".
# Example 3:
#
# Input: S = "a##c", T = "#a#c"
# Output: true
# Explanation: Both S and T become "c".
# Example 4:
#
# Input: S = "a#c", T = "b"
# Output: false
# Explanation: S becomes "c" while T becomes "b".
def backspaceCompare(S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
s_list = []
t_list = []
for x in S:
if x != "#":
s_list.append(x)
else:
if s_list:
s_list.pop()
for y in T:
if y != "#":
t_list.append(y)
else:
if t_list:
t_list.pop()
return "".join(s_list) == "".join(t_list)
| true |
ff3dc719301e1f8dbcfc28964d43173e79c7278d | AmitKulkarni23/Leet_HackerRank | /Dynamic_Programming/maximum_sum_increasing_subsequence.py | 1,346 | 4.25 | 4 | # Given an array of n positive integers.
# Write a program to find the sum of maximum sum subsequence of the given array such that the intgers in
# the subsequence are sorted in increasing order. For example, if input is {1, 101, 2, 3, 100, 4, 5},
# then output should be 106 (1 + 2 + 3 + 100),
# if the input array is {3, 4, 5, 10}, then output should be 22 (3 + 4 + 5 + 10) and
# if the input array is {10, 5, 4, 3}, then output should be 10
# Source -> https://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/
def max_sum_incr_subseq(arr):
"""
Function that returns the sum of teh maximum sum increasing subsequence of
the given array
Example:
max_sum_incr_subseq([1, 101, 2, 3, 100, 4, 5] ) -> 106
"""
# Copy/ Clone the entire array into a different array
msis = arr[:]
# Iterate through the arr
for i in range(1, len(arr)):
for j in range(i):
# Do what?
# Compare the elements
# Then check the sum
if arr[j] < arr[i] and msis[i] < msis[j] + arr[i]:
# Then update
msis[i] = msis[j] + arr[i]
# Return the max value in msis array
return max(msis)
# Test Examples:
arr = [1, 101, 2, 3, 100, 4, 5]
arr_2 = [3, 4, 5, 10]
print("MSIS is ", max_sum_incr_subseq(arr_2))
| true |
9a640edb1c2cea9743d4b651dbbae43095032d20 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Trees/572_subtree_of_another_tree.py | 2,144 | 4.15625 | 4 | # Given two non-empty binary trees s and t, check whether tree t
# has exactly the same structure and node values with a subtree of s.
# A subtree of s is a tree consists of a node in s and all of this node's descendants.
# The tree s could also be considered as a subtree of itself.
#
# Example 1:
# Given tree s:
#
# 3
# / \
# 4 5
# / \
# 1 2
# Given tree t:
# 4
# / \
# 1 2
# Return true, because t has the same structure and node values with a subtree of s.
# Example 2:
# Given tree s:
#
# 3
# / \
# 4 5
# / \
# 1 2
# /
# 0
# Given tree t:
# 4
# / \
# 1 2
# Return false.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
#Credits -> https://leetcode.com/problems/subtree-of-another-tree/discuss/102729/Short-Python-by-converting-into-strings
return self.do_pre_order_traversal(t) in self.do_pre_order_traversal(s)
def do_pre_order_traversal(self, node, x_string):
"""
Helper function
"""
if not node:
return "$"
return "^" + str(node.val) + "#" + self.do_pre_order_traversal(node.left) + self.do_pre_order_traversal(node.right)
# Time Complexity O(m * n)
# Space Complexity : O(n) -> where n is the number of nodes in s
def best_leetcode_sol(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
return traverse(s,t);
def equals(x, y):
"""
Helper function
"""
if not x and not y:
return True
if x is None or y is None:
return False
return x.val==y.val and equals(x.left,y.left) and equals(x.right,y.right)
def traverse(s, t):
"""
Helper Function
"""
return s is not None and ( equals(s,t) or traverse(s.left,t) or traverse(s.right,t))
| true |
a8dce32f98177322594dbd445b955acfa98c6fcb | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/merge_2_sorted_linked_lists.py | 2,896 | 4.125 | 4 | # Merge 2 sorted linked lists
# Return the new merged list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# My Solution - Very poor performance - beats only 26% of python submissions
# Runtime for 208 test cases = 88ms
# Sometimes - this is giving a runtime of 60ms
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# Iterate through the first list
# and store all the values of nodes in a
# list
first_ll_values = []
# If the second list is empty, return the
# first list
if not l2:
return l1
# If the first list is empty, return the
# second list
if not l1:
return l2
# Iterate through the first list and capture all the values
# in a list
first_ll_values = []
while l1:
first_ll_values.append(l1.val)
l1 = l1.next
# Iterate through the second list and capture all the values
# in a list
second_ll_values = []
while l2:
second_ll_values.append(l2.val)
l2 = l2.next
# Now we have all the values in 2 lists
# These lists should be merged and sorted
sorted_merged_list = sorted(first_ll_values + second_ll_values)
# Iterate through this sorted_merged_list and create
# a new ListNode for each item and link the next for this item as the
# next item in the list
for i in range(len(sorted_merged_list) - 1):
ListNode(sorted_merged_list[i]).next = sorted_merged_list[i+1]
return sorted_merged_list
# # Recursive Solution from discussion portal in
# # Leetcode ( https://leetcode.com/problems/merge-two-sorted-lists/discuss/9735/Python-solutions-(iteratively-recursively-iteratively-in-place).)
# # NOT MY SOLUTION
# # Runtime : 76ms
# if not l1 or not l2:
# return l1 or l2
# if l1.val < l2.val:
# l1.next = self.mergeTwoLists(l1.next, l2)
# return l1
# else:
# l2.next = self.mergeTwoLists(l1, l2.next)
# return l2
# # Iterative solution, in-place
# # NOT MY SOLUTION
# # Runtime : 68ms
# if None in (l1, l2):
# return l1 or l2
# dummy = cur = ListNode(0)
# dummy.next = l1
# while l1 and l2:
# if l1.val < l2.val:
# l1 = l1.next
# else:
# nxt = cur.next
# cur.next = l2
# tmp = l2.next
# l2.next = nxt
# l2 = tmp
# cur = cur.next
# cur.next = l1 or l2
# return dummy.next | true |
ed006d939bae223afdd788f0becae5ffe29e2ad3 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Bit_Manipulation/number_of_1_bits.py | 1,081 | 4.375 | 4 | # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
#
# Example 1:
#
# Input: 11
# Output: 3
# Explanation: Integer 11 has binary representation 00000000000000000000000000001011
# Example 2:
#
# Input: 128
# Output: 1
# Explanation: Integer 128 has binary representation 00000000000000000000000010000000
# ALGORITHM: Brian Kernighan’s Algorithm
# Subtraction of 1 from a number toggles all the bits (from right to left) till the rightmost set
# bit(including the righmost set bit). So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)),
# we unset the righmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count.
# Beauty of the this solution is number of times it loops is equal to the number of set bits in a given integer.
def hammingWeight(n):
"""
:type n: int
:rtype: int
"""
count = 0
while n > 0:
n = n & (n - 1)
count += 1
return count
# Examples:
n = 128
print(hammingWeight(n))
| true |
b2af5b93ed6b9fc6fa6503ed5ad1b93caae1ea70 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Medium/BFS/199_binary_tree_right_side_view.py | 1,605 | 4.3125 | 4 | # Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
#
# Example:
#
# Input: [1,2,3,null,5,null,4]
# Output: [1, 3, 4]
# Explanation:
#
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# Credits -> https://leetcode.com/problems/binary-tree-right-side-view/solution/
# Time Complexity -> O(n)
# Space Complexity -> O(n)
# n -> height of the tree
right_most_val = dict()
max_depth = -1
stack = [(root, 0)]
while stack:
node, depth = stack.pop()
if node is not None:
max_depth = max(depth, max_depth)
# Set default -> Sets the value to default value
# if this key is not already present
# Note: The dict is of the form {depth : node.val}
right_most_val.setdefault(depth, node.val)
# Append the left node first( because we want to pop the right node)
# as we want the right side view
stack.append((node.left, depth + 1))
stack.append((node.right, depth + 1))
return [right_most_val[d] for d in range(max_depth + 1)]
| true |
6e65a2c082edad96b92dc17dced5ed6615e22433 | AmitKulkarni23/Leet_HackerRank | /LeetCode/Medium/DFS/439_ternary_expression_parser.py | 2,830 | 4.5625 | 5 | # Given a string representing arbitrarily nested ternary expressions, calculate the result of the expression. You can always assume that the given expression is valid and only consists of digits 0-9, ?, :, T and F (T and F represent True and False respectively).
#
# Note:
#
# The length of the given string is ≤ 10000.
# Each number will contain only one digit.
# The conditional expressions group right-to-left (as usual in most languages).
# The condition will always be either T or F. That is, the condition will never be a digit.
# The result of the expression will always evaluate to either a digit 0-9, T or F.
# Example 1:
#
# Input: "T?2:3"
#
# Output: "2"
#
# Explanation: If true, then result is 2; otherwise result is 3.
# Example 2:
#
# Input: "F?1:T?4:5"
#
# Output: "4"
#
# Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
#
# "(F ? 1 : (T ? 4 : 5))" "(F ? 1 : (T ? 4 : 5))"
# -> "(F ? 1 : 4)" or -> "(T ? 4 : 5)"
# -> "4" -> "4"
# Example 3:
#
# Input: "T?T?F:5:3"
#
# Output: "F"
#
# Explanation: The conditional expressions group right-to-left. Using parenthesis, it is read/evaluated as:
#
# "(T ? (T ? F : 5) : 3)" "(T ? (T ? F : 5) : 3)"
# -> "(T ? F : 3)" or -> "(T ? F : 5)"
# -> "F" -> "F"
# Runtime : 76ms
def parseTernary(expression):
"""
:type expression: str
:rtype: str
"""
# Credits -> https://leetcode.com/problems/ternary-expression-parser/discuss/92185/Short-Python-solutions-one-O(n)
# Time COmplexity -> O(n)
stack = []
for c in reversed(expression):
stack.append(c)
# print("Stack is ", stack)
if stack[-2:-1] == ['?']:
# print("We are here")
# print("stack[-3]", stack[-3])
# print("stack[-5]", stack[-5])
# print("stack[-1]", stack[-1])
stack[-5:] = stack[-3 if stack[-1] == 'T' else -5]
return stack[0]
# Runtime : 32 ms
def parseTernary(expression):
"""
:type expression: str
:rtype: str
"""
while len(expression) > 2:
count = 0
for x in range(2, len(expression)):
if expression[x] == '?':
count += 1
elif expression[x] == ':':
count -= 1
if count == -1:
if expression[0] == 'T':
expression = expression[2:x]
else:
expression = expression[x+1:]
break
else:
return expression
return expression
# Examples:
express = "T?2:3"
print(parseTernary(express))
| true |
3c9e6d1bc56f8b97daada933d42d642542d3cd5c | AmitKulkarni23/Leet_HackerRank | /LeetCode/Easy/Bit_Manipulation/power_of_2.py | 362 | 4.21875 | 4 | # Given an integer, write a function to determine if it is a power of two.
#
# Example 1:
#
# Input: 1
# Output: true
# Example 2:
#
# Input: 16
# Output: true
# Example 3:
#
# Input: 218
# Output: false
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n > 0:
return (n & n - 1) == 0
return False
| true |
58589846f783e636a07f40bb1c9a67441cbe9bdd | giancarlo358/cracklepop | /crackle_pop.py | 686 | 4.25 | 4 | #Write a program that prints out the numbers 1 to 100 (inclusive).
#If the number is divisible by 3, print Crackle instead of the number.
#If it's divisible by 5, print Pop.
#If it's divisible by both 3 and 5, print CracklePop. You can use any language.
#custom range
start = 1
end = 101
my_range = range(start,end)
divisor_three = 3
divisor_five = 5
#function
def cracklepop(number, divisor):
return number % divisor == 0 # what is my residual
#loop
for i in my_range:
result = ""
if cracklepop(i, divisor_three):
result += "Crackle"
if cracklepop(i, divisor_five):
result += "Pop"
print(i if result == "" else result)
#https://repl.it/GICd
| true |
f592d4f598ec510ad260fb6133460514ea38e7d4 | UjjwalP08/Basics-Of-Python | /Exercises/Exercise 1.py | 353 | 4.125 | 4 | """In This exercise we can take input from user and compiler return according to its out put
Eg:- Key now we can provide some details about it."""
a = {"key": "Use to open lock", "greet": "Means to Call about Good mornig", "IT": "Study of Website and Computer"}
""
print(a.keys())
print("Enter Key which details you want to show")
b=input()
print(a[b]) | true |
ee0c50c7586746a4dfdbf6348592f561246942c4 | UjjwalP08/Basics-Of-Python | /No_55_Functioncaching.py | 2,008 | 4.65625 | 5 | """
--------------------> Function Caching <---------------------------
some times we are call the same function in program again and again so our time
of program is taken more than expected so reduce this we are use the function
caching
this method is inside the functool module and method is lur_cache
"""
# import time
#
# def work(n):
# # This is my function of work
# time.sleep(n)
# return n
#
# if __name__ == '__main__':
# print("This is first time")
# work(3)
# print("This is Second time")
# work(3)
# print("Completed")
#
"""
In this program we are call the work function 2 time but it contain 6 sce but
suppose if we have call function 10 times so taken time 30 sec that has not mean
to speed for us
so we want to first store that time value and when we want to that is printed
using this to or call this is known as function caching
"""
from functools import lru_cache
import time
@lru_cache(maxsize=10) # store the capacity of this function call is 10 now
# for different value of it stores after again call the time is reduce
def work(n):
# This is my function of work
time.sleep(n)
return n
if __name__ == '__main__':
print("This is first time")
work(5)
print("This is Second time")
work(3)
print("Completed")
work(5)
print("Again")
work(3)
print("Again")
work(4)
print("call Again")
work(3)
print("again call")
work(4)
print("Over")
# In this program the file or work function call 6 or 7 time like work(5) and work(3) etc
# after when we call the work(5) 2nd time that is not take 5sec to run it
"""
In simple or gujarati language ma kahu to work(5) 2nd time call thase tyare te 5 sce jetlo time nahi le
execution mate tevi j rite jo work(3) pacho call thaay to 3 sec nahi le aabadha function only ek j vaar
tema aapeli integer value hisabe run tahvaa mate time lese biji vaar jo te pachu call thay tyare speed ma
execute thasee vadhare samay nahi lee
""" | true |
4a89663ccb22ff3f3a9138af70b346b60aa43ab1 | aravinthusa/python-prgramme | /file1.py | 479 | 4.40625 | 4 | program:
#to find the radius of the circle
r=float(input("input the radius of the circle:"))
a=(22*r*r)/7
print("the area of circle with radius",r,"is:",a)
output:
input the radius of the circle:1.1
the area of circle with radius 1.1 is: 3.8028571428571434
program:
#to find the extension of the file
a=input("Input the Filename: ")
b=a.split(".")
c=print ("The extension of the file is : " ,b[-1])
output:
Input the Filename: abc.py
The extension of the file is : py
| true |
9665330448fa691346f1117e65665b734cd79aa3 | hungnd11111984/DataCamp | /pandas Foundation/Build a DataFrame.py | 2,933 | 4.28125 | 4 | # 1 Zip lists to build a DataFrame
# Display tuple
print(list_keys)
# ['Country', 'Total']
print(list_values)
# [['United States', 'Soviet Union', 'United Kingdom'], [1118, 473, 273]]
# Zip the 2 lists together into one list of (key,value) tuples: zipped
zipped = list(zip(list_keys,list_values))
# Inspect the list using print()
print(zipped)
# [('Country', ['United States', 'Soviet Union', 'United Kingdom']), ('Total', [1118, 473, 273])]
# Build a dictionary with the zipped list: data
data = dict(zipped)
# Build and inspect a DataFrame from the dictionary: df
df = pd.DataFrame(data)
print(df)
# Country Total
#0 United States 1118
#1 Soviet Union 473
#2 United Kingdom 273
# 2 Building DataFrames with broadcasting
# Make a string with the value 'PA': state
state = 'PA'
# print cities list
print(cities)
# ['Manheim', 'Preston park', 'Biglerville', 'Indiana', 'Curwensville', 'Crown', 'Harveys lake', 'Mineral springs', 'Cassville', 'Hannastown', 'Saltsburg', 'Tunkhannock', 'Pittsburgh', 'Lemasters', 'Great bend'
# Construct a dictionary: data
data = {'state':state, 'city':cities}
# Construct a DataFrame from dictionary data: df
df = pd.DataFrame(data)
# Print the DataFrame
print(df)
# city state
#0 Manheim PA
#1 Preston park PA
#2 Biglerville PA
#3 Indiana PA
#4 Curwensville PA
# 3: Import / Export Data
# 3.1 Reading Flat File
# Read in the file: df1
df1 = pd.read_csv('world_population.csv')
# Create a list of the new column labels: new_labels
new_labels = ['year','population']
# Read in the file, specifying the header and names parameters: df2
df2 = pd.read_csv('world_population.csv', header=0, names=new_labels)
# Print both the DataFrames
print(df1)
# Year Total Population
#0 1960 3.034971e+09
#1 1970 3.684823e+09
print(df2)
# year population
#0 1960 3.034971e+09
#1 1970 3.684823e+09
# 3.2 Delimiters, headers, and extensions
# print(file_messy)
# messy_stock_data.tsv
# Read the raw file as-is: df1
df1 = pd.read_csv(file_messy)
# Print the output of df1.head()
print(df1.head())
# ....
# ....
# IBM 156.08 160.01 159.81 165.22 172.25 167.15 1... NaN
# name Jan Feb Mar Apr May Jun Jul Aug \
#0 IBM 156.08 160.01 159.81 165.22 172.25 167.15 164.75 152.77
# Read in the file with the correct parameters: df2
df2 = pd.read_csv(file_messy, delimiter=' ', header=3, comment='#')
# Print the output of df2.head()
print(df2.head())
# Sep Oct Nov Dec
#0 145.36 146.11 137.21 137.96
#1 43.56 48.70 53.88 55.40
# Save the cleaned up DataFrame to a CSV file without the index
df2.to_csv(file_clean, index=False)
# Save the cleaned up DataFrame to an excel file without the index
df2.to_excel('file_clean.xlsx', index=False)
#
| true |
3bfa1389d2d43bcbdda5995b99c01a8fb16b6496 | yuede/Lintcode | /Python/Reverse-Linked-List.py | 495 | 4.125 | 4 | class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place.
"""
def reverse(self, head):
# write your code here
if head is None or head.next is None:
return head
pre = None
while head is not None:
temp = head.next
head.next = pre
pre = head
head = temp
return pre | true |
51aa90a32ee61c3e3891f4cad80c6a06d59a81dd | chunweiliu/leetcode2 | /insert_interval.py | 1,286 | 4.21875 | 4 | """Insert a new interval
<< [[1, 2], [3, 5], [7, 9]], [4, 8]
=> [[1, 2], [3, 9]]
<< [[1, 2]], [3, 4]
=> [[1, 2], [3, 4]]
- Insert a number
[0, 1, 2, 10], 3
Seperate the intervals to left and right half by comparing them with the target interval
- If not overlap, put them in to left or right
- Otherwise, update the start and end interval
Time: O(n)
Space: O(n)
"""
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
#
# def __repr__(self):
# return '({}, {})'.format(self.start, self.end)
class Solution(object):
def insert(self, intervals, target):
"""
:type intervals: List[Interval]
:type target: Interval
:rtype: List[Interval]
"""
left, right = [], []
for interval in intervals:
if interval.end < target.start:
left.append(interval)
elif interval.start > target.end:
right.append(interval)
else:
target.start = min(target.start, interval.start)
target.end = max(target.end, interval.end)
return left + [target] + right | true |
0c5d9e1322959ea228ef2e8ac23076caa162a192 | chunweiliu/leetcode2 | /the_skyline_problem.py | 1,998 | 4.21875 | 4 | """Use a dict to represent heights. For each critical point, pop the heightest.
<< [[1, 10, 5], [3, 8, 7]]
=> [[1, 5], [3, 7], [8, 5], [10, 0]]
A good illustration of the skyline problem
https://briangordon.github.io/2014/08/the-skyline-problem.html
Time: O(nlogn)
Space: O(n)
"""
from heapq import *
class Solution(object):
def getSkyline(self, LRH):
"""
:type LRH: List[List[int]]
:rtype: List[List[int]]
"""
skyline = []
# liveHR is a max heap of (-height, -right). Pairs are kept in the
# priority queue and they stay in there as long as there's a larger
# height in there, not just until their building is left behind.
liveHR = []
i, n = 0, len(LRH)
while i < n or liveHR:
# If the next building has a smaller x, comparing with the largest
# right point in the heap, add it to the liveHR heap.
#
# ------ <- roof (liveHR[0])
# ------- <- LRH[i] should be added to the live HR
# ------- <- liveHR[1]
if not liveHR or (i < n and LRH[i][0] <= -liveHR[0][1]):
x = LRH[i][0]
while i < n and LRH[i][0] == x:
heappush(liveHR, (-LRH[i][2], -LRH[i][1]))
i += 1
# Otherwise, we need to update liveHR.
#
# ------ <- liveHR that is going to be removed
# ------- <- LRH[i]
# -------- <- liveHR will not be removed at this time, but soon
else:
x = -liveHR[0][1]
while liveHR and -liveHR[0][1] <= x:
heappop(liveHR)
if liveHR:
height = -liveHR[0][0]
else:
height = 0
if not skyline or height != skyline[-1][1]:
skyline.append([x, height])
return skyline | true |
309df73c581fbddafb1d952ef24b7d107e445da4 | chunweiliu/leetcode2 | /implement_trie_prefix_tree.py | 1,849 | 4.3125 | 4 | """
Each Trie node has a dict and a flag.
For inserting a word, insert each character to the Trie if the character is not
there yet. For distiguish a word and a prefix, use the '#' symbol.
Trie
(f) (b)
(o) (a)
(o)T (r)T
"""
from collections import defaultdict
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.chars = defaultdict(TrieNode)
self.is_word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
# If the key is missing in the dict, __missing__ is called and a default
# value will be generated for the missing key, according to the the dict's
# default_factory argument (for example, Trie here).
for char in word:
node = node.chars[char]
node.is_word = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.traverse(word)
return node and node.is_word
def startsWith(self, prefix):
"""
Returns if there is any word in the trie
that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.traverse(prefix)
return bool(node)
def traverse(self, word):
node = self.root
for char in word:
if char not in node.chars:
return False
node = node.chars[char]
return node
# Your Trie object will be instantiated and called as such:
# trie = Trie()
# trie.insert("somestring")
# trie.search("key") | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.