blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c130d758ef000ea0de0b0ed4154dfa711f0b4504 | D-Bits/Math-Scripts | /main.py | 1,918 | 4.40625 | 4 | from vectors import get_dot_product
from series import get_fibonacci, get_num_of_fib, sum_of_terms
from math import factorial
# Choices for the user
options = {
'1': 'Calculate the dot product of two vectors.',
'2': 'Get the sum of the first n terms in an arithmetic series.',
'3': 'Get a specific number in the Fibonacci sequence.',
'4': 'Output the first n numbers in the Fibonacci sequence.',
'5': 'Calculate a factorial.'
}
if __name__ == "__main__":
print() # Blank line for readability
# Show the user their choices
for key, val in options.items():
print(key, val)
print() # Blank line for readability
choice = int(input('Enter a choice, based on the above options: '))
print()
if choice == 1:
vec_angle = float(input('Enter the angle between the two vectors (in degrees): '))
vec_a = int(input('Enter the magnitude of the first vector: '))
vec_b = int(input('Enter the magnitude of the second vector: '))
print('The dot product is:', get_dot_product(vec_angle, vec_a, vec_b), "\n")
elif choice == 2:
num_of_terms = int(input('Enter the number of terms in the series: '))
first_term = int(input('Enter the first term in the series: '))
second_term = int(input('Enter the second term in the series: '))
print(f'The sum of the first {num_of_terms} terms in the series is:', sum_of_terms(num_of_terms, first_term, second_term), "\n")
elif choice == 3:
fib_numb = int(input('Enter which number in the Fibonacci sequence you want to get the value of: '))
print(f'The {fib_numb} number in the Fibonacci sequence is:', get_fibonacci(fib_numb))
elif choice == 4:
fib_terms = int(input('Enter a number of terms in the Fibonacci sequence to display: '))
print(get_num_of_fib(fib_terms))
else:
raise Exception('Invalid Input.') | true |
096ac4e7c999f374495576ced8b6f9ac327a57de | pointmaster2/RagnarokSDE | /SDE/Resources/tut_part2.py | 1,281 | 4.3125 | 4 | """
Tutorial - Part 2
Selection
"""
# You can manipulate the selection of the editor and read its values.
# The example below prints the first three elements of the selected items.
if (selection.Count == 0):
script.throw("Please select an item in the tab!")
for tuple in selection:
print script.format("#{0}, {1}, {2}", tuple[0], tuple[1], tuple[2])
# The above will bring up the console output and show you the result.
# selection contains the items selected.
# script.format() is a useful method to format your output result.
# You can use the currently selected table with the following :
if (selected_db != item_db):
script.throw("Please select the Item tab!")
# To read the values of the table, simply iterate through it like a list.
for tuple in selected_db:
print "Id = " + str(tuple[0])
# This is the same as
for tuple in item_db:
print "Id = " + str(tuple[0])
# Let's say you want to select items from 500 to 560 :
selection.Clear()
for x in range(500, 561): # 561 is not included
if (selected_db.ContainsKey(x)):
selection.Add(selected_db[x])
# Or if you want to select all the potion items...¸
selection.Clear()
for tuple in item_db: # 561 is not included
if ("Potion" in tuple["name"]):
selection.Add(tuple)
| true |
612a5eb267901530782ffe5f82876c970fe34f65 | robseeen/Python-Projects-with-source-code | /Mile_to_KM_Converter_GUI/main.py | 1,119 | 4.34375 | 4 | from tkinter import *
# creating window object
window = Tk()
# Program title
window.title("Miles to Kilometer Converter")
# adding padding to window
window.config(padx=20, pady=20)
# taking user input
miles_input = Entry(width=7)
# grid placement
miles_input.grid(column=2, row=0)
# showing input label
miles_label = Label(text="Miles: ")
# grid placement
miles_label.grid(column=1, row=0)
# another text label
is_equal_label = Label(text="Equal to")
# grid placement
is_equal_label.grid(column=2, row=1)
# kilometer result label, default 0
kilometer_result_label = Label(text="0")
# grid placement
kilometer_result_label.grid(column=2, row=2)
# showing result label
kilometer_label = Label(text="KM:")
# grid placement
kilometer_label.grid(column=1, row=2)
# mile to km calculation
def miles_to_km():
miles = float(miles_input.get())
km = round(miles * 1.609)
kilometer_result_label.config(text=f"{km}")
# calculator button
calculate_button = Button(text="Calculate", command=miles_to_km)
# button placement
calculate_button.grid(column=2, row=3)
# continue run the window object
window.mainloop()
| true |
5cba02efb718d3cfdb85ee3439261fb2fa28cf9f | robseeen/Python-Projects-with-source-code | /average_height_using_for_loop.py | 852 | 4.125 | 4 | # Finding average height using for loop.
# takeing students height and sperated
student_heights = input(
"Input a list of students heights. Seperated by commas.\n => ").split()
# checking the input in list
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# printing the students height list
print(f"Student Height List: {student_heights}")
# total sum of heigth using for loop
total_height = 0
for height in student_heights:
total_height += height
print(f"Total height: {total_height}")
# Total length of students
number_of_students = 0
for student in student_heights:
number_of_students += 1
print(f"Total Number of Students: {number_of_students}")
# Average Height of students
average_height = round(total_height / number_of_students)
print(f"Average Height of Studens: {average_height}")
| true |
530fb79024873eee062a23f2eec7096c00c2c3fc | patidarjp87/python_core_basic_in_one_Repository | /29.Co-Prime.py | 573 | 4.125 | 4 |
print('numbers which do not have any common factor between them,are called co-prime factors')
print('enter a value of a and b')
a=int(input())
b=int(input())
if a>b:
for x in range(2,b+1):
if a%x==0 and b%x==0:
print(a,'&',b,'are not co-prime numbers')
break
else:
continue
if x==b:
print(a,'&',b,'are co-prime numbers')
else:
for x in range(2,a+1):
if a%x==0 and b%x==0:
print(a,'&',b,'are not co-prime numbers')
break
else:
continue
if x==a:
print(a,'&',b,'are co-prime numbers')
input('press enter to exit')
| true |
f8471e2937ec8f64d491a1856f103442e7ec41b3 | patidarjp87/python_core_basic_in_one_Repository | /71.cheacksubset.py | 461 | 4.34375 | 4 |
print("program to check whether a given set is a subset of another given set")
s1=set([eval(x) for x in input('enter elements in superset set 1 as it is as you want to see in your set with separator space\n').split()])
s2=set([eval(x) for x in input('enter elements subset set 2 as it is as you want to see in your set with separator space\n').split()])
if s2.issubset(s1):
print('s2 is a subset of s1')
else:
print("s2 is not a subset of s1")
input()
| true |
d78cd51c22c282a5a5e9c2bdc69442237700985c | patidarjp87/python_core_basic_in_one_Repository | /92.Accoutclass.py | 1,168 | 4.25 | 4 |
print("define a class Account with static variable rate of interest ,instance variable balance and accounr no.make function to set them")
class Account:
def setAccount(self,a,b,rate):
self.accno=a
self.balance=b
Account.roi=rate
def showBalance(self):
print("Balance is ",self.balance)
def showROI(self):
print("rate of interest is",Account.roi)
def showWithdraw(self,withdrawAmount):
if withdrawAmount>self.balance:
print("withdraw unsuccessful...!!! , your account does not have sufficient balance")
else:
print("your request has proceed successfully")
self.balance-=withdrawAmount
def showDeposite(self,Amount):
self.balance+=Amount
s=input("Case deposite successfully...!!! , Type yes to show balance otherwise no")
if s=='yes':
print("Your updated balance is ",self.balance)
acc=Account()
acc.setAccount(101,10000,2)
acc.showBalance()
acc.showROI()
withdrawAmount=eval(input('Enter withdraw amount'))
acc.showWithdraw(withdrawAmount)
Amount=eval(input('Enter a deposite amount'))
acc.showDeposite(Amount)
input()
| true |
776b3c99569733f3f1746eb1dee10bb971d52684 | patidarjp87/python_core_basic_in_one_Repository | /84.countwords.py | 221 | 4.125 | 4 |
print("script to ciunt words in a given string \n Takes somthing returns something\n Enter a string")
s=input()
def count(s):
l=s.split()
return len(l)
print('no. of words in agiven string is ',count(s))
input()
| true |
ca903da90a4a8ce81c24bcc3258259facbef43eb | kapari/exercises | /pydx_oop/adding.py | 629 | 4.15625 | 4 | import datetime
# Class that can be used as a function
class Add:
def __init__(self, default=0):
self.default = default
# used when an instance of the Add class is used as a function
def __call__(self, extra=0):
return self.default + extra
add2 = Add(2)
print(add2(5))
# >> 7
class Person:
def __init__(self, name, birth_date=None):
self.name = name
self.birth_date = birth_date
@property
def days_alive(self):
raturn (datetime.datetime.today() - self.birth_date).days
me = Person(name="Ken", birth_date=datetime.datetime(1981, 5, 23))
print(me.days_alive)
| true |
394e21f7262da6bedbb53a667bc738662033d26a | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/10_GetNodeValue.py | 2,559 | 4.25 | 4 |
"""
Get Node data of the Nth Node from the end.
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the node data of the linked list in the below method.
"""
def GetNode(head, position):
headReverse = Reverse(head)
return GetSpecificNode(headReverse, position).data
def GetSpecificNode(head, position):
current_position = 0
current_node = head
while current_position < position:
#print str(current_position) + " " + str(position - 1)
#print str(current_node.data)
current_node = current_node.next
current_position += 1
return current_node
def Reverse(head):
node = head
# if we don't use a new head, the last node in reversed list is pointed to the first node in origin list
# exp: for an 1->2->3 list, after the first node in reversed list inserted, the list become 1->1->2->3
new_head = None #Node()
while node != None:
new_head = Insert(new_head, node.data) # Forget to assign the latest value to head
node = node.next
return new_head
def Insert(head, data): # Insert to head
new_node = Node(data)
if head == None: # or head.data == None: # if we don't initialize the new_head with Node(), we don't have to check its data
head = new_node
else:
new_node.next = head
head = new_node
return head
"""
This challenge is part of a tutorial track by MyCodeSchool
Youre given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.
Input Format
You have to complete the int GetNode(Node* head, int positionFromTail) method which takes two arguments - the head of the linked list and the position of the node from the tail. positionFromTail will be at least 0 and less than the number of nodes in the list. You should NOT read any input from stdin/console.
Constraints
Position will be a valid element in linked list.
Output Format
Find the node at the given position counting backwards from the tail. Then return the data contained in this node. Do NOT print anything to stdout/console.
Sample Input
1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 0
1 -> 3 -> 5 -> 6 -> NULL, positionFromTail = 2
Sample Output
6
3
""" | true |
d525e7b1fc92767c602e4911fed11253e09d58ff | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/2_InsertANodeAtTheTailOfALinkedList.py | 1,553 | 4.28125 | 4 |
"""
Insert Node at the end of a linked list
head pointer input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method
"""
def Insert(head, data):
new_node = Node(data)
if head == None:
head = new_node
else:
node = head
while node.next != None:
node = node.next
node.next = new_node
return head
"""This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node. The given head pointer may be null, meaning that the initial list is empty.
Input Format
You have to complete the Node* Insert(Node* head, int data) method. It takes two arguments: the head of the linked list and the integer to insert. You should not read any input from the stdin/console.
Output Format
Insert the new node at the tail and just return the head of the updated linked list. Do not print anything to stdout/console.
Sample Input
NULL, data =
--> NULL, data =
Sample Output
2 -->NULL
2 --> 3 --> NULL
Explanation
1. We have an empty list, and we insert .
2. We start with a in the tail. When is inserted, then becomes the tail.
""" | true |
62351503e0025c4fd5c358a16036c52d48eccac6 | Aegis-Liang/Python | /HackerRank/Data Structure/2_LinkedLists/3_InsertANodeAtTheHeadOfALinkedList.py | 1,496 | 4.21875 | 4 | """
Insert Node at the begining of a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def Insert(head, data):
new_node = Node(data)
if head == None:
head = new_node
else:
new_node.next = head
head = new_node
return head
"""
This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
Youre given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer, insert this node at the head of the linked list and return the new head node. The head pointer given may be null meaning that the initial list is empty.
Input Format
You have to complete the Node* Insert(Node* head, int data) method which takes two arguments - the head of the linked list and the integer to insert. You should NOT read any input from stdin/console.
Output Format
Insert the new node at the head and return the head of the updated linked list. Do NOT print anything to stdout/console.
Sample Input
NULL , data = 1
1 --> NULL , data = 2
Sample Output
1 --> NULL
2 --> 1 --> NULL
Explanation
1. We have an empty list, on inserting 1, 1 becomes new head.
2. We have a list with 1 as head, on inserting 2, 2 becomes the new head.
""" | true |
9d11b885c5188412b5ed481fea5a49878ae3753e | sangzzz/AlgorithmsOnStrings | /week3&4_suffix_array_suffix_tree/01 - Knuth Morris Pratt/kmp.py | 905 | 4.1875 | 4 | # python3
import sys
def find_pattern(pattern, text):
"""
Find all the occurrences of the pattern in the text
and return a list of all positions in the text
where the pattern starts in the text.
"""
result = []
# Implement this function yourself
text = pattern + '$' + text
s = [0 for _ in range(len(text))]
border = 0
for i in range(1, len(text)):
while border > 0 and text[i] != text[border]:
border = s[border - 1]
if text[i] == text[border]:
border = border + 1
else:
border = 0
s[i] = border
l = len(pattern)
for j, i in enumerate(s[l + 1:]):
if i == l:
result.append(j-l+1)
return result
if __name__ == '__main__':
pattern = input().strip()
text = input().strip()
result = find_pattern(pattern, text)
print(" ".join(map(str, result)))
| true |
60dcba72cc85538aab4f58ddcd1a989e940f9522 | bhargav-makwana/Python-Corey-Schafer | /Practise-Problems/leap_year_functions.py | 654 | 4.3125 | 4 | # Program : Finding the days in the year
# Input : days_in_month(2015, 3)
# Output :
# Numbers of days per month. 0 is used as a placeholder for indexing purposes.
month_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(year):
""" Return True for leap years, False for non-leap years"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
""" Returns no of days in that month in that year. """
if not 1 <= month <= 12:
return 'Invalid Month'
if month == 2 and is_leap(year):
return 29
return month_days[month]
print(is_leap(2010))
print(days_in_month(2010,2)) | true |
7eb795b0920e210e7ff11317e1ba199129013837 | HypeDis/DailyCodingProblem-Book | /Email/81_digits_to_words.py | 1,058 | 4.21875 | 4 | """
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent.
You can assume each valid number in the mapping is a single digit.
For example if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should return [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf"].
"""
from collections import deque
digitMap = {
2: ['a', 'b', 'c'],
3: ['d', 'e', 'f'],
4: ['g', 'h', 'i'],
5: ['j', 'k', 'l'],
6: ['m', 'n', 'o'],
7: ['p', 'q', 'r', 's'],
8: ['t', 'u', 'v'],
9: ['w', 'x', 'y', 'z'],
}
def numberToWords(num):
res = deque([''])
while num:
# working backwards from ones leftwards
digit = num % 10
num = num // 10
queLen = len(res)
for _ in range(queLen):
curStr = res.popleft()
for char in digitMap[digit]:
res.append(char + curStr)
return list(res)
print(numberToWords(253))
| true |
a4450612113faaf8813c6163c461fc483f05bb63 | HypeDis/DailyCodingProblem-Book | /Chapter-5-Hash-Table/5.2-Cut-Brick-Wall.py | 972 | 4.125 | 4 | """
A wall consists of several rows of bricks of various integer lengths and uniform height. Your goal is to find a vertical line going from the top to the bottom of the wall that cuts through the fewest number of bricks. If the line goes through the edge between two bricks, this does not count as a cut.
"""
from collections import defaultdict
wall = [
[3, 5, 1, 1],
[2, 3, 3, 2],
[5, 5],
[4, 4, 2],
[1, 3, 3, 3],
[1, 1, 6, 1, 1]
]
def fewest_cuts(wall):
cuts = defaultdict(int)
for row in wall:
length = 0
for brick in row[:-1]:
length += brick
cuts[length] += 1
maxLines = 0
maxPosition = None
for position in cuts:
if cuts[position] > maxLines:
maxLines = cuts[position]
maxPosition = position
totalRows = len(wall)
print(
f'the optimal position is {maxPosition}, with {totalRows - maxLines} cuts required')
fewest_cuts(wall)
| true |
a18a302670bdb1c93bcf41783c1f3763d261c716 | HypeDis/DailyCodingProblem-Book | /Chapter-3-Linked-Lists/3.1-Reverse-Linked-List.py | 987 | 4.125 | 4 | from classes import LinkedList
myLinkedList = LinkedList(10)
def reverse(self):
self.reverseNodes(None, self.head)
LinkedList.reverse = reverse
def reverseNodes(self, leftNode, midNode):
# basecase reach end of list
if not midNode.next:
self.head = midNode
else:
self.reverseNodes(midNode, midNode.next)
midNode.next = leftNode
LinkedList.reverseNodes = reverseNodes
def reverseNonRecursive(self):
prev, current = None, self.head
while current is not None:
temp = current.next
current.next = prev
prev = current
current = temp
self.head = prev
LinkedList.reverseNonRecursive = reverseNonRecursive
myLinkedList.insert(20)
myLinkedList.insert(15)
myLinkedList.insert(91)
print(myLinkedList.listNodes())
myLinkedList.reverse()
print(myLinkedList.listNodes())
myLinkedList.reverseNonRecursive()
print(myLinkedList.listNodes())
myLinkedList.reverseNonRecursive()
print(myLinkedList.listNodes())
| true |
a717b09b4d4d486e3a05b5a9046fe396a9d65959 | Jorza/pairs | /pairs.py | 1,367 | 4.28125 | 4 | def get_pair_list():
while True:
try:
# Get input as a string, turn into a list
pairs = input("Enter a list of integers, separated by spaces: ")
pairs = pairs.strip().split()
# Convert individual numbers from strings into integers
for i in range(len(pairs)):
pairs[i] = int(pairs[i])
return pairs
except ValueError:
# Go back to the start if the input wasn't entered correctly
print("Invalid input")
def find_pairs(the_list):
# Sum odd => one value even, one value odd
# Product even => one value even
# The condition for the odd sum guarantees an even product.
# Therefore, only need to check the sum.
# Split list into even and odd values
even_list = []
odd_list = []
for item in the_list:
new_list = even_list if item % 2 == 0 else odd_list
new_list.append(item)
# Find all pairs with one item from the even list and one item from the odd list
pairs = []
for odd_item in odd_list:
for even_item in even_list:
pairs.append([odd_item, even_item])
return pairs
def print_pairs(pairs):
for pair in pairs:
print(pair)
if __name__ == "__main__":
print_pairs(find_pairs(get_pair_list()))
| true |
3c0042882117531431b5d27506e5bf602c92e3d3 | henrikgruber/PythonSIQChallenge | /Skill2.3_Friederike.py | 936 | 4.53125 | 5 | # Create 3 variables: mystring, myfloat and myint.
# mystring should contain the word "hello.The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.
# Finally, print all 3 variables by checking if mystring equals to "hello" then print it out. You then check if myfloat is really a float number and is equal to 10.0 - then you print it out (if both conditions are satisfied)
# And you do the same for int
mystring = "Hello"
myfloat= "string"
myint= 20
# mystring
if (type(mystring) is str) == True:
print(mystring)
elif (type(mystring) is str) != True:
print("No string")
# myfloat
if (type(myfloat)is float) == True:
print(myfloat)
elif (type(myfloat)) != True:
print("No float")
#myint
if (type(myint)is int) == True:
print(myint)
elif (type(myint)is int) != True:
print("No int") | true |
b44f4f5367ae2c8cb39de98e003dc9454d82970a | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill4.3_Vanessa.py | 1,028 | 4.78125 | 5 | #In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method.
# Create 3 lists: numbers, strings and names
numbers = []
strings = []
names = []
# Add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings variable
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("hello")
strings.append("world")
# Add names John, Eric and Jessica to strings list
names.append("John")
names.append("Eric")
names.append("Jessica")
#Create a new variable third_name with the third name taken from names list, using the brackets operator []. Note that the index is zero-based, so if you want to access the second item in the list, its index will be 1.
third_name = names[2]
# At the end print all lists and one variable created.
print("This is the list of numbers:", numbers)
print("This is the list of strings:", strings)
print("This is the list of names:", names)
print("This is the third name in the list of names:", third_name) | true |
b659d2d761ee8c0df61154e0497ddcf5a1fe2a80 | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill 2.3 Tamina.py | 777 | 4.40625 | 4 | # Create 3 variables: mystring, myfloat and myint.
# mystring should contain the word "hello.The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.
# Finally, print all 3 variables by checking if mystring equals to "hello" then print it out. You then check if myfloat is really a float number and is equal to 10.0 - then you print it out (if both conditions are satisfied)
# And you do the same for int
mystring = input ("Please enter a string ")
myfloat = input ("please enter a float number ")
myint = input ("Please enter an integer ")
try:
val = str(mystring)
if mystring == "Hello":
print (mystring)
break;
else:
print ("Error")
| true |
1b65e04c12a9b0c1df4be645bb0b841c96a67277 | henrikgruber/PythonSIQChallenge | /#2 Put your solutions here/Skill1.4_Vanessa.py | 512 | 4.25 | 4 | # This program finds the number of day of week for K-th day of year
print("Enter the day of the year:")
K = int(input())
a = (K % 7) + 3
if a == 0:
print("This day is a Sunday")
if a == 1:
print("This day is a Monday")
if a == 2:
print("This day is a Tuesday")
if a == 3:
print("This day is a Wednesday")
if a == 4:
print("This day is a Thursday")
if a == 5:
print("This day is a Friday")
if a == 6:
print("This day is a Saturday")
| true |
364341e055538b367469d9075147b32a326b1cbf | janettem/Coding-Challenges | /finding_adjacent_nodes/finding_adjacent_nodes.py | 879 | 4.15625 | 4 | def are_adjacent_nodes(adjacency_matrix: list, node1: int, node2: int) -> bool:
if adjacency_matrix[node1][node2] == 1:
return True
return False
def test():
adjacency_matrix1 = [[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0]]
adjacency_matrix2 = [
[0, 1, 0, 1, 1],
[1, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[1, 0, 0, 1, 0],
]
print(are_adjacent_nodes(adjacency_matrix1, 0, 1)) # -> True
print(are_adjacent_nodes(adjacency_matrix1, 0, 2)) # -> False
print(are_adjacent_nodes(adjacency_matrix2, 0, 3)) # -> True
print(are_adjacent_nodes(adjacency_matrix2, 1, 4)) # -> False
print(are_adjacent_nodes(adjacency_matrix1, 2, 3)) # -> True
print(are_adjacent_nodes(adjacency_matrix2, 0, 2)) # -> False
def main():
test()
if __name__ == "__main__":
main()
| false |
d42b959e448133ca39a6798c38daa06c90bb86d1 | pombredanne/Rusthon | /regtests/c++/returns_subclasses.py | 1,443 | 4.125 | 4 | '''
returns subclasses
'''
class A:
def __init__(self, x:int):
self.x = x
def method(self) -> int:
return self.x
class B(A):
def foo(self) ->int:
return self.x * 2
class C(A):
def bar(self) ->int:
return self.x + 200
class D(C):
def hey(self) ->int:
return self.x + 1
def some_subclass( x:int ) ->A:
switch x:
case 0:
a = A(1)
return a
case 1:
b = B(2)
return b
case 2:
c = C(3)
return c
case 3:
d = D(4)
return d
def main():
a = some_subclass(0)
b = some_subclass(1)
c = some_subclass(2)
d = some_subclass(3)
print(a.getclassname())
print(b.getclassname())
print(c.getclassname())
print(d.getclassname())
print(a.method())
print a.x
print(b.method())
print b.x
print(c.method())
print c.x
print(d.method())
print d.x
print('- - - - - - - ')
if isinstance(b, B):
print('b is type B')
print(b.method())
print(b.foo())
else:
print('error: b is not type B')
if isinstance(c, C):
print('c is type C')
print(c.method())
print(c.bar())
else:
print('error: c is not type C')
if isinstance(d, D):
print('d is type D')
#print(d.bar()) ## TODO, subclass from C.
print(d.hey())
else:
print('error: d is not type D')
print('------------------')
for i in range(3):
o = some_subclass(i)
print(o.method())
if isinstance(o, B):
print(o.foo())
if isinstance(o,C): ## TODO-FIX elif isinstance(o,C)
print(o.bar())
print('end of test') | false |
8b8a0b92e6e0697c486e0cdda96874934e4e48f0 | Sadashiv/interview_questions | /python/string_set_dictionary.py | 2,945 | 4.34375 | 4 | string = """
Strings are arrays of bytes representing Unicode characters.
Strings are immutable.
"""
print string
#String Operations details
str = "Hello Python"
str1 = "World"
print "String operations are started"
print str.capitalize()
print str.center(20)
print str.count('o')
print str.decode()
print str.encode()
print str.endswith('Python')
print str.expandtabs(12)
print str.find('P')
print str.format()
print str.index('y')
print str.isalnum()
print str.isalpha()
print str.isdigit()
print str.islower()
print str.isspace()
print str.istitle()
print str.isupper()
print str.lower()
print str.ljust(5)
print str.lstrip()
print str.partition('P')
print str.rfind('o')
print str.replace('o','r')
print str.rindex('o')
print str.rjust(20)
print str.rpartition('P')
print str.rsplit('P')
print str.rstrip('P')
print str.split('P')
print str.splitlines()
print str.startswith('Hello')
print str.strip()
print str.swapcase()
print str.title()
print str.upper()
print str.zfill(20)
print str.join(str1)
print str[0]
print str[6]
print str[-1]
print str[:]
print str[2:]
print str[:6]
print str[2:7]
print str[2:-2]
print "String operations are completed"
print ""
print "Sets details are started from here"
set_1 = """
A set is an unordered collection of items.
Every element is unique and must be immutable.
"""
print set_1
#set Operations details
print "Sets operations are started"
s = {1,2,3,4,3,2}
print s
set1 = {1,3}
set1.add(2)
print set1
set1.update([2,3,4])
print set1
set1.update([4,5], {1,6,8})
print set1
set1.discard(6)
print set1
set1.remove(8)
print set1
set2 = {"HelloWorld"}
print set2
set2.clear()
print set2
A = {1,2,3,4,5}
B = {4,5,6,7,8}
print(A|B)
print(A.union(B))
print(B.union(A))
print(A&B)
print(A.intersection(B))
print(B.intersection(A))
print(A-B)
print(B-A)
print(A.difference(B))
print(B.difference(A))
print(A^B)
print(B^A)
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
print "Sets operations are completed"
print ""
print "Dictionary details are started from here"
Dictionary = """
Python dictionary is an unordered collection of items.
a dictionary has a key:value pair.
"""
print Dictionary
#Dictionary Operations details
print "Dictionary operations are started"
dict = {'name':'Ramesh', 'age':28}
print dict.copy()
print dict.fromkeys('name')
print dict.fromkeys('age')
print dict.fromkeys('name','age')
print dict.get('name')
print dict.has_key('name')
print dict.has_key('Ramesh')
print dict.items()
for i in dict.iteritems():
print i
for i in dict.iterkeys():
print i
for i in dict.itervalues():
print i
print dict.keys()
print dict.values()
print dict.viewitems()
print dict.viewkeys()
print dict.viewvalues()
dict['name'] = 'Ram'
print dict
dict['age'] = 29
print dict
dict['address'] = 'Bijapur'
print dict
dict1 = {1:1, 2:4, 3:9, 4:16, 5:25}
print dict1.pop(4)
print dict1.popitem()
print dict1[5]
print dict1.clear()
print "Dictionary operations are completed" | true |
141f5d9eeb1020a83a79299fc7d3b93637058c83 | capncrockett/beedle_book | /Ch_03 - Computing with Numbers/sum_a_series.py | 461 | 4.25 | 4 | # sum_a_series
# A program to sum up a series of numbers provided from a user.
def main():
print("This program sums up a user submitted series of numbers.")
number_count = int(input("How many numbers will we be summing"
"up today? "))
summed = 0
for i in range(number_count):
x = float(input("Enter a number: "))
summed += x
print("The sum of the numbers is ", summed)
main()
| true |
80f931032dd8fbee7d859a1f04b9d2707d233227 | capncrockett/beedle_book | /Ch_03 - Computing with Numbers/triangle_area.py | 492 | 4.3125 | 4 | # triangle_area.py
# Calculates the area of a triangle.
import math
def main():
print("This program calculates the area of a triangle.")
print()
a = float(input("Please enter the length of side a: "))
b = float(input("Please enter the length of side b: "))
c = float(input("Please enter the length of side c: "))
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("The area of your triangle is ", area)
main()
| true |
b30b0e17c9c907d54c1d4e99b68c0580a00808c4 | capncrockett/beedle_book | /Ch_07 - Decision Structures/valid_date_func.py | 1,101 | 4.46875 | 4 | # valid_date_func.py
# A program to check if user input is a valid date. It doesn't take
# into account negative numbers for years.
from leap_year_func import leap_year
def valid_date(month: int, day: int, year: int) -> bool:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if 1 <= month <= 12:
# Month is OK. Move on.
# Determine last day in month.
if month == 2:
if leap_year(year):
last_day = 29
else:
last_day = 28
else:
last_day = days_in_month[month - 1]
# if day is also good, return True
if 1 <= day <= last_day:
return True
else:
return False
# def main():
# print("This program determines if a date input is valid.")
# month, day, year = input("Enter a date in format MM/DD/YYYY: ").split("/")
#
# if valid_date(int(month), int(day), int(year)):
# print("Date Valid.")
# else:
# print("Date is Invalid")
#
#
# for i in range(10):
# main()
| true |
b19f9c63a4c64753fc1c46a61177d05a0e08570b | capncrockett/beedle_book | /Ch_06 - Functions/sum_time.py | 545 | 4.25 | 4 | # sum_time.py
def sum_up_to(n):
summed = 0
for i in range(1, n + 1):
summed += i
print(f"The sum is {summed}.")
def sum_up_cubes(n):
summed = 0
for s in range(1, n + 1):
summed += s ** 3
print(f"The sum of the cubes is {summed}")
def main():
print("This program sums up the first n natural numbers and the \n"
"sum of the cubes of the first n natural numbers.\n")
n = int(input("Please enter a value for n: "))
sum_up_to(n)
sum_up_cubes(n)
main()
| true |
cd407e24b339ed7a4c42847457e538505cbcd63f | capncrockett/beedle_book | /Ch_02 - IDLE Examples/distance_converters.py | 575 | 4.34375 | 4 | # This program converts distances
def kilometers_miles():
print("This function converts kilometers to miles.")
kilometers = eval(input("Enter the distance in kilometers: "))
miles = kilometers * 0.62
print("The distance in miles is", miles)
def fahrenheit_kelvin():
print("This function converts Fahrenheit to Kelvin.")
fahrenheit = eval(input("Enter the temperature in Fahrenheit: "))
kelvin = (fahrenheit - 32) * 5 / 9 + 273.15
print("{} F is equal to {} Kelvin.".format(fahrenheit, kelvin))
fahrenheit_kelvin()
| false |
5c05feac6d95a6375275bc8ddb69d96fcd253f9b | capncrockett/beedle_book | /Ch_07 - Decision Structures/pay_rate_calc.py | 583 | 4.25 | 4 | # pay_rate_calc.py
# Program to calculate an employees pay rate, including overtime.
def main():
hours = eval(input("Enter employee total hours: "))
pay_rate = eval(input("Enter employee pay rate: "))
if hours <= 40:
pay = pay_rate * hours
print(f"Total pay = ${pay:0.2f}")
else:
base_pay = 40 * pay_rate
overtime = (hours - 40) * (pay_rate * 1.5)
print(f"Base pay = ${base_pay:0.02f}\n"
f"Overtime = ${overtime:0.02f}\n"
f"Total pay = ${base_pay + overtime:0.02f}")
main()
| true |
f759d2714063a7520a42a45e4ca8b4bf58d53e37 | capncrockett/beedle_book | /Ch_08 - Loop Structures and Booleans/prime_checker.py | 720 | 4.34375 | 4 | # prime_checker.py
# A positive number n > 2 is prime if no num between 2 and
# the sqrt of n (inclusive) evenly divides n.
import math
def prime_check(n):
sqrt_n = int(math.sqrt(n))
if n > 2:
if n == 3:
print("3 is prime")
for i in range(2, sqrt_n + 1):
if n % i == 0:
print(f"{n} can be divided by {i}")
break
elif n % i != 0 and i == sqrt_n:
print(f"{n} is prime")
def main():
print("This program checks to see if a number is prime.\n")
x = int(input("Enter a positive, whole number greater than 2 >> "))
prime_check(x)
if __name__ == '__main__':
main()
| false |
e9543a36d3cc89e88294035db335cf273c7b037a | capncrockett/beedle_book | /Ch_05 - Sequences/average_word_len.py | 998 | 4.3125 | 4 | # average_word_len
# Find the average word length of a sentence.
def main():
print("This program finds the average word length of a sentence.")
print()
sentence = input("Type a sentence: ")
word_count = sentence.count(' ') + 1
words = sentence.split()
letter_count = 0
for letters in words:
letter_count = letter_count + len(letters)
avg_word_length = letter_count // word_count
print(f"Letter count: {letter_count} ")
print(f"Word count: {word_count}")
print(f"Average word length: {avg_word_length}")
main()
# # c05ex10.py
# # Average word length
#
#
# def main():
# print("Average word length")
# print()
#
# phrase = input("Enter a phrase: ")
#
# # using accumulator loop
# count = 0
# total = 0
# for word in phrase.split():
# total = total + len(word)
# count = count + 1
#
# print("Average word length", total / count)
#
#
# main()
| true |
a7a921940f1cedee399c3d732f7a2cb4869979ef | DaanvanMil/INFDEV02-1_0892773 | /assignment6pt3/assignment6pt3/assignment6pt3.py | 367 | 4.25 | 4 | x = input ("how many rows? ")
printed = ("") #The printing string
n = x + 1 #Make sure it is x rows becasue of the range
for a in range(n): #Main for loop which prints n amount of lines
for b in range(a): #For loop which adds a amount of asterisks per line
printed += '*'
printed += '\n'
print printed | true |
4c687faa942587e54da9a4e4cdcc491865c93b82 | Billoncho/TurtelDrawsTriangle | /TurtleDrawsTriangle.py | 684 | 4.4375 | 4 | # TurtleDrawsTriangle.py
# Billy Ridgeway
# Creates a beautiful triangle.
import turtle # Imports turtle library.
t = turtle.Turtle() # Creates a new pen called t.
t.getscreen().bgcolor("black") # Sets the background to black.
t.pencolor("yellow") # Sets the pen's color to yellow.
t.width(2) # Sets the pen's width to 2.
t.shape("turtle") # Sets the shape of the pen to a turtle.
for x in range(100): # Sets the range of x to 100.
t.forward(3*x^2) # Moves the pen forward 3 times the value of x squared.
t.left(120) # Turns the pen left 120 degrees.
| true |
55eb79671bcc26fb01f38670730e7c71b5e0b6ff | vymao/SmallProjects | /Chess/ChessPiece.py | 956 | 4.125 | 4 | class ChessPiece(object):
"""
Chess pieces are what we will add to the squares on the board
Chess pieces can either moves straight, diagonally, or in an l-shape
Chess pieces have a name, a color, and the number of squares it traverses per move
"""
Color = None
Type = None
ListofPieces = [ "Rook", "Knight", "Pawn", "King", "Queen", "Bishop" , "Random"]
def __init__(self, dict_args):
""" Constructor for a new chess piece """
self.Type = dict_args["Type"]
self.Color = dict_args["Color"]
def __str__(self):
""" Returns the piece's string representation as the first letter in each word
example: bN - black knight, wR - white rook"""
if self.Type in ["Rook", "Knight", "Pawn", "King", "Queen", "Bishop"]:
color = self.Color[0]
if(self.Type != "Knight"):
pieceType = self.Type[0]
else:
pieceType = "N"
return color.lower() + pieceType.upper()
else:
return " "
| true |
49e452747a9a019aec7cef09fd23abb9eb2ce101 | hwang-17/forpythonstudy | /contact_list.py | 1,407 | 4.1875 | 4 | '''
this is a practice of dict from fishC forum
'''
print('§---欢迎使用通讯录程序---§')
print('§---1:查询联系人资料---§')
print('§---2:添加新的联系人---§')
print('§---3:删除已有联系人---§')
print('§---4:退出通讯录程序---§')
contacts = dict()
while 1:
instr = int(input('\n请输入相关的指令代码:'))
if instr == 1:
name = input('请输入联系人姓名')
if name in contacts:
print(name+':' + contacts[name])
else:
print('没有该联系人')
if instr == 2:
name = input('请输入联系人姓名')
if name in contacts:
print('联系人已经存在-->>', end='') # end='' 是末尾不换行的意思哈
print(name+':'+contacts[name])
if input('是否修改用户资料(YES/NO):')=="YES":
contacts[name]=input('请输入用户电话号码')
else:
contacts[name]=input('请输入新用户电话号码')
if instr == 3:
name = input('请输入要删除的联系人姓名:')
if name in contacts:
del(contacts[name]) # you also can use dict.pop(). del here is used to delete a element in dict
else:
print('您输入的用户不存在喔喔喔哦')
if instr == 4:
break
print('---thank you for using this application---')
| false |
d8bc071aba1c639a3d17a2b87ccd45f51530da3d | ronny-souza/Lista-Exercicios-04-Python | /Exercicio02.py | 1,107 | 4.1875 | 4 | # QUESTÃO 02 - Faça um programa que percorre uma lista com o seguinte formato:
# [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], 'Itália', 'Espanha', [7,8]]].
# Essa lista indica o número de faltas que cada time fez em cada jogo. Na lista acima, no jogo entre Brasil e
# Itália, o Brasil fez 10 faltas e a Itália fez 9. O programa deve imprimir na tela:
# (a) o total de faltas do campeonato
# (b) o time que fez mais faltas
# (c) o time que fez menos faltas
tabelaFaltas = [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], 'Itália', 'Espanha', [7,8]]
totalFaltas = tabelaFaltas[0][2][0] + tabelaFaltas[0][2][1] + tabelaFaltas[1][2][0] + tabelaFaltas[1][2][1] + tabelaFaltas[4][0] + tabelaFaltas[4][1]
timeMaisFaltas = tabelaFaltas[0][0]
timeMenosFaltas = tabelaFaltas[1][0]
print(f"O total de faltas do campeonato foi: {totalFaltas}")
print(f"O time que mais cometeu faltas foi: {timeMaisFaltas} no jogo {tabelaFaltas[0][0]} X {tabelaFaltas[0][1]}")
print(f"O time que menos cometeu faltas foi: {timeMenosFaltas} no jogo {tabelaFaltas[1][0]} X {tabelaFaltas[1][1]}") | false |
01099d699d3e8b9919b117704f36d1c95ee75bcc | mitalijuneja/Python-1006 | /Homework 5/engi1006/advanced/pd.py | 1,392 | 4.1875 | 4 |
#########
# Mitali Juneja (mj2944)
# Homework 5 = statistics functionality with pandas
#
#########
import pandas as pd
def advancedStats(data, labels):
'''Advanced stats should leverage pandas to calculate
some relevant statistics on the data.
data: numpy array of data
labels: numpy array of labels
'''
# convert to dataframe
df = pd.DataFrame(data)
# print skew and kurtosis for every column
skew = df.skew(axis = 0)
kurt = df.kurtosis(axis = 0)
for col in range(df.shape[1]):
print("Column {} statistics".format(col))
print("\tSkewness = {}\tKurtosis = {}".format(skew[col], kurt[col]))
# assign in labels
df["labels"] = labels
print("\n\nDataframe statistics")
# groupby labels into "benign" and "malignant"
mean = df.groupby(["labels"]).mean().T
sd = df.groupby(["labels"]).std().T
# collect means and standard deviations for columns,
# grouped by label
b_mean = mean.iloc[:,0]
m_mean = mean.iloc[:,-1]
b_sd = sd.iloc[:,0]
m_sd = sd.iloc[:,-1]
# Print mean and stddev for Benign
print("Benign Stats:")
print("Mean")
print(b_mean)
print("SD")
print(b_sd)
print("\n")
# Print mean and stddev for Malignant
print("Malignant Stats:")
print("Mean")
print(m_mean)
print("SD")
print(m_sd)
| true |
bd367cea336727a2ccbd217e8e201aad6ab42391 | Eddie02582/Leetcode | /Python/069_Sqrt(x).py | 1,565 | 4.40625 | 4 | '''
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
'''
class Solution(object):
def mySqrt_build(self, x):
"""
:type x: int
:rtype: int
"""
return int(x**0.5)
'''
y**2=x
logy**2=logx
2logy=logx
y=10**(0.5*logx)
'''
def mySqrt_log(self, x):
import math
if x==0 :
return 0
return int( 10**(0.5 *math.log10(x)))
#Using Newton's method:
def mySqrt(self, x):
result = 1
if x == 0 :
return 0
while abs(result * result - x) >0.1:
result=(result + float(x) / result) /2
return int(result)
#Binary
def mySqrt(self, x: int) -> int:
l = 0
r = x
while l < r:
mid = (l + r + 1) // 2
if mid * mid == x:
return mid
elif mid * mid > x:
r = mid - 1
else:
l = mid
return r
sol =Solution()
assert sol.mySqrt(4)==2
assert sol.mySqrt(8)==2
assert sol.mySqrt(1)==1
assert sol.mySqrt(0)==0 | true |
ef5e3b08084b712e924f564ec05a235e157ce482 | Eddie02582/Leetcode | /Python/003_Longest Substring Without Repeating Characters.py | 2,886 | 4.125 | 4 | '''
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
'''
#!/usr/bin/python
# encoding=utf-8
class Solution:
'''
另用map 紀錄出現字母,right指針向右,如果沒出現就紀錄長度
,當出現過的字母,left 指針就跑到重複出現字母的位置
'''
def lengthOfLongestSubstring(self, s):
left,right,max_length=0,0,0
maps = set()
while right < len(s):
if s[right] not in maps:
maps.add(s[right])
right += 1
else:
maps.remove(s[left])
left += 1
max_length = max(right-left,max_length)
return max_length
def lengthOfLongestSubstring_array(self, s):
locations = [0]*256
l,r=0,-1
res = 0
while l < len(s):
if r + 1 < len(s) and not locations[ord(s[r +1])]:
r += 1
locations[ord(s[r])] += 1
else:
locations[ord(s[l])] -= 1
l += 1
res =max(res,r - l + 1)
return res
def lengthOfLongestSubstring(self, s):
if not s:
return 0
position = [-1] * 256
res = 0
l ,r = 0 ,0
while r < len(s) :
index = ord(s[r])
if position[index] >= l:
l = position[index] + 1
res = max(res ,r - l + 1)
position[index] = r
r += 1
return res
def lengthOfLongestSubstring_map(self, s):
if not s:
return 0
if len(s) <= 1:
return len(s)
locations = [-1 for i in range(256)]
index = -1
m = 0
for i, v in enumerate(s):
if locations[ord(v)] > index:
index = locations[ord(v)]
m = max(m, i - index)
locations[ord(v)] = i
return m
sol =Solution()
assert sol.lengthOfLongestSubstring('abcabcbb')==3
assert sol.lengthOfLongestSubstring('abcbcbb')==3
assert sol.lengthOfLongestSubstring('bbbbb')==1
assert sol.lengthOfLongestSubstring_map('pwwkew')==3
assert sol.lengthOfLongestSubstring(' ')==1
assert sol.lengthOfLongestSubstring('au')==2
| true |
b34977331a8f620c267ae294ddf3977cccf3f8f9 | ratansingh98/design-patterns-python | /factory-method/FactoryMethod.py | 1,328 | 4.34375 | 4 | #
# Python Design Patterns: Factory Method
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
# 2016
#
# Source code is licensed under MIT License
# (for more details see LICENSE)
#
import sys
#
# Product
# products implement the same interface so that the classes
# can refer to the interface not the concrete product
#
class Product:
def getName(self):
pass
#
# Concrete Products
# define product to be created
#
class ConcreteProductA(Product):
def getName(self):
return "type A"
class ConcreteProductB(Product):
def getName(self):
return "type B"
#
# Creator
# contains the implementation for all of the methods
# to manipulate products except for the factory method
#
class Creator:
def createProductA(self):
pass
def createProductB(self):
pass
#
# Concrete Creator
# implements factory method that is responsible for creating
# one or more concrete products ie. it is class that has
# the knowledge of how to create the products
#
class ConcreteCreator(Creator):
def createProductA(self):
return ConcreteProductA()
def createProductB(self):
return ConcreteProductB()
if __name__ == "__main__":
creator = ConcreteCreator()
p1 = creator.createProductA()
print("Product: " + p1.getName())
p2 = creator.createProductB()
print("Product: " + p2.getName())
| true |
5513562b84170f92d6581dc1da83414705338443 | ratansingh98/design-patterns-python | /abstract-factory/AbstractFactory.py | 1,921 | 4.28125 | 4 | #
# Python Design Patterns: Abstract Factory
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
# 2016
#
# Source code is licensed under MIT License
# (for more details see LICENSE)
#
import sys
#
# Product A
# products implement the same interface so that the classes can refer
# to the interface not the concrete product
#
class ProductA:
def getName(self):
pass
#
# ConcreteProductAX and ConcreteProductAY
# define objects to be created by concrete factory
#
class ConcreteProductAX(ProductA):
def getName(self):
return "A-X"
class ConcreteProductAY(ProductA):
def getName(self):
return "A-Y"
#
# Product B
# same as Product A, Product B declares interface for concrete products
# where each can produce an entire set of products
#
class ProductB:
def getName(self):
pass
#
# ConcreteProductBX and ConcreteProductBY
# same as previous concrete product classes
#
class ConcreteProductBX(ProductB):
def getName(self):
return "B-X"
class ConcreteProductBY(ProductB):
def getName(self):
return "B-Y"
#
# Abstract Factory
# provides an interface for creating a family of products
#
class AbstractFactory:
def createProductA(self):
pass
def createProductB(self):
pass
#
# Concrete Factories
# each concrete factory create a family of products and
# client uses one of these factories
#
class ConcreteFactoryX(AbstractFactory):
def createProductA(self):
return ConcreteProductAX()
def createProductB(self):
return ConcreteProductBX()
class ConcreteFactoryY(AbstractFactory):
def createProductA(self):
return ConcreteProductAY()
def createProductB(self):
return ConcreteProductBY()
if __name__ == "__main__":
factoryX = ConcreteFactoryX()
factoryY = ConcreteFactoryY()
p1 = factoryX.createProductA()
print("Product: " + p1.getName())
p2 = factoryY.createProductA()
print("Product: " + p2.getName())
| true |
7dc4a7cd2f0cea643673ee0ace3ccd2b8b5cf117 | bliiir/python_fundamentals | /16_variable_arguments/16_01_args.py | 345 | 4.1875 | 4 | '''
Write a script with a function that demonstrates the use of *args.
'''
def my_args(*args):
'''Print out the arguments received
'''
print('These are the arguments you gave me: \n')
for arg in args:
print(arg)
# Call the my_args function with a string, a number and a copy of itself
my_args('a string', 4, my_args)
| true |
80af3874703bc28aa1707bb080aa25c332d5569a | YCullen/LeetcodePractice | /0_RotateMatrix.py | 533 | 4.125 | 4 | import pdb
def rotate(matrix):
# 矩阵转90度的本质是把第i行换到第-i列
N = len(matrix)
matrix_copy = [[0 for i in range(N)] for j in range(N)]
for i in range(N):
for j in range(N):
matrix_copy[i][j] = matrix[i][j]
for i in range(N):
tmp = matrix_copy[i]
for j in range(N):
matrix[j][N-1-i] = tmp[j]
return matrix
if __name__ == "__main__":
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
ans = rotate(matrix)
print(ans)
| false |
cf1d92c0821e5bc526fb920787b2306f18f5358e | GilliamD/Digital-Crafts-Day-4 | /day_of_the_week.py | 320 | 4.28125 | 4 | day = int(input("Day 0-6? "))
if day == 0:
print("Sunday")
elif day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("day")
else:
print("Thats\'s not a day, Bud.") | false |
609fc7970d1e8a9a1fc194c10d0ae73975e6c428 | jfeidelb/Projects | /PythonTextGame.py | 2,237 | 4.34375 | 4 | from random import randint
import operator
print("This is an educational game where you will answer simple math questions.")
print("How many questions would you like to answer?")
questionInput = input()
def MathQuestion(questionInput):
questionLoop = 0
score = 0
try:
#loop to control number of questions
while questionLoop < int(questionInput):
value1 = randint(1, 20)
value2 = randint(1, 20)
#variable to assign mathematical operation
operationVariable = randint(0, 3)
if operationVariable == 0:
correctMathAnswer = operator.add(value1, value2)
operation = "+"
elif operationVariable == 1:
correctMathAnswer = operator.sub(value1, value2)
operation = "-"
elif operationVariable == 2:
correctMathAnswer = operator.mul(value1, value2)
operation = "*"
elif operationVariable == 3:
while value1 % value2 != 0:
value1 = randint(1, 20)
value2 = randint(1, 20)
correctMathAnswer = operator.truediv(value1, value2)
operation = "/"
print()
#asking the math question to the user
print("What is " + str(value1) + operation + str(value2) + "?")
userInput = input()
try:
#checks the users answer with the correct answer
if float(userInput) == correctMathAnswer:
print("Yes! That is the correct answer!")
score += 1
print("Your score is: " + str(score))
else:
print("That is not the correct answer.")
print("Your score is: " + str(score))
#except statement to ensure a number is answered
except ValueError:
print("Please enter a numerical answer.")
questionLoop += 1
#except statement to ensure a number is entered
except ValueError:
print("Please enter a number!")
questionInput = input()
MathQuestion(questionInput)
MathQuestion(questionInput) | true |
383cf5c58b65554c25ba6c29ec5805c5e6abfbde | thekushkode/lists | /lists.2.py | 1,321 | 4.375 | 4 | # List Exercise 2
# convert infinite grocery item propt
# only accept 3 items
# groc list var defined
groc = []
#build list
while len(groc) < 3:
needs = input('Enter one grocery item you need: ')
groc.append(needs)
#groc2 list var defined
groc2 = []
#build list
while len(groc2) < 3:
needs2 = input('Enter one grocery item you need: ')
groc2.append(needs2)
#adds lists and puts them into a new list
groc_fin = groc + groc2
#or groc_fin = groc.extend(groc2)
print(groc_fin)
#ask for index to be replaced
index_to_replace = int(input('Enter the index of the iem you want to replace: '))
#ask for item to add
item_to_add = input('What item would you like to add: ')
#adds item to final list based on user inputs
groc_fin[index_to_replace] = item_to_add
#prints new list
print(groc_fin)
#code w/o comments
# groc = []
# while len(groc) < 3:
# needs = input('Enter one grocery item you need: ')
# groc.append(needs)
# groc2 = []
# while len(groc2) < 3:
# needs2 = input('Enter one grocery item you need: ')
# groc2.append(needs2)
# groc_fin = groc + groc2
# print(groc_fin)
# index_to_replace = int(input('Enter the index of the iem you want to replace: '))
# item_to_add = input('What item would you like to add: ')
# groc_fin[index_to_replace] = item_to_add
# print(groc_fin) | true |
810912f2f7b530068dfa948332fc404572c3bb8e | abdulalbasith/python-programming | /unit-3/dict_practice.py | 521 | 4.59375 | 5 | my_name= {
"a":1,
"b":1,
"d":1,
"u":1,
"l":1
}
for letter in my_name:
print (f"The letter {letter} appears {my_name[letter]} time in my name")
def reverse_lookup(state_capitals,value):
result = ""
for state in state_capitals:
if state_capitals [state] == value:
result = state
return result
state_capitals = {
"Alaska" : "Juneau",
"Colorado" : "Denver",
"Oregon" : "Salem",
"Texas" : "Austin"
}
print(reverse_lookup(state_capitals,"Denver")) | false |
b8d1d4a3facd658685105842d2ba4d25ce3bdd24 | abdulalbasith/python-programming | /unit-2/homework/hw-3.py | 368 | 4.25 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
number_of_strings = 0
for string in odd_strings:
string_length = len(string)
first_char= string [0]
last_char= string [-1]
if string_length > 3 and first_char == last_char:
number_of_strings += 1
print (number_of_strings)
| true |
89d79dc316e679596d8ffe70747316ed83b75442 | abdulalbasith/python-programming | /unit-3/sols-hw-pr5.py | 1,023 | 4.125 | 4 | #Homework optional problem #5
def letter_count (word):
count = {}
for l in word:
count[l] = count.get (l,0) +1
return count
def possible_word (word_list, char_list):
#which words in word list can be formed from the characters in the character list
#iterate over word_list
valid_words=[]
for word in word_list:
is_word_valid = True
#get a count of each character in word
char_count = letter_count(word)
#check each character in the word
for letter in word:
if letter not in char_list:
is_word_valid = False
else:
if char_list.count(letter) != char_count [letter]:
is_word_valid = False
#Add valid words to a list
if is_word_valid:
valid_words.append (word)
return valid_words
#testing
legal_words = ['go', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
letters = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
print (possible_word(legal_words,letters)) | true |
ecd28bb5b6fa31378207b40b9a6ea0c93db7e2b0 | Amaya1998/business_application | /test2.py | 565 | 4.21875 | 4 | import numpy as np
fruits= np.array (['Banana','Pine-apple','Strawberry','Avocado','Guava','Papaya'])
print(fruits)
def insertionSort(fruits):
for i in range(1, len(fruits)): # 1 to length-1
item = fruits[i]
# Move elements
# to right by one position
f = i
while f >0 and fruits[f-1] > item:
fruits[f] = fruits[f-1] # move value to right
f -= 1
fruits[f] = item # insert at correct place
insertionSort(fruits)
print(fruits)
| true |
9b4c24baf6b2a851fb83dfe5857aac73a5d3596d | kajalchoundiye/Python_programs | /truefalse2.py | 278 | 4.25 | 4 | if 0:
print("True")
else:
print("False")
name=input("please enter your name ")
if name:
print("hello,{}".format(name))
else:
print("are you the man with no name? ")
#if name
if name != "":
print('hiiii' + name)
else:
print("no name...!") | false |
a1a09bf2afeae4790b4c405446bdfd4d79c23eea | intkhabahmed/PythonProject | /Day1/Practice/Operators.py | 243 | 4.125 | 4 | num1 = input("Enter the first number") #Taking first number
num2 = input("Enter the second number") #Taking second number
print("Addtion: ",num1+num2)
print("Subtraction: ",num1-num2)
print("Multiply: ",num1*num2)
print("Division: ",num1/num2) | true |
5ada27d455d8bf9d51b6e71360ddd85175b0ac95 | wang264/JiuZhangLintcode | /AlgorithmAdvance/L2/require/442_implement-trie-prefix-tree.py | 1,802 | 4.3125 | 4 | # Implement a Trie with insert, search, and startsWith methods.
#
# Example
# Example 1:
#
# Input:
# insert("lintcode")
# search("lint")
# startsWith("lint")
# Output:
# false
# true
# Example 2:
#
# Input:
# insert("lintcode")
# search("code")
# startsWith("lint")
# startsWith("linterror")
# insert("linterror")
# search("lintcode“)
# startsWith("linterror")
# Output:
# false
# true
# false
# true
# true
# Notice
# You may assume that all inputs are consist of lowercase letters a-z.
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
"""
@param: word: a word
@return: nothing
"""
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
# return the node that has the last character of this word if exist.
def find(self, word):
node = self.root
for char in word:
node = node.children.get(char)
if node is None:
return None
return node
"""
@param: word: A string
@return: if the word is in the trie.
"""
def search(self, word):
node = self.find(word)
if node is None:
return False
return node.is_word
"""
@param: prefix: A string
@return: if there is any word in the trie that starts with the given prefix.
"""
def startsWith(self, prefix):
return self.find(prefix) is not None
trie = Trie()
trie.search('lintcode')
trie.startsWith("lint")
trie.insert("lint")
trie.startsWith("lint") | true |
c952d98015d0b0bb0618b42780fd18d221b0e408 | wang264/JiuZhangLintcode | /AlgorithmAdvance/L3/optional/370_convert-expression-to-reverse-polish-notation.py | 1,939 | 4.15625 | 4 | # 370. Convert Expression to Reverse Polish Notation
# 中文English
# Given a string array representing an expression, and return the
# Reverse Polish notation of this expression. (remove the parentheses)
# 370. 将表达式转换为逆波兰表达式
# 中文English
# 给定一个字符串数组,它代表一个表达式,返回该表达式的逆波兰表达式。(去掉括号)
#
# Example
# Example 1:
#
# Input: ["3", "-", "4", "+", "5"]
# Output: ["3", "4", "-", "5", "+"]
# Explanation: 3 - 4 + 5 = -1 + 5 = 4
# 3 4 - 5 + = -1 5 + = 4
# Example 2:
#
# Input: ["(", "5", "-", "6", ")", "*", "7"]
# Output: ["5","6","-","7","*"]
# Explanation: (5 - 6) * 7 = -1 * 7 = -7
# 5 6 - 7 * = -1 7 * = -7
# Clarification
# Definition of Reverse Polish Notation:
#
# https://en.wikipedia.org/wiki/Reverse_Polish_notation
# https://baike.baidu.com/item/逆波兰表达式/9841727?fr=aladdin
class Solution:
"""
@param expression: A string array
@return: The Reverse Polish notation of this expression
"""
def convertToRPN(self, expression):
stk = []
RPN = []
for s in expression:
if s == '(':
stk.append(s)
elif s == ')':
pos = stk[::-1].index('(')
RPN += stk[::-1][:pos]
stk = stk[:-pos - 1]
elif s[0] in '1234567890':
RPN.append(s)
else:
priority = self.getPriority(s)
while len(stk) and self.getPriority(stk[-1]) >= priority:
RPN.append(stk[-1])
stk.pop()
stk.append(s)
RPN += stk[::-1]
return RPN
def getPriority(self, s):
if s in '*/':
return 3
if s in '+-':
return 2
if s in '()':
return 1
return 0
sol =Solution()
sol.convertToRPN(["(", "5", "-", "6", ")", "*", "7"]) | false |
c547b2db20d700bdc3b0bc06a7193e38e1d92440 | wang264/JiuZhangLintcode | /Algorithm/L4/require/480_binary-tree-paths.py | 2,826 | 4.21875 | 4 | # 480. Binary Tree Paths
# 中文English
# Given a binary tree, return all root-to-leaf paths.
#
# Example
# Example 1:
#
# Input:{1,2,3,#,5}
# Output:["1->2->5","1->3"]
# Explanation:
# 1
# / \
# 2 3
# \
# 5
# Example 2:
#
# Input:{1,2}
# Output:["1->2"]
# Explanation:
# 1
# /
# 2
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
rslt = []
this_path = []
self.helper(root, this_path, rslt)
return rslt
def helper(self, node, this_path, rslt):
# if this node is leave node
this_path.append(str(node.val))
if node.left is None and node.right is None:
temp_str = '->'.join(this_path)
rslt.append(temp_str)
else:
if node.left:
self.helper(node.left, this_path, rslt)
this_path.pop()
if node.right:
self.helper(node.right, this_path, rslt)
this_path.pop()
# divide and conquer
class Solution2:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
paths = self.tree_path_helper(root)
return ['->'.join(path) for path in paths]
def tree_path_helper(self, root):
# write your code here
if root is None:
return []
left_paths = self.tree_path_helper(root.left)
right_paths = self.tree_path_helper(root.right)
paths = left_paths + right_paths
if len(paths) == 0:
return [[str(root.val)]]
else:
for path in paths:
path.insert(0, str(root.val))
return paths
# DFS
class Solution3:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
paths = []
this_path = [str(root.val)]
self.dfs(root, this_path, paths)
return paths
def dfs(self, node, this_path, paths):
if node.left is None and node.right is None:
paths.append('->'.join(this_path))
if node.left:
this_path.append(str(node.left.val))
self.dfs(node.left, this_path, paths)
this_path.pop()
if node.right:
this_path.append(str(node.right.val))
self.dfs(node.right, this_path, paths)
this_path.pop()
from helperfunc import build_tree_breadth_first
sol = Solution3()
root = build_tree_breadth_first(sequence=[1, 2, 3, None, 5])
sol.binaryTreePaths(root=root)
| true |
48292de617f3eda89c003ac106a37d62e8f445d9 | wang264/JiuZhangLintcode | /Algorithm/L7/optional/601_flatten-2d-vector.py | 1,398 | 4.375 | 4 | # 601. Flatten 2D Vector
# 中文English
# Implement an iterator to flatten a 2d vector.
#
# 样例
# Example 1:
#
# Input:[[1,2],[3],[4,5,6]]
# Output:[1,2,3,4,5,6]
# Example 2:
#
# Input:[[7,9],[5]]
# Output:[7,9,5]
from collections import deque
class Vector2D(object):
# @param vec2d {List[List[int]]}
def __init__(self, vec2d):
self.deque = deque(vec2d)
self.next_element = None
# Initialize your data structure here
# @return {int} a next element
def next(self):
return self.next_element
# @return {boolean} true if it has next element
# or false
def hasNext(self):
if not self.deque:
return False
curr_element = self.deque.popleft()
while isinstance(curr_element, list):
for i in reversed(curr_element):
self.deque.appendleft(i)
if len(self.deque) != 0:
curr_element = self.deque.popleft()
else:
curr_element = None
if curr_element is None:
return False
else:
self.next_element = curr_element
return True
# Your Vector2D object will be instantiated and called as such:
vec2d = [[1, 2], [3], [4, 5, 6]]
i, v = Vector2D(vec2d), []
while i.hasNext(): v.append(i.next())
v
vec2d = [[], []]
i, v = Vector2D(vec2d), []
while i.hasNext(): v.append(i.next()) | true |
7fb4c1cab08e8ecb37dee89edf8a47093e54a1b5 | wang264/JiuZhangLintcode | /AlgorithmAdvance/L4/require/633_find-the-duplicate-number.py | 1,001 | 4.125 | 4 | # 633. Find the Duplicate Number
# 中文English
# Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
# guarantee that at least one duplicate number must exist.
# Assume that there is only one duplicate number, find the duplicate one.
#
# Example
# Example 1:
#
# Input:
# [5,5,4,3,2,1]
# Output:
# 5
# Example 2:
#
# Input:
# [5,4,4,3,2,1]
# Output:
# 4
# Notice
# You must not modify the array (assume the array is read only).
# You must use only constant, O(1) extra space.
# Your runtime complexity should be less than O(n^2).
# There is only one duplicate number in the array, but it could be repeated more than once.
class Solution:
"""
@param nums: an array containing n + 1 integers which is between 1 and n
@return: the duplicate one
"""
def findDuplicate(self, nums):
# write your code here
pass
sol = Solution()
sol.findDuplicate(nums=[5,4,4,3,2,1])
sol.findDuplicate(nums=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]) | true |
9539668c96bc480672085947c057285af7b26a6f | wang264/JiuZhangLintcode | /AlgorithmAdvance/L2/optional/432_find-the-weak-connected-component-in-the-directed-graph.py | 1,236 | 4.1875 | 4 | # 找出有向图中的弱连通分量 · Find the Weak Connected Component in the Directed Graph
# Union Find
# LintCode 版权所有
# 描述
# Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and
# a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in which
# any two vertices are connected by direct edge path.)
#
# Sort the elements of a component in ascending order.
# 样例
# Example 1:
#
# Input: {1,2,4#2,4#3,5#4#5#6,5}
# Output: [[1,2,4],[3,5,6]]
# Explanation:
# 1----->2 3-->5
# \ | ^
# \ | |
# \ | 6
# \ v
# ->4
# Example 2:
#
# Input: {1,2#2,3#3,1}
# Output: [[1,2,3]]
# 说明
# graph model explaination:
# https://www.lintcode.com/help/graph
#
#
# 找出有向图中的弱连通分量 · Find the Weak Connected Component in the Directed Graph
# Union Find
# LintCode 版权所有
# 描述
# 请找出有向图中弱连通分量。图中的每个节点包含 1 个标签和1 个相邻节点列表。
# (有向图的弱连通分量是任意两点均有有向边相连的极大子图)
#
# 将连通分量内的元素升序排列。
print('same as 431')
| false |
c55f839e550c5d851150254ae6f2f151deed02a5 | wang264/JiuZhangLintcode | /Algorithm/L7/optional/606_kth-largest-element-ii.py | 808 | 4.21875 | 4 | # 606. Kth Largest Element II
# 中文English
# Find K-th largest element in an array. and N is much larger than k. Note that it is the kth largest element in the sorted order, not the kth distinct element.
#
# Example
# Example 1:
#
# Input:[9,3,2,4,8],3
# Output:4
#
# Example 2:
#
# Input:[1,2,3,4,5,6,8,9,10,7],10
# Output:1
#
# Notice
# You can swap elements in the array
class Solution:
"""
@param nums: an integer unsorted array
@param k: an integer from 1 to n
@return: the kth largest element
"""
def kthLargestElement2(self, nums, k):
# write your code here
import heapq
heap = []
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap)
return heapq.heappop(heap)
| false |
b20590161658824d6ec48d666ca7dafbb19bcbcd | wang264/JiuZhangLintcode | /Algorithm/L4/require/453_flatten-binary-tree-to-linked-list.py | 2,642 | 4.1875 | 4 | # 453. Flatten Binary Tree to Linked List
# 中文English
# Flatten a binary tree to a fake "linked list" in pre-order traversal.
#
# Here we use the right pointer in TreeNode as the next pointer in ListNode.
#
# Example
# Example 1:
#
# Input:{1,2,5,3,4,#,6}
# Output:{1,#,2,#,3,#,4,#,5,#,6}
# Explanation:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Example 2:
#
# Input:{1}
# Output:{1}
# Explanation:
# 1
# 1
# Challenge
# Do it in-place without any extra memory.
#
# Notice
# Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.
class Solution:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
if root is None:
return root
dummy_node = TreeNode(-1) # dummy node
prev_node = dummy_node
stack = [root]
while stack:
curr_node = stack.pop()
prev_node.left = None
prev_node.right = curr_node
prev_node = curr_node
if curr_node.right:
stack.append(curr_node.right)
if curr_node.left:
stack.append(curr_node.left)
return dummy_node.right
from helperfunc import TreeNode, build_tree_breadth_first
sol = Solution()
root = build_tree_breadth_first(sequence=[1, 2, 5, 3, 4, None, 6])
linked_list = sol.flatten(root)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import deque
class SolutionOutOfMemory:
"""
@param root: a TreeNode, the root of the binary tree
@return: nothing
"""
def flatten(self, root):
# write your code here
if root is None:
return None
q_traverse = deque([])
q_nodes = deque([])
q_traverse.append(root)
while q_traverse:
node = q_traverse.popleft()
q_nodes.append(node)
if node.right:
q_nodes.appendleft(node.right)
if node.left:
q_nodes.appendleft(node.left)
# fix the relationship.
root = q_nodes[0]
while len(q_nodes) > 1:
node = q_nodes.popleft()
node.left = None
node.right = q_nodes[0]
return root
sol = SolutionOutOfMemory()
root = build_tree_breadth_first(sequence=[1, 2, 5, 3, 4, None, 6])
linked_list = sol.flatten(root)
| true |
e9f8b128025f9273474c6c0af58541eb9fcf1ae8 | wang264/JiuZhangLintcode | /Intro/L5/require/376_binary_tree_path_sum.py | 1,969 | 4.21875 | 4 | # 376. Binary Tree Path Sum
# 中文English
# Given a binary tree, find all paths that sum of the nodes in the path equals to a given number target.
#
# A valid path is from root node to any of the leaf nodes.
#
# Example
# Example 1:
#
# Input:
# {1,2,4,2,3}
# 5
# Output: [[1, 2, 2],[1, 4]]
# Explanation:
# The tree is look like this:
# 1
# / \
# 2 4
# / \
# 2 3
# For sum = 5 , it is obviously 1 + 2 + 2 = 1 + 4 = 5
# Example 2:
#
# Input:
# {1,2,4,2,3}
# 3
# Output: []
# Explanation:
# The tree is look like this:
# 1
# / \
# 2 4
# / \
# 2 3
# Notice we need to find all paths from root node to leaf nodes.
# 1 + 2 + 2 = 5, 1 + 2 + 3 = 6, 1 + 4 = 5
# There is no one satisfying it.
from helperfunc import TreeNode, build_tree_breadth_first
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def binaryTreePathSum(self, root, target):
rslt = self.binary_tree_path_sum_helper(root, target)
return [list(reversed(x)) for x in rslt]
def binary_tree_path_sum_helper(self, root, target):
# write your code here
if root is None:
return []
if root.left is None and root.right is None:
if root.val == target:
return [[target]]
else:
return []
left_rslt = self.binary_tree_path_sum_helper(root.left, target - root.val)
right_rslt = self.binary_tree_path_sum_helper(root.right, target - root.val)
rslt = left_rslt + right_rslt
for i in range(len(rslt)):
rslt[i].append(root.val)
return rslt
root = build_tree_breadth_first(sequence=[1, 2, 4, 2, 3])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=5)
print(rslt)
root = build_tree_breadth_first(sequence=[1, 2, -5, 4, None, 5, 6])
sol = Solution()
rslt = sol.binaryTreePathSum(root=root, target=2)
| true |
67b68a4104edef825605d7b8bfeceb5400cab448 | Gorilla-Programming/Python-Course | /Assignment 5/Ques 8.py | 218 | 4.28125 | 4 | # Program to print Volume of Cuboid
a = float(input("Enter 1st number : "))
b = float(input("Enter 2nd number : "))
c = float(input("Enter 3rd number : "))
print("Average of given Number is : %f " %((a+b+c)/3))
| false |
4924278da3dba92909c099754236d732d5ae6e09 | trinahaque/LeetCode | /Easy/String/reverseWordsInString.py | 942 | 4.15625 | 4 | # Given an input string, reverse the string word by word.
# Input: "the sky is blue"
# Output: "blue is sky the"
def reverseWordsInString(s):
if len(s) < 1:
return ""
elif len(s) < 2:
if s.isalnum() == True:
return s
result = ""
# splits the words into an array
strArr = s.split(" ")
# reverses the array
for i in range(int(len(strArr)/2)):
if strArr[i].isalnum() == False or strArr[len(strArr) - 1 - i].isalnum() == False:
break
strArr[i], strArr[len(strArr) - 1 - i] = strArr[len(strArr) - 1 - i], strArr[i]
# puts each word from the reversed array into result string except for the last one
for i in range(len(strArr) - 1):
if strArr[i].isalnum() == False:
break
result += strArr[i] + " "
result += strArr[len(strArr) - 1]
return result
input = "the sky blue"
print (reverseWordsInString("1 "))
| true |
f8d38ef5ba690a50e58554b0edfb0ecdf3610f95 | haoccheng/pegasus | /leetcode/insertion_sort_list.py | 1,396 | 4.125 | 4 | # insertion sort in linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_list(values):
root = None
curr = None
for v in values:
n = ListNode(v)
if root is None:
root = n
curr = root
else:
curr.next = n
curr = curr.next
return root
create_list = staticmethod(create_list)
def pt(self):
ret = []
ret.append(self.val)
if self.next is not None:
ret += self.next.pt()
return ret
def insertion_sort(head):
p1 = head
p2 = None
while (p1 is not None):
curr = p1
p1 = p1.next
curr.next = None
if p2 is None:
p2 = curr
elif curr.val <= p2.val:
curr.next = p2
p2 = curr
else:
p3 = p2
while (p3.next is not None):
if p3.next.val < curr.val:
p3 = p3.next
else:
curr.next = p3.next
p3.next = curr
curr = None
break
if curr is not None:
p3.next = curr
return p2
insertion_sort = staticmethod(insertion_sort)
x = ListNode.create_list([1, 2, 3, 2, 1])
y = ListNode.insertion_sort(x)
print y.pt()
x = ListNode.create_list([5, 4, 3, 2, 1])
y = ListNode.insertion_sort(x)
print y.pt()
x = ListNode.create_list([1, 2, 3, 4, 5])
y = ListNode.insertion_sort(x)
print y.pt()
| false |
b8c79c64b1f91888afb0fadaf80e9af7921f191d | haoccheng/pegasus | /leetcode/power_of_two.py | 416 | 4.375 | 4 | # Given an integer, determine if it is a power of two.
def power_of_two(n):
if n <= 0:
return False
else:
value = n
while (value > 0):
if value == 1:
return True
else:
r = value % 2
if r != 0:
return False
else:
value = value / 2
return True
print power_of_two(1)
print power_of_two(2)
print power_of_two(8)
print power_of_two(9)
| true |
2029924ab34ced3e322083702d175366ba02b12e | haoccheng/pegasus | /coding_interview/list_sort.py | 965 | 4.125 | 4 | # implement a function to sort a given list.
# O(n2): each iteration locate the element that should have been placed in the specific position, swap.
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def take(self):
buffer = [self.value]
if self.next is not None:
buffer += self.next.take()
return buffer
def create_linked_list():
w = Node(3)
x = Node(4)
y = Node(2)
z = Node(1)
w.next = x
x.next = y
y.next = z
return w
def sort_list(input):
root = input
curr = input
while (curr is not None):
min_v = curr.value
min_p = curr
pt = curr.next
while (pt is not None):
if (min_v > pt.value):
min_v = pt.value
min_p = pt
pt = pt.next
t = curr.value
curr.value = min_v
min_p.value = t
curr = curr.next
return root
input = create_linked_list()
print input.take()
sort = sort_list(input)
print sort.take()
| true |
963162725075e8a2cf90d90f906a8afc3ac94a54 | SAMIFIX/Training_Data_Structure | /mutability.py | 1,292 | 4.8125 | 5 | """
Mutable :
هي امكانيه تغير القيمه للمتغير
Immutable:
غير ممكن تغير القيمه للمتغير
Mutable Object:
list, dict, set
Immutable Object:
Integer, float, string, tuple, bool , frozenset
"""
# Example in Mutable Objects:
# list
sami = []
sami.append(1)
sami.append("Hello")
sami.append("For")
sami.append(True)
print('Mutable list: Before change=> ', sami)
sami[1]= 'No'
sami[3]= 'No'
print('Mutable list: After change=> ', sami)
# Immutable Objects:
yes = 1
print('yes before change: ',yes)
print('yes id: ',id(yes))
yes = 2
print('yes after change: ',yes)
print('yes id: ',id(yes))
class Mutability:
def __init__(self, id=None):
self.id = id
def get_id(self):
if self.id is not None:
return print(self.id)
return None
def set_id(self, id):
self.id = id
def get_id_addresses(self):
if self.id is not None:
return print(id(self.id))
else:
return None
mu = Mutability()
mu.set_id(1)
mu.get_id()
mu.get_id_addresses()
print(id(mu))
mu.set_id(2)
mu.get_id()
mu.get_id_addresses()
print(id(mu))
# tuple
jack = 1,2,'Yes', 'No'
# print('jack clothes: ', jack)
# print('jack type: ', type(jack))
jack[2] = 4
print(jack)
| false |
c165079e81b5aff822766262f7c4271ba5d8ec88 | m-bansal/build_up | /graphic figures.py | 850 | 4.125 | 4 | import turtle
t = turtle.Turtle()
t.pensize(4)#for thickness
t.hideturtle()
#line
line=int(input("Enter the number of pixels by which a turtle should be moved to draw a line: "))
t.forward(line)#distance moved by turtle
t.penup()#move the turtle head
t.goto(0, -200)#no outline drawn by turtle
t.pendown()#start outlining
#square
x=int(input("Enter the number of pixels by which a turtle should be moved for square: "))
for i in range(4):
t.forward(x)#distance moved by turtle
t.left(90)
t.penup()#move the turtle head
t.goto(0, -x)#no outline drawn by turtle
t.pendown()#start outlining
#rectangle
l=int(input("Enter the length for rectangle: "))
b=int(input("Enter the breadth for rectangle: "))
for i in range(2):
t.forward(l)
t.left(90)
t.forward(b)
t.left(90)
turtle.done()
| false |
5ca3c133c63549ef5c4c2dc75e83b2e2dd06e454 | xartiou/algorithms-and-structures-python | /task_8_l2.py | 1,330 | 4.28125 | 4 | # 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
# Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
# Запросить количество вводимых чисел (n) и цифру для подсчета (d).
n = int(input("Введите сколько будет чисел?: "))
d = int(input("Какую цифру будем считать?: "))
# Присвоить счетчику цифр значение 0.
count = 0
#Выполнить n раз цикл
for i in range(1, n + 1):
m = int(input("Число " + str(i) + ": "))
while m > 0:
# извлекать последнюю его цифру и сравнивать с цифрой, которую надо посчитать
if m % 10 == d:
#увеличивать значение счетчика цифр на 1, если сравниваемые цифры совпадают
count += 1
#избавляться от последней цифры числа
m = m // 10
print("Было введено %d цифр %d" % (count, d))
| false |
3f6c4d1f0b362444e84e36ca4d0ff3943bfc6bed | xartiou/algorithms-and-structures-python | /task_1.py | 822 | 4.34375 | 4 | # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# - просим пользователя ввести целое трехзначное число
three_digit = int(input('Введите целое трехзначное число: '))
# - выделяем цифры из числа
one_d = three_digit // 100
two_d = (three_digit % 100) // 10
three_d = three_digit % 10
# - сумма цифр числа
sum_of_digits = one_d + two_d + three_d
# - произведение цифр числа
comp_of_digits = one_d * two_d * three_d
# - выводим результат
print(f'Для числа {three_digit} сумма цифр = {sum_of_digits}\nпроизведение цифр = {comp_of_digits}')
| false |
9cb6bc62c648f66140ca8cc97a7eb264ce21a88c | ismaelconejeros/100_days_of_python | /Day 04/exercise_01.py | 521 | 4.4375 | 4 | #You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".
#Important, the first letter should be capitalised and spelt exactly like in the example e.g. Heads, not heads.
#There are many ways of doing this. But to practice what we learnt in the last lesson, you should generate a
# random number, either 0 or 1. Then use that number to print out Heads or Tails.
import random
coin = random.randint(0,1)
if coin == 0:
print('Tails')
elif coin == 1:
print('Heads') | true |
1be3880c9dbce5695a23b3aa8fb6cd4fa043c8bc | ismaelconejeros/100_days_of_python | /Day 03/exercise_05.py | 2,192 | 4.21875 | 4 | #write a program that tests the compatibility between two people.
#To work out the love score between two people:
#Take both people's names and check for the number of times the letters in the word TRUE occurs.
# Then check for the number of times the letters in the word LOVE occurs.
# Then combine these numbers to make a 2 digit number.
#For Love Scores less than 10 or greater than 90, the message should be:
#"Your score is **x**, you go together like coke and mentos."
#For Love Scores between 40 and 50, the message should be:
#"Your score is **y**, you are alright together."
#Otherwise, the message will just be their score. e.g.:
#"Your score is **z**."
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
true = ['t','r','u','e','T','R','U','E']
love = ['l','o','v','e','L','O','V','E']
names = name1 + name2
true_num = 0
love_num = 0
for letter in names:
if letter in true:
true_num += 1
if letter in love:
love_num += 1
score = int(str(true_num) + str(love_num))
if score < 10 or score > 90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif score >= 40 and score <= 50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.")
#-------------Other way
# 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
names = name1.lower() + name2.lower()
t = names.count('t')
r = names.count('r')
u = names.count('u')
e = names.count('e')
l = names.count('l')
o = names.count('o')
v = names.count('v')
e = names.count('e')
true = str(t+r+u+e)
love = str(l+o+v+e)
score = int(true+love)
if score < 10 or score > 90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif score >= 40 and score <= 50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.") | true |
a5b39aec77a04693499049e27f6ee26ab3ff66e6 | Malcolm-Tompkins/ICS3U-Unit4-01-Python-While_Loops | /While_Loops.py | 695 | 4.125 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on May 12, 2021
# Determines sum of all numbers leading up to a number
def main():
# Input
user_input = (input("Enter your number: "))
try:
user_number = int(user_input)
loop_counter = 0
while (loop_counter < user_number):
total = (user_number / 2) * (1 + user_number)
loop_counter = loop_counter + 1
print("{0:,.0f} is the total sum of the previous numbers before {1}"
.format(total, user_number))
except Exception:
print("{} is not an integer".format(user_input))
finally:
print("Done.")
if __name__ == "__main__":
main()
| true |
e37cb75f5da75f5c0e24a79fde1551f7debf8799 | exeptor/TenApps | /App_2_Guess_The_Number/program_app_2.py | 873 | 4.25 | 4 | import random
print('-------------------------------------')
print(' GUESS THE NUMBER')
print('-------------------------------------')
print()
random_number = random.randint(0, 100)
your_name = input('What is your name? ')
guess = -1
first_guess = '' # used this way in its first appearance only; on the second it will be changed
while guess != random_number:
raw_guess = input('What is your{} guess {}? '.format(first_guess, your_name))
guess = int(raw_guess)
first_guess = ' next' # change on the second appearance in the loop to enrich user experience
if guess < random_number:
print('Sorry {}, {} is LOWER!'.format(your_name, guess))
elif guess > random_number:
print('Sorry {}, {} is HIGHER!'.format(your_name, guess))
else:
print('Congratulation {}, {} is the correct number!'.format(your_name, guess))
| true |
9ac51bc45b2f5dfb09bb397ce0aa9c1e5ae06034 | engineerpassion/Data-Structures-and-Algorithms | /DataStructures/LinkedList.py | 2,417 | 4.1875 | 4 | class LinkedListElement():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def is_empty(self):
empty = False
if self.head is None:
empty = True
return empty
def add(self, value):
element = LinkedListElement(value)
if self.is_empty():
self.head = element
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = element
return
def delete(self, value):
deleted = False
if not self.is_empty():
if self.head.value == value:
temp = self.head
self.head = self.head.next
del temp
deleted = True
if not deleted and self.head.next is not None:
prev = self.head
current = self.head.next
while current is not None:
if current.value == value:
prev.next = current.next
del current
deleted = True
break
prev = current
current = current.next
return deleted
def traverse(self):
s = ""
temp = self.head
while temp is not None:
s += str(temp.value)
temp = temp.next
if temp is not None:
s += "->"
print(s)
return
def main():
ll = LinkedList()
print("Created an empty Linked List!")
print("Adding 1.")
ll.add(1)
print("Linked list looks as follows:")
ll.traverse()
print("Adding 2.")
ll.add(2)
print("Linked list looks as follows:")
ll.traverse()
print("Adding 3.")
ll.add(3)
print("Adding 4.")
ll.add(4)
print("Adding 5.")
ll.add(5)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 3.")
ll.delete(3)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 4.")
ll.delete(4)
print("Linked list looks as follows:")
ll.traverse()
print("Removing 1.")
ll.delete(1)
print("Linked list looks as follows:")
ll.traverse()
"""
Uncomment the following line to run the file.
"""
#main() | true |
f2f0dc7da7f646a4b647c49cef1810a3c73fb6d6 | caged9/lrn-py | /1 half/Lesson 4/task_6.py | 974 | 4.25 | 4 | #В программе генерируется случайное целое число от 0 до 100.
#Пользователь должен его отгадать не более чем за 10 попыток. После
#каждой неудачной попытки должно сообщаться, больше или меньше
#введенное пользователем число, чем то, что загадано. Если за 10 попыток
#число не отгадано, вывести ответ
import random
print("Guess a number from 0 to 100 \n ")
rand = random.randint(0, 100)
tr = 10
while (tr != 0):
num = int(input())
if num == rand:
print("You guessed the number!")
break
elif num > rand:
print("Your number is bigger than one given")
elif num < rand:
print("Your number is smaller than one given")
tr -= 1
if tr == 0:
print("Right number was: ", rand) | false |
111d2814ccefb468c7c62abcf08708365d551426 | caged9/lrn-py | /1 half/Lesson 3/task_1.py | 626 | 4.125 | 4 | #Выполнить логические побитовые операции «И», «ИЛИ» и др. над двумя
#введенными пользователем числами. Выполнить над одним из введенных
#чисел побитовый сдвиг вправо и влево на два знака
a=int(input('Type a: '))
b=int(input('Type b: '))
print(a, ' = ', bin(a))
print(b, ' = ', bin(b))
print('a & b = ', a & b, '(',bin(a&b), ')')
print('a | b = ', a | b, '(',bin(a|b), ')')
print('a << 2 = ', a<<2, '(',bin(a<<2), ')')
print('a >> 2 = ', a>>2, '(',bin(a>>2), ')') | false |
531470e218f42e9f88b95968c05469ffd5e81554 | Morgenrode/Euler | /prob4.py | 725 | 4.1875 | 4 | '''prob4.py: find the largest palidrome made from the product of two 3-digit numbers'''
def isPalindrome(num):
'''Test a string version of a number for palindromicity'''
number = str(num)
return number[::-1] == number
def search():
'''Search through all combinations of products of 3 digit numbers'''
palindrome = 0
for x in range(100,1000):
for y in range(100,1000):
z = x * y
if isPalindrome(z) and z > palindrome:
palindrome = z
else:
pass
return palindrome
print(search())
| true |
166ed8b161017285f5fe6c52e76d8a985b6ba903 | acheimann/PythonProgramming | /Book_Programs/Ch1/chaos.py | 553 | 4.46875 | 4 | # File: chaos.py
# A simple program illustrating chaotic behavior.
#Currently incomplete: advanced exercise 1.6
#Exericse 1.6 is to return values for two numbers displayed in side-by-side columns
def main():
print "This program illustrates a chaotic function"
x = input("Enter a number between 0 and 1: ")
y = input ("Enter a second number between 0 and 1:")
n = input("How many numbers should I print?")
for i in range(n):
x = 2.0 * x * (1 - x)
print x
y = 2.0 * y * (1-y)
print y
main() | true |
1262c1d720d1a6d51261e0eb5ca739abe7545254 | acheimann/PythonProgramming | /Book_Programs/Ch3/sum_series.py | 461 | 4.25 | 4 | #sum_series.py
#A program to sum a series of natural numbers entered by the user
def main():
print "This program sums a series of natural numbers entered by the user."
print
total = 0
n = input("Please enter how many numbers you wish to sum: ")
for i in range(n):
number = input("Please enter the next number in your sequence: ")
total = total + number
print "Your total adds up to", total
main()
| true |
431a0f0002427aa49f2cb3c4df8fb0fd3a6fa2ba | acheimann/PythonProgramming | /Book_Programs/Ch2/convert_km2mi.py | 391 | 4.5 | 4 | #convert_km2mi.py
#A program to convert measurements in kilometers to miles
#author: Alex Heimann
def main():
print "This program converts measurements in kilometers to miles."
km_distance = input("Enter the distance in kilometers that you wish to convert: ")
mile_equivalent = km_distance * 0.62
print km_distance, "kilometers is equal to ", mile_equivalent, "miles."
main() | true |
45b4cf3fd7e165e8c741d80694e34fe248e48780 | va4oz/python_learning | /if_else.py | 237 | 4.125 | 4 | # -*- coding: utf-8 -*-
a = 12
if a == 12:
print("Верно")
b = 13
if b == 12:
print("верно")
else:
print("не верно")
c = 5
if c < 2 or c > 3:
print("не верно")
elif c == 2:
print("верно") | false |
3d40a99ce2dd3e7965cf4284455091e715ca1227 | Ray0907/intro2algorithms | /15/bellman_ford.py | 1,630 | 4.1875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# single source shortest path algorithm.
from sys import maxsize
# The main function that finds shortest
# distances from src to all other vertices
# using Bellman-Ford algorithm. The function
# also detects negative weight cycle
# The row graph[i] represents i-th edge with
# three values u, v and w.
def BellmanFord(graph, V, E, src):
# Initialize distance of all vertices as infinite.
dis = [maxsize] * V
# Initialize distance of source as 0
dis[src] = 0
'''
Relax all edges |V| - 1 times. A simple shortest path from src to any other vertex can have at-most |V| -1 edges.
'''
for i in range(V -1):
for j in range(E):
if dis[graph[j][0]] + \
graph[j][2] < dis[graph[j][1]]:
dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2]
'''
Check for negative-weight cycles.The above step gurantees shortest distances if graph doesn't contain negative weight cycle. If we get a shorter path, then there is a cycle.
'''
for i in range(E):
x = graph[i][0]
y = graph[i][1]
weight = graph[i][2]
if dis[x] != maxsize and dis[x] + weight < dis[y]:
print('Graph contains negative weight cycle')
print('Vertex Distance from source')
for i in range(V):
print('%d\t\t%d' % (i, dis[i]))
if __name__ == '__main__':
V = 5 # Number of vertices in graph
E = 8 # NUmber of edges in graph
'''
Every edge has three values (u, v, w) where the edge is from vertex u to v.And weight of the edge is w.
'''
graph = [[0, 1, -1], [0, 2, 4], [1, 2, 3],
[1, 3, 2], [1, 4, 2], [3, 2, 5],
[3, 1, 1], [4, 3, -3]]
BellmanFord(graph, V, E, 0)
| true |
e9c98d8d13b3b55e9fd02d19d6ab17df4f1eb0d7 | MohamedAamil/Simple-Programs | /BinarySearchWords.py | 1,805 | 4.21875 | 4 | """
BinarySearchWords.py
To check whether a word is in the word list, you could use the in operator, but
it would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a
bisection search (also known as binary search), which is similar to what you
do when you look a word up in the dictionary (the book, not the data
structure). You start in the middle and check to see whether the word you are
looking for comes before the word in the middle of the list. If so, you search
the first half of the list the same way. Otherwise you search the second half.
Either way, you cut the remaining search space in half. If the word list has
113,809 words, it will take about 17 steps to find the word or conclude that it’s
not there.
Write a function called in_bisect that takes a sorted list and a target value and
returns True if the word is in the list and False if it’s not
"""
def in_bisect(Target, Strings):
"""
Searches for the Element using Binary Search
:param Target: String , Word
:param Strings: List , Words
:return: Boolean
"""
First = 0
Last = len(Strings) - 1
while First <= Last:
Mid = (First + Last) // 2
if Target == Strings[Mid]:
return Mid+1
elif Target < Strings[Mid]:
Last = Mid - 1
else:
First = Mid + 1
else:
return False
Length = eval(input("Enter Range: "))
Arr = []
for i in range(Length):
Words = eval(input("Enter Sorted String : "))
Arr.append(Words)
Elem = input("\n Enter Element to search: ")
Pos = in_bisect(Elem,Arr)
if not Pos:
print("Element not Found!!")
else:
print("\n Element found in Position : ", Pos) | true |
92f328387b9d1754ad0f5fc71d2626acd3c82666 | MohamedAamil/Simple-Programs | /SumOfDigits.py | 397 | 4.21875 | 4 | """
SumOfDigits.py : Displays the Sum of Digits of the given Number
"""
def get_sumofDigits(Num):
"""
Calculates the Sum of Digits
:param Num: integer , Number
"""
Sum = 0
while Num != 0:
a = Num % 10
Sum = Sum + a
Num = Num // 10
print("Sum of Digits : ",Sum)
Num = eval(input("Enter a Number: "))
get_sumofDigits(Num)
| true |
ffaab16f7ee68be9b9599cca7e2906279430d19d | trangthnguyen/PythonStudy | /integercuberootwhile.py | 388 | 4.34375 | 4 | #!/usr/bin/env python3
#prints the integer cube root, if it exists, of an
#integer. If the input is not a perfect cube, it prints a message to that
#effect.
x = int(input('Enter integer number:'))
guess = 0
while guess ** 3 < abs(x):
guess = guess + 1
if guess ** 3 == abs(x):
if x < 0:
guess = - guess
print('Cube root of', x, 'is:', guess)
else:
print(x, 'is not a perfect cube')
| true |
c58cd3ffc8bc84c8b21d8821daf55fca3f197eb3 | trangthnguyen/PythonStudy | /numberstringsum.py | 418 | 4.1875 | 4 | #!/usr/bin/env python3
#Let s be a string that contains a sequence of decimal numbers
#separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints
#the sum of the numbers in s.
x = input('Enter a string:')
count = 0
sum = 0
for i in x:
if i in '0123456789':
count = count + 1
sum = sum + int(i)
if count > 0:
print('Sum of the numbers in', x, 'is', sum)
else:
print('There is no number in', x)
| true |
f22285f06df5b6c8d79febe605d7471919356199 | kshruti1410/python-assignment | /src/q2.py | 822 | 4.15625 | 4 | """ abc is a by default abrstract class present """
from abc import ABC, abstractmethod
class Person(ABC):
""" inherit ABC class """
@abstractmethod
def get_gender(self):
""" skipping the function """
pass
class Female(Person):
""" this class return gender of a person """
def get_gender(self):
""" self is by default argument """
print("Person is Female")
class Male(Person):
""" this class return gender of a person """
def get_gender(self):
""" self is by default argument """
print("Person is Male")
try:
PARENT = Person()
except TypeError:
print(TypeError)
finally:
print("Female class method")
FEMALE = Female()
FEMALE.get_gender()
print("Male class method")
MALE = Male()
MALE.get_gender() | true |
bcb068344d4db4f5ae984ad6f6d63a378587ad83 | Abed01-lab/python | /notebooks/Handins/Modules/functions.py | 1,289 | 4.28125 | 4 | import csv
import argparse
def print_file_content(file):
with open(file) as f:
reader = csv.reader(f)
for row in reader:
print(row)
def write_list_to_file(output_file, lst):
with open(output_file, 'w') as f:
writer = csv.writer(f)
for element in lst:
f.write(element + "\n")
def write_strings_to_file(file, *strings):
with open(file, 'w') as f:
for string in strings:
f.write(string + "\n")
print(string)
def read_csv(input_file):
with open(input_file) as f:
new_list = []
reader = csv.reader(f)
for row in reader:
new_list.append(row)
return new_list
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A program that reads from csv and write to txt. the path is the location of the csv and file_name is the location of the file to write to.')
parser.add_argument('path', help='The path to the csv file')
parser.add_argument('-file', '--file_name', help='The file to write to')
args = parser.parse_args()
print('csv path:', args.path)
print('file_name:', args.file_name)
if args.file_name is not None:
write_list_to_file(args.file_name, read_csv(args.path)) | true |
ad7819e0dde2bf2b8583f992ec18f7ef5261cd0b | Intro-to-python/homework1-MaeveFoley | /problem2.py | 534 | 4.34375 | 4 | #homework1
#Due 10/10/18
# Problem 2
#Write a Python program to guess a number between 1 to 9.
# User is prompted to enter a guess. If the user guesses wrong then
#the prompt appears again until the guess is correct, on successful guess,
#user will get a "Well guessed!" message, and the program will exit.
#(Hint use a while loop)
#Don't forget to import random
import random
targetNum = random.randint(1,9)
guessNum = input("Enter a number")
while guessNum = targetNum:
print("Well guessed!")
else:
print(input("Try again!"))
| true |
edac7d307b6001b92023f46bddd49fd29af13715 | williamwbush/codewars | /unfinished/algorithm_night.py | 2,116 | 4.15625 | 4 | # Problem 1:
# https://www.hackerrank.com/challenges/counting-valleys/problem
# Problem 2:
# You found directions to hidden treasure only written in words. The possible directions are "NORTH", "SOUTH","WEST","EAST".
# "NORTH" and "SOUTH" are opposite directions, as are "EAST" and "WEST". Going one direction and coming back in the opposite direction leads to going nowhere. Someone else also has these directions to the treasure and you need to get there first. Since the directions are long, you decide to write a program top figure out the fastest and most direct route to the treasure.
# Write a function that will take a list of strings and will return a list of strings with the unneeded directions removed (NORTH<->SOUTH or EAST<->WEST side by side).
# Example 1:
# input: ['NORTH','EAST','WEST','SOUTH','WEST','SOUTH','NORTH','WEST']
# output:['WEST','WEST']
# In ['NORTH','EAST','WEST','SOUTH','WEST','SOUTH','NORTH','WEST'] 'NORTH' and 'SOUTH' are not directly opposite but they become directly opposite after reduction of 'EAST' and 'WEST'. The whole path can be reduced to ['WEST','WEST'].
# Example 2:
# input: ['EAST','NORTH','WEST','SOUTH']
# output:['EAST','NORTH','WEST','SOUTH']
# Not all paths are reducible. The path ['EAST','NORTH','WEST','SOUTH'] is not reducible. 'EAST' and 'NORTH', 'NORTH' and 'WEST', 'WEST' and 'SOUTH' are not directly opposite of each other and thus can't be reduced. The resulting path has
inp = ['EAST','NORTH','WEST','SOUTH']
position = [0,0]
for d in inp:
if d == 'NORTH':
position[1] += 1
elif d == 'SOUTH':
position[1] -= 1
elif d == 'EAST':
position[0] += 1
elif d == 'WEST':
position[0] -= 1
print(position)
directions = []
if position[0] > 0:
for i in range(position[0]):
directions.append('EAST')
if position[0] < 0:
for i in range(abs(position[0])):
directions.append('WEST')
if position[1] > 0:
for i in range(position[1]):
directions.append('NORTH')
if position[1] < 0:
for i in range(abs(position[1])):
directions.append('SOUTH')
print(directions)
| true |
615b00ffe0a15294d2b65af008f6889ef622e005 | igauravshukla/Python-Programs | /Hackerrank/TextWrapper.py | 647 | 4.25 | 4 | '''
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
Input Format :
The first line contains a string, S.
The second line contains the width, w.
Constraints :
0 < len(S) < 1000
0 < w < len(S)
Output Format :
Print the text wrapped paragraph.
Sample Input 0
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output 0
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
'''
import textwrap
def wrap(string, max_width):
l = textwrap.wrap(string,max_width)
return "\n".join(l)
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
| true |
0459d6caa8b5aacf99a1e9fb0e4208d70c72c09c | panditprogrammer/python3 | /python88.py | 1,374 | 4.25 | 4 | #Formatting String video 94
#format () method part2
"""this is
multiline comments in python """
print("fomating string and method rules")
print("----------integer---------")
print("{}".format(15))
print("{:d}".format(15))
print("{0:d}".format(15))
print("{num:d}".format(num=15))
print("----------float---------\n")
print("{}".format(15.65))
print("{:f}".format(15.65))
print("{0:f}".format(15.65))
print("{num:f}".format(num=15.65))
print("----------float and more---------\n")
print("{num:f}".format(num=10.2))
print("{num:8f}".format(num=10.2))
print("{num:8.3f}".format(num=10.2))
print("{num:+8.2f}".format(num=10.2))
print("{num:<8.2f}".format(num=10.2))
print("{num:*<8.2f}".format(num=10.2))
print("{num:*>8.2f}".format(num=10.2))
print("{num:^8.2f}".format(num=10.2))
print("{num:*^8.2f}".format(num=10.2))
# # print("----------string and its rules---------\n")
# # print("{str1:s}".format(str1="Panditprogrammer"))
# print("{str1:20s}".format(str1="Panditprogrammer"))
# print("{str1:20.s}".format(str1="Panditprogrammer"))
# print("{str1:<20.s}".format(str1="Panditprogrammer"))
# print("{str1:>20.s}".format(str1="Panditprogrammer"))
# print("{str1:*<20.s}".format(str1="Panditprogrammer"))
# print("{str1:*>20.s}".format(str1="Panditprogrammer"))
# print("{str1:^20.s}".format(str1="Panditprogrammer"))
# print("{str1:*^20.s}".format(str1="Panditprogrammer")) | false |
83c33d7ffe87715f233c63902d36bcfdab77460a | panditprogrammer/python3 | /python72.py | 354 | 4.40625 | 4 | # creating 2D array using zeros ()Function
from numpy import *
a=zeros((2,3) ,dtype=int)
print(a)
print("This is lenth of a is ",len(a))
n=len(a)
for b in range(n):
# range for index like 0,1,in case of range 2.
m=len(a[b])
print("This is a lenth of a[b]",m)
for c in range(m):
#print("This is inner for loop")
print( b,c,"index =",a[b][c])
| true |
9fdcf03a227850f99153d4948c26c3415ccb34f2 | panditprogrammer/python3 | /Tkinter GUI/tk_python01.py | 774 | 4.28125 | 4 | from tkinter import *
#creating a windows
root=Tk()
# geometry is used to create windows size
root.geometry("600x400")
# To creating a label or text you must use Label class
labelg=Label(root,text="This is windows",fg= "red", font=("Arial",20))
# fg for forground color and bg for background color to change font color
lab1=Label(root,fg="blue",text="this is another\n label",font=("Arial",20)).pack()
# .pack is used for packing on windows and displaying
labelg.pack()
lab2=Label(root,bg="gray",width="20",height="3",text="label 2" ,
fg="green",font=("Arial",18)).pack()
#minsize is used for windows size
root.minsize(480,300)
text=Label(text="This is simple windows.",font=("Arial 16")).pack()
root.mainloop()
print(" after mainloop run successfully")
| true |
ffae30c198f5a7132713304fcb3d0a2a0d4962a6 | panditprogrammer/python3 | /python78.py | 860 | 4.46875 | 4 | # slicing array in multi dimensional array in python
#video 83\
from numpy import *
# a=array([[11,13,17],
# [11,12,13],
# [21,22,23] ])
# print("array after printing")
# print(a)
# print("1st row 2nd coloum")
# b=a[1,2 ]
# print(b)
# print("2nd coloum")
# c=a[0:1,0:1]
# print(c)
x=array ([
[1,2,3,4,5,],
[11,12,13,14,15],
[21,22,23,24,25],
])
print(x)
print("0th row and all coloum\n")
n=x[ 0, : ]
print(n)
print("1th row and all coloum\n")
n=x[ 1, : ]
print(n)
print("2nd row and all coloum\n")
n=x[ 2, : ]
print(n)
print("0th coloum and all rows\n")
n=x[ :, 0 ]
print(n)
print("1st coloum and all rows \n")
n=x[ :, 1 ]
print(n)
print("2nd coloum and all rows\n")
n=x[ :, 2]
print(n)
print("3rd coloum and all rows\n")
n=x[ :, 3]
print(n)
print("4th coloum and all rows\n")
n=x[ :, 4]
print(n) | false |
26230d0e8b712a5ea37bb008e578768ed322b5c7 | jktheking/MLAI | /PythonForDataScience/ArrayBasics.py | 1,027 | 4.28125 | 4 | import numpy as np
array_1d = np.array([1, 2, 3, 4, 589, 76])
print(type(array_1d))
print(array_1d)
print("printing 1d array\n", array_1d)
array_2d = np.array([[1, 2, 3], [6, 7, 9], [11, 12, 13]])
print(type(array_2d))
print(array_2d)
print("printing 2d array\n", array_2d)
array_3d = np.array([[[1, 2, 3], [6, 7, 9]], [[11, 12, 13], [12, 19, 12]]])
print(type(array_3d))
print("printing 3d array\n")
print(array_3d)
# array multiplication, let's first see the multiplication of 2 lists
mul_list1 = [1, 2, 3, 4]
mul_list2 = [4, 3, 2, 1]
mul_list_result = list(map(lambda x, y: x*y, mul_list1, mul_list2))
print("\nmultiplication of list using lambda:", mul_list_result)
# let's see how multiplication for arrays, binary operators in numpy works element-wise.
# Note : To use binary operators on array, size of operand arrays must be dimension-wise same.
mul_array1 = np.array(mul_list1)
mul_array2 = np.array(mul_list2)
mul_array_result = mul_array1 * mul_array2;
print("\n multiplication of array:", mul_array_result)
| true |
bd48356cbcf6e50f44dd26a88b8b8e2178311ef0 | AtulRajput01/Data-Structures-And-Algorithms-1 | /sorting/python/heap-sort.py | 1,331 | 4.15625 | 4 | """
Heap Sort
Algorithm:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1.
Finally, heapify the root of the tree.
3. Repeat step 2 while the size of the heap is greater than 1.
Example Testcase - I/P - [12, 11, 13, 5, 6, 7]
O/P - 5 6 7 11 12 13
Time Complexity - O(n*Logn)
"""
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
# check if left child of root exists and is greater than root
if l < n and arr[largest] < arr[l]:
largest = l
# check if right child of root exists and is greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# swap values in needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
# heapify the root
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
# building a max heap
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
# extract elements one by one
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
# Driver code
arr = list(map(int, input().split()))
heapSort(arr)
n = len(arr)
print("Sorted array is")
print(*arr)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.