text stringlengths 37 1.41M |
|---|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
length = 1
linked_list = head
while linked_list.next is not None:
length += 1
linked_list = linked_list.next
for i in range(0, length // 2):
head = head.next
return head
|
def printFibno(n):
if(n==0):
fib = []
elif(n==1):
fib = [1]
elif(n==2):
fib = [1,1]
elif(n>2):
fib = [1,1]
i = 1
while(i< n-1):
fib.append(fib[i]+fib[i-1])
i = i +1
return fib
print(printFibno(int(input("Enter Number"))))
#another code Fibonacci Numbers
def printFibonacciNumbers(n):
f1 = 0
f2 = 1
if (n < 1):
return
for x in range(0, n):
print(f2, end = " ")
next = f1 + f2
f1 = f2
f2 = next
printFibonacciNumbers(7)
#Recussrsive Solution :
# Function for nth Fibonacci number
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
|
def fuel(mass: int):
return mass // 3 - 2
def theRocketEq(mass: int):
neededFuel = fuel(mass)
totalFuel = neededFuel
while neededFuel > 0:
neededFuel = fuel(neededFuel)
if neededFuel < 0:
break
totalFuel += neededFuel
return totalFuel
print(theRocketEq(100756))
sum = 0
with open("day1Input.txt") as f:
for i in range(100):
sum += theRocketEq(int(f.readline()))
print(sum)
|
def get_freq(str):
freq = {}
for char in str:
freq[char] = freq.get(char, 0)+1
return freq
def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
# dict1 = {}
# for digit in str(num1):
# if digit in dict1:
# dict1[digit] = dict1[digit]+1
# else:
# dict1[digit] = 1
# dict2 = {}
# for digit in str(num2):
# if digit in dict2:
# dict2[digit] = dict2[digit]+1
# else:
# dict2[digit] = 1
# return dict1 == dict2
# suggested solution:
return get_freq(str(num1)) == get_freq(str(num2))
|
import re
class Word:
def __init__(self, file_path):
self.file_path = file_path
def find_regex_match(self, pattern, path=None):
"""""
input data from the file
"""
if path is None:
path = self.file_path
with open( path, 'r' ) as file:
for line in file.readlines():
if re.findall( pattern, line, re.I ):
print(line)
return line
|
credit = int(input("Enter the value of credits: "))
if credit >= 7500:
print("Tera Leader")
elif credit >= 6000 and credit < 7500:
print("Gega Leader")
elif credit >= 4500 and credit < 6000:
print("Mega Leader")
elif credit < 4500:
print("Rising star")
|
for x in range(int(raw_input())):
word = raw_input()
if len(word) > 10:
print(word[0] + str(len(word)-2) + word[len(word)-1])
else:
print(word) |
class Group():
def __init__(self, persons):
self.persons = persons
def lil_pop(self):
self.persons -= 1
return 1
def pop(self):
if self.persons > 1:
self.persons -= 2
return 2
elif self.persons == 0:
return 0
else:
self.persons = 0
return 1
def check_pop(self):
if self.persons > 1:
return 2
elif self.persons == 0:
return 0
else:
return 1
def waiting(self):
if self.persons > 0:
return True
else:
return False
class Room():
def __init__(self):
self.available_beds = 2
self.guests = 0
def is_full(self):
if self.available_beds == 0:
return True
else:
return False
def occupied(self):
if self.available_beds < 2:
return True
else:
return False
def fits(self, number):
if self.available_beds - number >= 0:
return True
else:
return False
def insert_guests(self, number):
self.available_beds -= number
self.guests += number
class Hotel():
def __init__(self, rooms_number):
self.rooms = []
self.available_rooms = rooms_number
for x in range(rooms_number):
self.rooms.append(Room())
def insert_guests(self, guests):
if self.available_rooms > 0:
self.normal_insert(guests)
else:
self.softly_insert(guests)
def normal_insert(self, guests):
for x in range(len(self.rooms)):
if guests.waiting() and self.available_rooms > 0:
if not self.rooms[x].occupied():
if self.rooms[x].fits(guests.check_pop()):
self.rooms[x].insert_guests(guests.pop())
self.available_rooms -= 1
elif guests.waiting():
self.softly_insert(guests)
else:
return
def softly_insert(self, guests):
for x in range(len(self.rooms)):
if guests.waiting():
if not self.rooms[x].is_full():
self.rooms[x].insert_guests(guests.lil_pop())
else:
return
try:
entry = raw_input().split()
rooms = int(entry[0])
groups = int(entry[1])
if rooms == 0 or groups == 0:
exit()
my_hotel = Hotel(rooms)
for x in range(groups):
guests = int(raw_input())
my_hotel.insert_guests(Group(guests))
for x in range(len(my_hotel.rooms)):
print(my_hotel.rooms[x].guests)
exit()
except EOFError:
exit() |
def validateSI(input):
outInvalid = {
"tinNumber": input,
"validStructure": False,
"validSyntax": False,
}
if not input.isnumeric():
outInvalid["message"] = "TIN must be numeric"
return outInvalid
elif not (int(input) < 1000000 or int(input) > 9999999):
outInvalid["message"] = "TIN must be between 1000000 and 9999999 included"
return outInvalid
else:
return checkDigit(input)
def checkDigit(input):
sum = int(input[0])*8 + int(input[1])*7 + int(input[2])*6 + int(input[3])*5 + int(input[4])*4 + int(input[5])*3 + int(input[6])*2
module = sum % 11
checkDigit = 11 - module
if int(input[7]) == checkDigit:
return({
"tinNumber": input,
"validStructure": True,
"validSyntax": True,
})
else:
return({
"tinNumber": input,
"validStructure": True,
"validSyntax": False,
"message": "Check Digit failed"
})
|
import re
def validateAT(input):
tin = input
input = re.sub('[^A-Za-z0-9 ]+', '', tin)
outInvalid = {
"tinNumber": tin,
"validStructure": False,
"validSyntax": False,
}
if len(input) != 9:
outInvalid["message"] = "Invalid Length"
return outInvalid
elif not input.isnumeric():
outInvalid["message"] = "TIN must be numeric"
return outInvalid
else:
return checkDigit(input)
def checkDigit(input):
total = 0
for c in range(0,len(input[0:8])):
if c % 2 == 0:
total = total + int(input[c])*1
else:
s = int(input[c])*2
if s > 9:
s = s%10 + 1
total = total + s
unitDigit = (100 - total) % 10
if unitDigit == int(input[8]):
return({
"tinNumber": input,
"validStructure": True,
"validSyntax": True,
})
else:
return({
"tinNumber": input,
"validStructure": True,
"validSyntax": False,
"message": 'Check Digit - failed'
}) |
# Guess the number game
import random
guessesTaken = 0
print('Hello, what is your name?') # ask user their name
userName = input()
number = random.randint(1, 10)
print(userName + ', I am thinking of a number between 1 and 10.')
# create loop for user to guess up to six times on number
while guessesTaken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
# if user guesses correctly print good job message
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + userName + '! You guessed my number in ' + guessesTaken + ' guesses!')
# if user guesses wrong all six times, tell them they're wrong and what number it was
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
|
import unittest
from typing import List
def min_rectangle(sizes: List[List[int]]) -> int:
max_w, max_h = 0, 0
for w, h in sizes:
if w < h:
w, h = h, w
max_w, max_h = max(max_w, w), max(max_h, h)
return max_w * max_h
class Test(unittest.TestCase):
def test(self):
self.assertEqual(min_rectangle([[60, 50], [30, 70], [60, 30], [80, 40]]), 4000)
self.assertEqual(min_rectangle([[10, 7], [12, 3], [8, 15], [14, 7], [5, 15]]), 120)
self.assertEqual(min_rectangle([[14, 4], [19, 6], [6, 16], [18, 7], [7, 11]]), 133)
if __name__ == "__main__":
unittest.main()
|
import unittest
class Solution:
def reverseStr(self, s: str, k: int) -> str:
if len(s) < k:
return s[::-1]
return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k)
class Test(unittest.TestCase):
def test_reverseStr(self):
solution = Solution()
self.assertEqual(solution.reverseStr("abcdefg", 2), "bacdfeg")
self.assertEqual(solution.reverseStr("abcd", 2), "bacd")
if __name__ == '__main__':
unittest.main()
|
import unittest
def find_prime(n):
a = set([i for i in range(3, n+1, 2)])
for i in range(3, n+1, 2):
if i in a:
a -= set([i for i in range(i*2, n+1, i)])
return len(a) + 1
class Test(unittest.TestCase):
def test(self):
self.assertEqual(find_prime(10), 4)
self.assertEqual(find_prime(5), 3)
if __name__ == '__main__':
unittest.main()
|
"""
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.
"""
import collections
import unittest
class MyStack:
def __init__(self):
self.q = collections.deque()
def push(self, x: int) -> None:
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self) -> int:
return self.q.popleft()
def top(self) -> int:
return self.q[0]
def empty(self) -> bool:
return len(self.q) == 0
class Test(unittest.TestCase):
def test_MyStack(self):
my_stack = MyStack()
my_stack.push(1)
my_stack.push(2)
self.assertEqual(my_stack.top(), 2)
self.assertEqual(my_stack.pop(), 2)
self.assertEqual(my_stack.empty(), False)
if __name__ == "__main__":
unittest.main()
|
import unittest
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start <= end:
mid = (start + end) // 2
if nums[mid] < target:
start = mid + 1
else:
if nums[mid] == target and nums[mid-1] != target:
return mid
else:
end = mid - 1
return start
class Test(unittest.TestCase):
def test_searchInsert(self):
solution = Solution()
self.assertEqual(solution.searchInsert([1, 3, 5, 6], 5), 2)
self.assertEqual(solution.searchInsert([1, 3, 5, 6], 2), 1)
self.assertEqual(solution.searchInsert([1, 3, 5, 6], 7), 4)
self.assertEqual(solution.searchInsert([1, 3, 5, 6], 0), 0)
self.assertEqual(solution.searchInsert([1], 0), 0)
if __name__ == '__main__':
unittest.main()
|
import unittest
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = sum(nums[0:3])
d = abs(target - res)
for i in range(len(nums) - 2):
j, k = i + 1, len(nums) - 1
while j < k:
total = nums[i] + nums[j] + nums[k]
if total == target:
return total
total_d = abs(total - target)
if total_d < d:
res, d = total, total_d
if total < target:
j += 1
else:
k -= 1
return res
class Test(unittest.TestCase):
def test_threeSumClosest(self):
solution = Solution()
self.assertEqual(solution.threeSumClosest([-1, 2, 1, -4], 1), 2)
if __name__ == '__main__':
unittest.main()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
list_size = len(arr)
positive_counter = 0
zero_counter = 0
negative_counter = 0
for number in arr:
if(number > 0):
positive_counter = positive_counter + 1
elif(number == 0):
zero_counter = zero_counter + 1
elif(number < 0):
negative_counter = negative_counter + 1
print("{0:.6f}".format(positive_counter / list_size))
print("{0:.6f}".format(negative_counter / list_size))
print("{0:.6f}".format(zero_counter / list_size))
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
|
import unittest
from typing import List
def target_number(numbers: List[int], target: int) -> int:
answer = 0
queue = [[numbers[0], 0], [-1 * numbers[0], 0]]
n = len(numbers)
while queue:
temp, idx = queue.pop()
idx += 1
if idx < n:
queue.append([temp + numbers[idx], idx])
queue.append([temp - numbers[idx], idx])
else:
if temp == target:
answer += 1
return answer
class Test(unittest.TestCase):
def test(self):
self.assertEqual(target_number([1, 1, 1, 1, 1], 3), 5)
self.assertEqual(target_number([4, 1, 2, 1], 4), 2)
if __name__ == "__main__":
unittest.main()
|
import unittest
from collections import defaultdict
class TimeMap:
def __init__(self):
self.dict = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.dict[key].append([timestamp, value])
def get(self, key: str, timestamp: int) -> str:
arr = self.dict[key]
left, right = 0, len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid][0] <= timestamp:
left = mid + 1
elif arr[mid][0] > timestamp:
right = mid
return "" if right == 0 else arr[right - 1][1]
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
class TimeMapTest(unittest.TestCase):
def test_TimeMap1(self):
obj = TimeMap()
self.assertIsNone(obj.set("foo", "bar", 1))
self.assertEqual(obj.get("foo", 1), "bar")
self.assertEqual(obj.get("foo", 3), "bar")
self.assertIsNone(obj.set("foo", "bar2", 4))
self.assertEqual(obj.get("foo", 4), "bar2")
self.assertEqual(obj.get("foo", 5), "bar2")
def test_TimeMap2(self):
obj = TimeMap()
self.assertIsNone(obj.set("love", "high", 10))
self.assertIsNone(obj.set("love", "low", 20))
self.assertEqual(obj.get("love", 5), "")
self.assertEqual(obj.get("love", 10), "high")
self.assertEqual(obj.get("love", 15), "high")
self.assertEqual(obj.get("love", 20), "low")
self.assertEqual(obj.get("love", 25), "low")
if __name__ == "__main__":
unittest.main()
|
import unittest
def valid_parenthesis(s: str) -> bool:
stack = []
for c in s:
if c == "(":
stack.append(c)
else:
try:
stack.pop()
except IndexError:
return False
if stack:
return False
return True
class Test(unittest.TestCase):
def test(self):
self.assertEqual(valid_parenthesis("()()"), True)
self.assertEqual(valid_parenthesis("(())()"), True)
self.assertEqual(valid_parenthesis(")()("), False)
self.assertEqual(valid_parenthesis("(()("), False)
if __name__ == "__main__":
unittest.main()
|
import collections
import unittest
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())
class Test(unittest.TestCase):
def test_groupAnagrams(self):
solution = Solution()
self.assertCountEqual(
solution.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]),
[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']])
self.assertCountEqual(solution.groupAnagrams([""]), [[""]])
self.assertCountEqual(solution.groupAnagrams(["a"]), [["a"]])
if __name__ == '__main__':
unittest.main()
|
from .ast import BExpr, ParanExpr, NumExpr
from .lexer import *
class ParseException(Exception):
""" An Exception while parsing """
pass
class ParseError(ParseException):
""" An error that occurs during parsing """
def __init__(self, message):
self.message = message
def message(self):
return self.message
class Parser(object):
""" Recursive descent parser for the basic calculator language """
def __init__(self):
super().__init__()
def eval(self, tokens):
tokens.reverse()
return self.__parse(tokens).eval()
def __parse(self, tokens):
if len(tokens) == 0:
return tokens
expressions = []
self.__expr(tokens, expressions)
return expressions[0]
def __expr(self, tokens, expressions):
self.__term(tokens, expressions)
self.__expr_prime(tokens, expressions)
def __expr_prime(self, tokens, expressions):
top = None
try:
top = tokens[-1]
except IndexError:
return
else:
if isinstance(top, PlusOp) or isinstance(top, MinusOp):
op = self.__op1(tokens)
self.__term(tokens, expressions)
right = expressions.pop()
left = expressions.pop()
expressions.append(BExpr(left, op, right))
self.__expr_prime(tokens, expressions)
def __term(self, tokens, expressions):
self.__term_prime(tokens, expressions)
self.__term_dprime(tokens, expressions)
def __term_prime(self, tokens, expressions):
if isinstance(tokens[-1], Num):
expressions.append(self.__num(tokens))
else:
e1 = tokens.pop()
self.__expr(tokens, expressions)
e3 = tokens.pop()
expressions.append(ParanExpr(e1, expressions.pop(), e3))
def __term_dprime(self, tokens, expressions):
top = None
try:
top = tokens[-1]
except IndexError:
return
else:
if isinstance(top, MultOp) or isinstance(top, DivOp):
op = self.__op2(tokens)
self.__term_prime(tokens, expressions)
right = expressions.pop()
left = expressions.pop()
expressions.append(BExpr(left, op, right))
self.__term_dprime(tokens, expressions)
def __op1(self, tokens):
return tokens.pop()
def __op2(self, tokens):
return tokens.pop()
def __num(self, tokens):
return NumExpr(tokens.pop())
|
number = int(input("Enter a number: "))
if number == 5:
print("it's 5!")
elif number < 5:
print("so low!")
elif number > 5 and number < 20:
print("pretty decent.")
else:
print("whoa slow down! so high, take care!")
'''
flag = input("Enter 'True' or 'False': ")
flag = bool(flag)
# if the condition evaluates to True, the indented code gets executed
# otherwise it is simply skipped
if flag == True:
print("yay!")
else:
print("woop!")
print(type(flag))
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, it is a little higher than that')
# You can do whatever you want in a block ...
else:
print('No, it is a little lower than that')
# you must have guessed > number to reach here
print('Done')
# This last statement is always executed,
# after the if statement is executed.
'''
|
# As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line.
word = input("Please enter a word: ")
x = 0
while x < len(word):
i = 1
print(word[len(word) - i])
i = i + 1
x = x + 1
'''
users = {'mary': 22, 'caroline': 26, 'harry': 20}
# let's make them age for 30 years each!
for user, age in users.items():
aged = age + 30
print(user, aged)
'''
'''
my_list = [1, 2, 3, "hello", "it's blue!", 10]
for i in my_list:
print(i)
'''
|
'''
If a runner runs 10 miles in 30 minutes and 30 seconds,
What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km)
'''
distance_ran_miles = 10
time_taken_seconds = (30 * 60) + 30
time_taken_hours = (time_taken_seconds/60)/60
speed_in_miles = distance_ran_miles/time_taken_hours
print(speed_in_miles)
speed_in_kilometres = speed_in_miles * 1.6
print("The runners' speed in kilometres per hour is " + str(round(speed_in_kilometres, 2)))
|
'''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it out, otherwise
come back to this task after you have learned about loops)
'''
num = 0
num_list = []
while num < 10:
num_enter = int(input("Enter a number: "))
num_list.append(num_enter)
num = num + 1
# prints the largest number in the list
max_num = max(num_list)
print(max_num)
# prints the sum of all the numbers in the list
x = 0
for i in num_list:
x = x + i
print(x)
'''
num_1 = int(input("Enter a number: "))
num_2 = int(input("Enter a number: "))
num_3 = int(input("Enter a number: "))
num_4 = int(input("Enter a number: "))
num_5 = int(input("Enter a number: "))
num_list = [num_1, num_2, num_3, num_4, num_5]
'''
|
users = {'mary': 22, 'caroline': 26, 'harry': 22}
print(users['mary']) # using the key to return the value of key 'mary'
users['harry'] = 20 # changing the original value of 'harry'
print(users['harry'])
for user, age in users.items():
print(user, age)
for user, age in users.items():
age = age + 10
print(user, age)
for k in users.keys(): # returns just the keys
print(k)
for v in users.values(): # returns just the values
print(v)
dict_to_list = list(users) # converts a dictionary to a list
print(dict_to_list)
dict_to_tuple = tuple(users) # converts a dictionary to a tuple
print(dict_to_tuple)
dict_to_set = set(users) # converts a dictionary to a tuple
print(dict_to_set)
cars = {'Honda': 22, "Toyota": 15, " Suzuki": 7, "BMW": 12}
cars2 = cars.copy()
print(cars2)
cars2.clear()
print(cars2)
cars3 = cars.fromkeys('Sazuki', "Honda")
print(cars3)
print(cars.get('Honda'))
cars.update({'Honda': 27, 'Mazda' : 32})
print(cars)
|
import random
randomlist = []
randomlist2 = []
for i in range(0,20):
n = random.randint(1,20)
m= random.randint(1,20)
randomlist.append(n)
randomlist2.append(m)
print(randomlist)
print(randomlist2)
p= random.randint(1,40)
# list_1 = [1,2,3,4,5,6,7,8]
# list_2 = [9,2,5,59,56,6,8,1]
list_1 =randomlist
list_2 =randomlist2
multi = lambda x:x*2
adder = lambda x,y:x+y
result = list(map(adder,list_1,list_2))
print(result) |
# importing required libraries gui based
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
# create a Window class
class Window(QMainWindow):
# constructor
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100,
300, 500)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for components
def UiComponents(self):
# turn
self.turn = 0
# times
self.times = 0
# creating a push button list
self.push_list = []
# creating 2d list
for _ in range(3):
temp = []
for _ in range(3):
temp.append((QPushButton(self)))
# adding 3 push button in single row
self.push_list.append(temp)
# x and y co-ordinate
x = 90
y = 90
# traversing through push button list
for i in range(3):
for j in range(3):
# setting geometry to the button
self.push_list[i][j].setGeometry(x*i + 20,
y*j + 20,
80, 80)
# setting font to the button
self.push_list[i][j].setFont(QFont(QFont('Times', 17)))
# adding action
self.push_list[i][j].clicked.connect(self.action_called)
# creating label to tel the score
self.label = QLabel(self)
# setting geometry to the label
self.label.setGeometry(20, 300, 260, 60)
# setting style sheet to the label
self.label.setStyleSheet("QLabel"
"{"
"border : 3px solid black;"
"background : white;"
"}")
# setting label alignment
self.label.setAlignment(Qt.AlignCenter)
# setting font to the label
self.label.setFont(QFont('Times', 15))
# creating push button to restart the score
reset_game = QPushButton("Reset-Game", self)
# setting geometry
reset_game.setGeometry(50, 380, 200, 50)
# adding action action to the reset push button
reset_game.clicked.connect(self.reset_game_action)
# method called by reset button
def reset_game_action(self):
# resetting values
self.turn = 0
self.times = 0
# making label text empty:
self.label.setText("")
# traversing push list
for buttons in self.push_list:
for button in buttons:
# making all the button enabled
button.setEnabled(True)
# removing text of all the buttons
button.setText("")
# action called by the push buttons
def action_called(self):
self.times += 1
# getting button which called the action
button = self.sender()
# making button disabled
button.setEnabled(False)
# checking the turn
if self.turn == 0:
button.setText("X")
self.turn = 1
else:
button.setText("O")
self.turn = 0
# call the winner checker method
win = self.who_wins()
# text
text = ""
# if winner is decided
if win == True:
# if current chance is 0
if self.turn == 0:
# O has won
text = "O Won"
# X has won
else:
text = "X Won"
# disabling all the buttons
for buttons in self.push_list:
for push in buttons:
push.setEnabled(False)
# if winner is not decided
# and total times is 9
elif self.times == 9:
text = "Match is Draw"
# setting text to the label
self.label.setText(text)
# method to check who wins
def who_wins(self):
# checking if any row crossed
for i in range(3):
if self.push_list[0][i].text() == self.push_list[1][i].text() \
and self.push_list[0][i].text() == self.push_list[2][i].text() \
and self.push_list[0][i].text() != "":
return True
# checking if any column crossed
for i in range(3):
if self.push_list[i][0].text() == self.push_list[i][1].text() \
and self.push_list[i][0].text() == self.push_list[i][2].text() \
and self.push_list[i][0].text() != "":
return True
# checking if diagonal crossed
if self.push_list[0][0].text() == self.push_list[1][1].text() \
and self.push_list[0][0].text() == self.push_list[2][2].text() \
and self.push_list[0][0].text() != "":
return True
# if other diagonal is crossed
if self.push_list[0][2].text() == self.push_list[1][1].text() \
and self.push_list[1][1].text() == self.push_list[2][0].text() \
and self.push_list[0][2].text() != "":
return True
#if nothing is crossed
return False
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
|
# Number
# string
# list
# dict
# tuple
# set
a=2345
b=374.3
print(type (a),a)
print(type (b),b)
name="this is a car can't for flying"
print(type(name),name)
c= 'This is a single qoutes "string" '
d=" double we can use \n for new line "
e="""This
is also
multiline for paragraph writing
"""
f="she is asking me i \"like you\" "
print(type(c),c)
print(d)
print(e)
print(f)
# List is here list can hold every thing
list=[1,2,3,"A",5.6,{"name:""Aman"}, (),[] ]
print(type(list),list)
print(type(list[3]))
print(type(list[4]))
print(type(list[5]))
print(type(list[6]))
print(type(list[7]))
# 3- Lists
# test_list = [1,1.1,'string',{},(),[]]
#
# print(test_list[5])
# 4- Dictionaries(Objects)
# dic_test = {'key':'value','key2':2}
# print(dic_test)
# print(dic_test['key2'])
list2=[1,{"key1":"value_1"}]
# in the list we can access object by this method
print(list2[1]["key1"])
my_dic={"key1":"valu1"}
print(my_dic["key1"]) |
"""Tests for samplesheet.py"""
from fluffy import samplesheet
def test_get_separator_space():
"""Test to get a separator"""
# GIVEN a line with spaces
line = "one two three"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert space is returned
assert sep == " "
def test_get_separator_csv():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one,two,three"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert comma is returned
assert sep == ","
def test_get_separator_tab():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one\ttwo\tthree"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert None is returned
assert sep is None
def test_get_separator_semi():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one;two;three"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert None is returned
assert sep is None
def test_get_separator_unknown():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one.two.three"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert None is returned
assert sep is None
def test_get_sample_col():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one two SampleID"
# WHEN finding the sample col
col_nr = samplesheet.get_sample_col(line.split(" "))
# THEN assert correct col nr is returned
assert col_nr == 2
def test_get_sample_name():
"""Test to get a separator"""
# GIVEN a line with commas as delimiter
line = "one two SampleName"
# WHEN finding the sample col
col_nr = samplesheet.get_sample_name_col(line.split(" "))
# THEN assert correct col nr is returned
assert col_nr == 2
|
def my_sum(*val):
result = 0
for x in val:
result = result + x
return result
print(my_sum(1, 4, 5))
|
"""
Closest Pair of Points XY Plane
- closest_pair_2d: Divide and Conquer in xy plane
- bf_closest_pair_2d: Brute force in xy plane
"""
import math
import random
from .utils import min_of_pairs
class Point(object):
"""
Point class of 2d: x and y
"""
def __init__(self, x, y, *args):
self.x = x
self.y = y
def __repr__(self):
return f"({self.x}, {self.y})"
def __eq__(self, o):
return self.x == o.x and self.y == o.y
def __getitem__(self, key):
if key == 0:
return self.x
elif key == 1:
return self.y
else:
raise IndexError()
def __len__(self):
return 2
@staticmethod
def distance(point_a, point_b):
"""Return dist of two points"""
return math.sqrt((point_a.x - point_b.x)**2 +
(point_a.y - point_b.y)**2)
@staticmethod
def get_unique_points(size):
"""Generate list of random and unique points"""
x = random.sample(range(-size*10, size*10), size)
y = random.sample(range(-size*10, size*10), size)
return [Point(a, b) for a, b in zip(x, y)]
def bf_closest_pair_2d(points):
"""
Wrapper for bruteforce approach to get minimal distance of two points.
Parameters
----------
points (list): List of Point
Return
------
{"distance": float, "pair": Point}
"""
return bf_closest_2d(points, 0, len(points) - 1)
def bf_closest_2d(points, low, high):
"""
Bruteforce approach to get minimal distance of two points.
Minumum size is 2 (high - low >= 1), else exception IndexError is raised.
Time Complexity: O(n^2)
Parameters
----------
points (list): List of Point
low (int): Start index (inclusive)
high (int): End index (inclusive)
Return
------
{"distance": float, "pair": Point}
"""
# raise exception if points is less than 2 elements (high is inclusive)
if high - low <= 0:
raise IndexError()
# set minimal pair as the first two elements
min_dist = Point.distance(points[low], points[low + 1])
min_points = (points[low], points[low + 1])
# iterate if points has more than 2 elements
if high - low > 1:
for i in range(low, high): # skip last element compare b/c redundant
for j in range(i + 1, high + 1):
dist = Point.distance(points[i], points[j])
if dist < min_dist:
min_dist = dist
min_points = (points[i], points[j])
return {"distance": min_dist, "pair": min_points}
def closest_pair_2d(points):
"""
Find closest_2d pair in points using divide and conquer.
Timsort: O(nlogn)
Closest: O(nlogn)
Time Complexity: O(nlogn)
Return
------
{"distance": float, "pair": Point}
"""
# sort points by x and y via python's Timsort: O(nlogn)
points_xsorted = sorted(points, key=lambda point: point.x)
points_ysorted = sorted(points, key=lambda point: point.y)
return closest_2d(points_xsorted, 0, len(points_xsorted) - 1, points_ysorted)
def closest_2d(points_xsorted, low, high, points_ysorted):
"""
Recursively find the closest_2d pair of points in points_xsorted and with
points_ysorted for the strip in the middle.
Recurrence relation: T(n) = 2T(n/2) + n
Time Complexity: O(nlogn)
Parameters
----------
points_xsorted (list): List of Point sorted by x-coordinate
low (int): Start index for points_xsorted (inclusive)
high (int): End index for points_xsorted (inclusive)
points_ysorted (list): List of Point sorted by y-coordinate
Return
------
{"distance": float, "pair": Point}
"""
# base case: use brute force on size 3 or less
if high - low + 1 <= 3:
return bf_closest_2d(points_xsorted, low, high)
# initializations
mid = (low + high) // 2
mid_point = points_xsorted[mid]
points_yleft, points_yright = [], []
# split points_ysorted by middle of points_xsorted's midpoint
for point in points_ysorted:
if point.x <= mid_point.x:
points_yleft.append(point)
else:
points_yright.append(point)
# recurse to find local minimal pairs on left and right
min_pair_left = closest_2d(points_xsorted, low, mid, points_yleft)
min_pair_right = closest_2d(points_xsorted, mid + 1, high, points_yright)
# get the smaller of the two local minimal pairs
min_pair = min_of_pairs(min_pair_left, min_pair_right)
# build strip array to find points smaller than delta from x-coord to mid
delta = min_pair["distance"]
strip = [p for p in points_ysorted if abs(p.x - mid_point.x) < delta]
# return min_pair or smaller if found in strip
return strip_closest_2d(strip, min_pair)
def strip_closest_2d(strip, min_pair):
"""
Find closest_2d pair in strip. Sparsity geneeralization by Jon Louis Bentley
and Michael Ian Shamos.
Time Complexity: O(7n)
Parameters
----------
strip (list): A strip of list of Points around median within delta
min_pair (dict): Minimal distance of two Points
Correctness Proof
-----------------
Need to only compare at most 7 comparisons per point by correctness proof
Let a list be bisected into two halves.
Let d = delta, the closest_2d pair's distance of two halves in the list.
Then create a strip from the middle to delta distance on either side.
This strip has been pre-sorted by y-coordinate.
Populate points where x-coord from middle to within delta distance.
Because the points are within d, then in a d x 2d rectangle, there can only
be 1 point per d/2 x d/2 square.
Therefore, a point can have at most 7 points to compare to find a new pair
that's less than delta wide. Points larger than delta wide are irrelevant.
Because the strip has already been sorted by y-coordinate, you only need
to iterate a point to 7 other sequential point comparisons.
Illustration
------------
Let's consider a rectangle of d by 2d in the strip along the middle.
Let's compare point X to every other point in the rectangle, which is at
most 7 points.
y-coord
|
. . . . | . . . .
. | .
. | . <--- strip
.___ ___|___ ___.
d high |_4_|_5_|_6_|_7_|
___ ___|_X_|_1_|_2_|_3_|___ ___ x-coord
. | .
.<-- 2d wide -->.
Return
------
{"distance": float, "pair": Point}
"""
strip_min_dist = min_pair["distance"]
strip_min_points = min_pair["pair"]
for i in range(len(strip) - 1): # skip last element compare
for j in range(i + 1, min(i + 7, len(strip))):
dist = Point.distance(strip[i], strip[j])
if dist < strip_min_dist:
strip_min_dist = dist
strip_min_points = (strip[i], strip[j])
return {"distance": strip_min_dist, "pair": strip_min_points}
def closest_pair_2d_opt(points):
"""
Find closest_2d pair in points using divide and conquer using optimized strip
calculation.
Optimized version does not consider duplicate points.
Timsort: O(nlogn)
Closest: O(nlogn)
Time Complexity: O(nlogn)
Return
------
{"distance": float, "pair": Point}
"""
# sort points by x and y via python's Timsort: O(nlogn)
points_xsorted = sorted(points, key=lambda point: point.x)
points_ysorted = sorted(points, key=lambda point: point.y)
return closest_opt(points_xsorted, 0, len(points_xsorted) - 1, points_ysorted)
def closest_opt(points_xsorted, low, high, points_ysorted):
"""
Recursively find the closest_2d pair of points in points_xsorted and with
points_ysorted for the strip in the middle.
Uses optimized strip calculation.
Recurrence relation: T(n) = 2T(n/2) + n
Time Complexity: O(nlogn)
Parameters
----------
points_xsorted (list): List of Point sorted by x-coordinate
low (int): Start index for points_xsorted (inclusive)
high (int): End index for points_xsorted (inclusive)
points_ysorted (list): List of Point sorted by y-coordinate
Return
------
{"distance": float, "pair": Point}
"""
# base case: use brute force on size 3 or less
if high - low + 1 <= 3:
return bf_closest_2d(points_xsorted, low, high)
# initializations
mid = (low + high) // 2
mid_point = points_xsorted[mid]
points_yleft, points_yright = [], []
# split points_ysorted by middle of points_xsorted's midpoint
for point in points_ysorted:
if point.x <= mid_point.x:
points_yleft.append(point)
else:
points_yright.append(point)
# recurse to find local minimal pairs on left and right
min_pair_left = closest_opt(points_xsorted, low, mid, points_yleft)
min_pair_right = closest_opt(points_xsorted, mid + 1, high, points_yright)
# get the smaller of the two local minimal pairs
min_pair = min_of_pairs(min_pair_left, min_pair_right)
# build strip array to find points smaller than delta from x-coord to mid
delta = min_pair["distance"]
strip_left = [p for p in points_yleft if abs(p.x - mid_point.x) < delta]
strip_right = [p for p in points_yright if abs(p.x - mid_point.x) < delta]
# return min_pair or smaller if found in strip
return strip_closest_opt(strip_left, strip_right, min_pair)
def strip_closest_opt(strip_left, strip_right, min_pair):
"""
Find closest_2d pair in strip using hopscotch approach by Jose C. Pereira
and Fernando G. Lobo.
Time Complexity: O(2n)
Parameters
----------
strip_left (list): A strip of Points left side of median within delta.
strip_right (list): A strip of Points right side of median within delta.
min_pair (dict): Minimal distance of two Points
Correctness Proof
-----------------
Because each side of median do not need to compare itself, then points
on each side need only compare points on the opposite side.
Let d = delta and in a d x 2d box where left is d x d and right is d x d.
Suppose the left side has a point X of interest and the right side has a
maximum of 4 points of interest. Then, point X need only to compare the
closest_2d 2/4 points. The other farther 2 points are larger than delta.
Similarly, the same reasoning can be applied when right has 3 points.
Therefore, only 2 comparisons are needed per point on either side.
Illustration
------------
Let left = {X}, right = {1, 2, 3, 4}.
Point X to point 1 and point 2 are within delta distance.
Point X to point 3 and point 4 are larger than delta distance.
Therefore, X need only compare to point 1 and point 2.
y-coord
|
. . . . | . . . .
. | .
. | . <--- strip
.___ ___|___ ___.
d high |___|___|_2_|_3_|
___ ___|___|_X_|_1_|_4_|___ ___ x-coord
. | .
.<-- 2d wide -->.
NOTE
----
Worse Case Scenario:
When all points are on the same axis, such as all vertical points
where x=C for some constant C, then strip_right is empty.
Because the strip is already by y-coord, then there only need one for loop
of n comparisons on strip_left.
Therefore, time complexity is O(n).
Return
------
{"distance": float, "pair": Point}
"""
strip_min_dist = min_pair["distance"]
strip_min_points = min_pair["pair"]
# if strip_left and strip_right is not empty
if strip_left and strip_right:
# init left and right indices
l, r = 0, 0
# while there are still points in strip_left or strip_right
while l < len(strip_left) and r < len(strip_right):
left, right = strip_left[l], strip_right[r]
dist = Point.distance(left, right)
if dist < strip_min_dist:
strip_min_dist = dist
strip_min_points = (left, right)
# if left is lower than or same level as right
if left.y <= right.y:
# when there's still point on the otherside
if r + 1 < len(strip_right):
right = strip_right[r+1]
dist = Point.distance(left, right)
if dist < strip_min_dist:
strip_min_dist = dist
strip_min_points = (left, right)
l += 1
# else right is lower than left
else:
# when there's still point on the other side
if l + 1 < len(strip_left):
left = strip_left[l+1]
dist = Point.distance(left, right)
if dist < strip_min_dist:
strip_min_dist = dist
strip_min_points = (left, right)
r += 1
# else there is only strip_left
elif strip_left and not strip_right:
for i in range(len(strip_left) - 1): # skip last element compare
dist = Point.distance(strip_left[i], strip_left[i+1])
if dist < strip_min_dist:
strip_min_dist = dist
strip_min_points = (strip_left[i], strip_left[i+1])
return {"distance": strip_min_dist, "pair": strip_min_points}
# -------------------------------------------
# METHODS BELOW FOR VISUALIZATION RUN PROGRAM
# -------------------------------------------
def bf_pairs_2d(points):
"""
Creates a permutation list of all pairs of points with distance.
Used for visual run program.
Return [(Point, Point, float)]
"""
return _bf_pairs_2d(points, 0, len(points) - 1)
def _bf_pairs_2d(points, low, high):
"""
Creates a permutation list of all pairs of points with distance.
Used for visual run program.
Return [(Point, Point, float)]
"""
# raise exception if points is less than 2 elements (high is inclusive)
if high - low <= 0:
raise IndexError()
pairs = []
# iterate if points has more than 2 elements
if high - low > 1:
for i in range(low, high): # skip last element compare b/c redundant
for j in range(i + 1, high + 1):
dist = Point.distance(points[i], points[j])
pairs.append((points[i], points[j], dist))
return pairs
def closest_pair_2d_opt_plt(points, pause_t):
"""
Matplotlib version to show how middle points are selected.
Used for visual run program.
Parameters
pause_t (float): Number of seconds to pause at each recursion
"""
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle, Patch
# presort points by x-coord and y-coord
points_xsorted = sorted(points, key=lambda point: point.x)
points_ysorted = sorted(points, key=lambda point: point.y)
# matplotlib
plt.ion()
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.73, 0.75]) # add space for legend
# add title and legend
ax.set_title("Divide and Conquer")
left_patch = Patch(color="aqua", label="Left")
right_patch = Patch(color="lime", label="Right")
strip_patch = Patch(color="tomato", label="Strip")
mid_patch = Patch(color="violet", label="Middle")
ax.legend(handles=[left_patch, right_patch, strip_patch, mid_patch],
bbox_to_anchor=(1, 1), loc="upper left", frameon=False)
# prepare x, y arrays for plot
plt_x, plt_y = [], []
for point in points:
plt_x.append(point.x)
plt_y.append(point.y)
# add plot line with scatter style
ax.plot(plt_x, plt_y, linestyle="None", marker="o", c="black")
# preadd empty plot line (scatter style) for marking min_pair
ax.plot([], [], linestyle="None", marker="o", c="black")
# preadd invis vertical line
ax.axvline(x=0, linewidth=0, c="violet")
# preadd invis rectangle to plot
rect_h = points_ysorted[-1].y - points_ysorted[0].y
rect = Rectangle(xy=(0, points_ysorted[0].y), width=0, height=rect_h,
linewidth=0, color='aqua', fill=False)
ax.add_patch(rect)
# do closest_2d pair of points with matplotlib
min_pair = closest_2d_opt_plt(points_xsorted, 0, len(points_xsorted) - 1,
points_ysorted, ax, pause_t)
# show plot after recursion
plt.show(block=True)
return min_pair
def closest_2d_opt_plt(points_xsorted, low, high, points_ysorted, ax, pause_t):
"""
Matplotlib version to show minimal pair at each recursion level.
Used for visual run program.
Parameters
----------
plt_x (array): 1D array of x values
plt_y (array): 1D array of y values
pause_t (float): Number of seconds to pause at each recursion
rect_y (float): Rectangle lower y coordinate for boundary
rect_h (float): Rectangle height for boundary
"""
from matplotlib import pyplot as plt
# base case: use brute force on size 3 or less
if high - low + 1 <= 3:
return bf_closest_2d(points_xsorted, low, high)
# initializations
mid = (low + high) // 2
mid_point = points_xsorted[mid]
points_yleft, points_yright = [], []
# split points_ysorted by middle of points_xsorted's midpoint
for point in points_ysorted:
if point.x <= mid_point.x:
points_yleft.append(point)
else:
points_yright.append(point)
# recurse to find local minimal pairs on left
min_pair_left = closest_2d_opt_plt(points_xsorted, low, mid,
points_yleft, ax, pause_t)
# get last plot line and rectangle
line = ax.get_lines()[-2]
vline = ax.get_lines()[-1]
rect = ax.patches[-1]
# plot minimal pair on the left
min_points = min_pair_left['pair']
x = [min_points[0].x, min_points[1].x]
y = [min_points[0].y, min_points[1].y]
plt.pause(pause_t)
ax.set_title(f"Midpoint: ({mid_point.x}, {mid_point.y})\n"
f"Min left: {min_pair_left['distance']:.2f}\n")
line.set_data(x, y)
line.set_color("aqua")
# draw rectangle boundary
rect.set_xy((points_xsorted[low].x, rect.get_y()))
rect.set_linewidth(1)
rect.set_width(abs(mid_point.x - points_xsorted[low].x))
rect.set_color("aqua")
# change vertical line position and make visible
vline.set_xdata([mid_point.x])
vline.set_linewidth(1)
# recurse to find local minimal pairs on right
min_pair_right = closest_2d_opt_plt(points_xsorted, mid + 1, high,
points_yright, ax, pause_t)
# plot minimal pair on the right
min_points = min_pair_right['pair']
x = [min_points[0].x, min_points[1].x]
y = [min_points[0].y, min_points[1].y]
plt.pause(pause_t)
ax.set_title(f"Midpoint: ({mid_point.x}, {mid_point.y})\n"
f"Min right: {min_pair_right['distance']:.2f}\n")
line.set_data(x, y)
line.set_color("lime")
# draw rectangle boundary
rect.set_xy((mid_point.x, rect.get_y()))
rect.set_width(abs(mid_point.x - points_xsorted[high].x))
rect.set_color("lime")
# change vertical line position
vline.set_xdata([mid_point.x])
# get the smaller of the two local minimal pairs
min_pair = min_of_pairs(min_pair_left, min_pair_right)
# build strip array to find points smaller than delta from x-coord to mid
delta = min_pair["distance"]
strip_left = [p for p in points_yleft if abs(p.x - mid_point.x) < delta]
strip_right = [p for p in points_yright if abs(p.x - mid_point.x) < delta]
# try to find a pair that's smaller than min_pair in the strip
min_pair = strip_closest_opt(strip_left, strip_right, min_pair)
# plot minimal pair
min_points = min_pair['pair']
x = [min_points[0].x, min_points[1].x]
y = [min_points[0].y, min_points[1].y]
plt.pause(pause_t)
ax.set_title(f"Midpoint: ({mid_point.x}, {mid_point.y})\n"
f"Combined min: {min_pair['distance']:.2f}\n"
f"Delta: {delta:.2f}")
line.set_data(x, y)
line.set_color("tomato")
# draw rectangle boundary
rect.set_xy((mid_point.x - delta, rect.get_y()))
rect.set_width(2*delta)
rect.set_color("tomato")
# return the smaller of min_pair and strip_min_pair
return min_pair
|
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("tic tac toe game")
root.iconbitmap("D:/tkinter/tic tac toe/game.ico")
root.geometry("1350x750")
root.config(background="skyblue")
#frame for showing title of game
frame1 = Frame(root,bg="cadet blue",width=1350,height=100,pady=2,relief=RIDGE)
frame1.grid(row=0,column=0)
#frame for body of game
frame2 = Frame(root,bg="powder blue",width=1350,height=600,pady=2,relief=RIDGE)
frame2.grid(row=1,column=0)
#label to show title
gametitle = Label(frame1,font=("arial",50,"bold"),text="GUI Tic toc toe game",padx=20,pady=10,fg="red")
gametitle.grid(row=0,column=0)
#inserting right and left side frames
rightframe = Frame(frame2,bd=10,width=560,height=500,padx=10,pady=2,relief=RIDGE,bg="cadet blue")
rightframe.pack(side="right")
leftframe = Frame(frame2,bd=10,width=750,height=500,padx=10,pady=2,relief=RIDGE,bg="cadet blue")
leftframe.pack(side="left")
#partitioning right frame
rightframe1 = Frame(rightframe,bd=10,width=600,height=230,padx=10,pady=2,relief=RIDGE,bg="green")
rightframe1.grid(row=0,column=0)
rightframe2 = Frame(rightframe,bd=10,width=600,height=230,padx=10,pady=2,relief=RIDGE,bg="green")
rightframe2.grid(row=1,column=0)
#declaring player variables
playerx=IntVar()
player0=IntVar()
playerx.set(0)
player0.set(0)
buttons = StringVar()
click = True
def check(buttons):
global click
if buttons['text'] == " " and click == True:
buttons['text'] = 'X'
click = False
score()
if buttons['text'] == " " and click == False:
buttons['text'] = 'O'
click = True
score()
def score():
if button1['text']=="X" and button2['text'] == "X" and button3["text"] == "X":
button1.configure(background="red")
button2.configure(background="red")
button3.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button4['text']=="X" and button5['text'] == "X" and button6["text"] == "X":
button4.configure(background="red")
button5.configure(background="red")
button6.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button7['text']=="X" and button8['text'] == "X" and button9["text"] == "X":
button7.configure(background="red")
button8.configure(background="red")
button9.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button1['text']=="X" and button5['text'] == "X" and button9["text"] == "X":
button1.configure(background="red")
button5.configure(background="red")
button9.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button3['text']=="X" and button5['text'] == "X" and button7["text"] == "X":
button3.configure(background="red")
button5.configure(background="red")
button7.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button1['text']=="X" and button4['text'] == "X" and button7["text"] == "X":
button1.configure(background="red")
button4.configure(background="red")
button7.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button3['text']=="X" and button6['text'] == "X" and button9["text"] == "X":
button3.configure(background="red")
button6.configure(background="red")
button9.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
if button2['text']=="X" and button5['text'] == "X" and button8["text"] == "X":
button2.configure(background="red")
button5.configure(background="red")
button8.configure(background="red")
n = float(playerx.get())
value = n+1
playerx.set(value)
messagebox.showinfo("status","player x won")
#checking for player 0
if button1['text']=="O" and button2['text'] == "O" and button3["text"] == "O":
button1.configure(background="red")
button2.configure(background="red")
button3.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player 0 won")
if button4['text']=="O" and button5['text'] == "O" and button6["text"] == "O":
button4.configure(background="red")
button5.configure(background="red")
button6.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player 0 won")
if button7['text']=="O" and button8['text'] == "O" and button9["text"] == "O":
button7.configure(background="red")
button8.configure(background="red")
button9.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player 0 won")
if button1['text']=="O" and button5['text'] == "O" and button9["text"] == "O":
button1.configure(background="red")
button5.configure(background="red")
button9.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player 0 won")
if button3['text']=="O" and button5['text'] == "O" and button7["text"] == "O":
button3.configure(background="red")
button5.configure(background="red")
button7.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player 0 won")
if button1['text']=="O" and button4['text'] == "O" and button7["text"] == "O":
button1.configure(background="red")
button4.configure(background="red")
button7.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player x won")
if button3['text']=="O" and button6['text'] == "O" and button9["text"] == "O":
button3.configure(background="red")
button6.configure(background="red")
button9.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player x won")
if button2['text']=="O" and button5['text'] == "O" and button8["text"] == "O":
button2.configure(background="red")
button5.configure(background="red")
button8.configure(background="red")
n = float(player0.get())
value = n+1
player0.set(value)
messagebox.showinfo("status","player x won")
def reset():
button1['text']=" "
button2['text']=" "
button3['text']=" "
button4['text']=" "
button5['text']=" "
button6['text']=" "
button7['text']=" "
button8['text']=" "
button9['text']=" "
click = True
#changing color
button1.configure(background="powder blue")
button2.configure(background="powder blue")
button3.configure(background="powder blue")
button4.configure(background="powder blue")
button5.configure(background="powder blue")
button6.configure(background="powder blue")
button7.configure(background="powder blue")
button8.configure(background="powder blue")
button9.configure(background="powder blue")
def new():
reset()
playerx.set(0)
player0.set(0)
#adding player names in rightframe1
label1 = Label(rightframe1,text="playerx:",font="arial,40,bold")
label1.grid(row=0,column=0,pady=10)
e1 = Entry(rightframe1,width=20,textvariable=playerx,font="arial,40,bold")
e1.grid(row=0,column=1,padx=10)
label2 = Label(rightframe1,text="playerx:",font="arial,40,bold")
label2.grid(row=1,column=0,pady=10)
e2 = Entry(rightframe1,width=20,textvariable=player0,font="arial,40,bold")
e2.grid(row=1,column=1,padx=10)
#declaring reset and new game button
buttonreset = Button(rightframe2,text="reset",bg="blue",font=("arial",20,"bold"),height=3,width=20,command=reset)
buttonreset.grid(row=0,column=0)
buttonnewgame = Button(rightframe2,text="new game",bg="blue",font=("arial",20,"bold"),height=3,width=20,command=new)
buttonnewgame.grid(row=1,column=0)
#declaring buttons in right frame for playing game
button1 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button1))
button1.grid(row=0,column=0,sticky=S+N+W+E)
button2 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button2))
button2.grid(row=0,column=1,sticky=S+N+W+E)
button3 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button3))
button3.grid(row=0,column=2,sticky=S+N+W+E)
button4 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button4))
button4.grid(row=1,column=0,sticky=S+N+W+E)
button5 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button5))
button5.grid(row=1,column=1,sticky=S+N+W+E)
button6 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button6))
button6.grid(row=1,column=2,sticky=S+N+W+E)
button7 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button7))
button7.grid(row=2,column=0,sticky=S+N+W+E)
button8 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button8))
button8.grid(row=2,column=1,sticky=S+N+W+E)
button9 = Button(leftframe,text=" ",bg="powder blue",font=("arial",20,"bold"),height=3,width=8,command=lambda:check(button9))
button9.grid(row=2,column=2,sticky=S+N+W+E)
root.mainloop() |
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("binding events")
root.iconbitmap("icons/superman.ico")
root.geometry("400x400")
def clicked(event):
Label(root,text="button clicked"+" "+str(event.x)+" "+str(event.y)+" "+event.char+" ",font=("arial",20)).pack()
button = Button(root,text="click",bg="green",fg="cyan",font=("Helvetica",25)
)
button.bind("<Button-3>",clicked)
button.bind("<Button-1>",clicked)
button.bind("<Enter>",clicked)
button.bind("<Leave>",clicked)
button.bind("<FocusIn>",clicked)
button.bind("Return",clicked)
button.bind("<Key>",clicked)
button.pack()
Button(root,text="Exit").pack()
root.mainloop() |
from tkinter import *
root = Tk()
e = Entry(root,width=50)
e.insert(0,"enter here")
e.pack()
def clicked():
hello="hello"+" "+e.get()
mylabel=Label(root,text=hello,fg="blue")
mylabel.pack()
button=Button(root,text="click here",command=clicked)
button.pack()
root.mainloop() |
from random import randint
import random
answer_list = []
global list1
global rando
list1 = ['ntr_np','ntr_tem','ntr_jlk','prabhas','mahesh_sri',
'mahesh_ban','mahesh_maha']
names = {"ntr_np":'nanakuprematho',"ntr_tem":'temper',"ntr_jlk":'jailavakusa',
"prabhas":'saaho',"mahesh_sri":'srimanthudu',"mahesh_ban":'bharath ane nenu',"mahesh_maha":'maharshi'}
#creating a random int
count=1
while count<4:
rando = randint(0,len(list1)-1)
answer = list1[rando]
print(answer,"is selected")
list1.remove(list1[rando])
answer_list.append(list1[rando])
count+=1
print(answer_list) |
side=float(input())
area=side**2
perimeter=4*side
print("Area of square",area)
print("Perimeter of square",perimeter)
|
def max3(arr):
arr = sorted(arr, reverse=True)
return arr[:3]
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
max_number= max3(numbers_list)
for num in max_number:
print(num) |
"""Module to fetch weather information"""
import requests as rq
def lookup_weather(city, day, month, year, api_key):
"""Get weather information for a place at a given date, using the
World Weather Online API. This API is limited to 500 calls / user / day.
Parameters
----------
city : string
day : int
month : int
year : int
api_key : string
Returns
-------
json response
"""
# Build parameters dictionary
date_string = "{}-{}-{}".format(year, str(month).zfill(2), str(day).zfill(2))
params = {
"q": city,
"date": date_string,
"key": api_key,
"format": "json",
}
# Fetch data with GET request
url = "http://api.worldweatheronline.com/premium/v1/past-weather.ashx"
response = rq.get(url, params)
return response.json()
def extract_weather_info(json):
"""Extract useful features from a JSON response for a World Weather Online
API call.
Parameters
----------
json : dict
Returns
-------
min_temp : int
minimal temperature in Celsius degrees
max_temp : int
maximal temperature in Celsius degrees
uv_index : int
UV index
hourly : dict
dictionary containing hourly info, with the following format:
{
time: {
'temp': t,
'windspeed': ws,
'humidity': hp,
'precip': milli,
'description': desc
}
}
"""
try:
weather = json['data']['weather'][0]
# Extract general information
min_temp = int(weather['mintempC'])
max_temp = int(weather['maxtempC'])
uv_index = int(weather['uvIndex'])
# Extract hourly information
hourly = {}
for hweather in weather['hourly']:
time = hweather['time']
temp = int(hweather['tempC'])
ws = int(hweather['windspeedKmph'])
hp = int(hweather['humidity'])
milli = float(hweather['precipMM'])
desc = ""
if len(hweather['weatherDesc']) > 0:
desc = hweather['weatherDesc'][0]['value']
hourly[time] = {
'temp': temp,
'windspeed': ws,
'humidity': hp,
'precip': milli,
'description': desc
}
return min_temp, max_temp, uv_index, hourly
except KeyError:
#print("error during parsing of weather info from API")
raise Exception
|
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
im = np.array(Image.open('empire.jpg'))
plt.imshow(im)
x = [100,100,400,400]
y = [200,500,200,500]
plt.plot(x, y, 'r*')
plt.plot(x[:2], y[:2])
plt.axis('off')
plt.title('Plotting: "empire.jpg"')
plt.savefig('plot2img_axis-off.jpg')
plt.show()
|
# Task 1
# The greatest number
# Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
import random as rd
our_num = list()
n = 0
while n < 20:
numbers = rd.randint(0, 1000)
n = n+1
our_num.append(numbers)
print(our_num)
print('Largest element in list is ',max(our_num))
|
__all__ = ['Heart']
class Heart(object):
def __init__(self, size):
self.size = size
def get_distance(self, point):
x, y, z = point
x /= self.size * 0.43
y /= self.size * 0.43
z /= self.size * 0.43
res = 320 * ((-x**2 * z**3 - 9*y**2 * z**3/80) +
(x**2 + 9*y**2/4 + z**2-1)**3)
return res
def get_distance_numpy(self, x, y, z):
raise NotImplementedError
if __name__ == "__main__":
h = Heart(20)
for y in range(-15, 15):
s = ''
for x in range(-30, 30):
d = h.get_distance((x * 0.5, 0, -y))
if d < 0:
s += 'x'
else:
s += '.'
print(s)
|
print('{{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x4100 + x + y * 18) + ', ', end='')
print(' },')
print('},{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x6200 + x + y * 18) + ', ', end='')
print(' },')
print('}};')
|
#根据GFF3文件统计外显子大小和数量以及内含子大小
#1.每个基因的外显子起始与结束的位置,保存为1.txt,注意需要打开1.txt编辑删除第一行的空行
output_file = open("1.txt", "w")
with open('test.gff3', 'r') as f:
for line in f:
line = line.rstrip("\n") # 删除行尾的换行符
array = line.split("\t")
sub_array = array[8].split(";")
name = sub_array[1].replace('name=','')
if array[2] == 'gene':
output_file.write("\n")
output_file.write(name + "\t" + array[0] + "\t" + array[3] + "\t" + array[4] + "\t" + array[6] + "\t")
if array[2] == 'exon':
output_file.write(array[3] + "\t" + array[4] + "\t")
output_file.close()
f.close()
#2.计算每个外显子的大小
with open('1.txt', 'r') as f, open("count_exon_size.txt", "w") as f1:
for line in f:
lin = line.strip().split()
a = len(lin)
for i in range(6, a, 2):
exon = int(lin[i]) - int(lin[i-1]) + 1
f1.write(lin[0]+"\t"+str(exon)+"\n")
f.close()
#3.计算每个内含子的大小
with open('1.txt', 'r') as f1, open("count_intron_size.txt", "w") as f2:
for line in f1:
lin = line.strip().split()
a = len(lin)
if a == 7:
f2.write(lin[0]+"\t"+'0'+"\n")
if a > 7:
if lin[4] == '+':
for i in range(7, a, 2):
intron = abs(int(lin[i]) - int(lin[i-1]) - 1)
f2.write(lin[0]+"\t"+str(intron)+"\n")
if lin[4] == '-':
for i in range(8, a, 2):
intron = abs(int(lin[i]) + 1 - int(lin[i - 3]))
f2.write(lin[0] + "\t" + str(intron) + "\n")
f1.close()
#4.统计每个基因外显子的数量
with open('1.txt', 'r') as f1, open("count_per_exon_in_gene.txt", "w") as f2:
for line in f1:
lin = line.strip().split()
a = len(lin)
n = (a - 5)/2
f2.write(lin[0]+"\t" + str(n) + "\n")
f2.close()
f1.close() |
"""
给定一棵二叉树,返回其节点值的后序遍历。
例如:
给定二叉树 [1,null,2,3],
1
\
2
/
3
返回 [3,2,1]。
注意: 递归方法很简单,你可以使用迭代方法来解决吗?
"""
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stackNode = []
node = root
markNode = None
res = []
while stackNode or node:
while node:
stackNode.append(node)
node = node.left
node = stackNode.pop()
if node.right is None or node.right is markNode:
res.append(node.val)
markNode = node
node = None
else:
stackNode.append(node)
node = node.right
return res
|
'''
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
'''
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
if len(self.stack2) == 0:
self.stack2.append(node)
elif node < self.stack2[-1]:
self.stack2.append(node)
else:
self.stack2.append(self.stack2[-1])
# write code here
def pop(self):
if self.stack1 == None:
return None
self.stack2.pop()
return self.stack1.pop()
# write code here
def top(self):
return self.stack1[-1]
# write code here
def min(self):
return self.stack2[-1]
# write code here
s = Solution()
s.push(3)
s.min()
s.push(4)
s.min()
s.push(2)
s.min()
s.push(3)
s.min()
s.pop()
s.min()
s.pop()
s.min()
s.pop()
s.min()
s.push(0)
print(s.min())
|
'''
请实现一个函数按照之字形打印二叉树,
即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def printTree(self, root):
if root == None:
return
result, nodes = [], [root]
right = True
while nodes:
curStack, nextStack = [], []
if right:
for node in nodes:
curStack.append(node.val)
if node.left:
nextStack.append(node.left)
if node.right:
nextStack.append(node.right)
else:
for node in nodes:
curStack.append(node.val)
if node.right:
nextStack.append(node.right)
if node.left:
nextStack.append(node.left)
nextStack.reverse()
right = not right
result.append(curStack)
nodes = nextStack
return result
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
S = Solution()
print(S.printTree(pNode1)) |
"""
time: O(log(m+n)
"""
class Solution:
def median_of_two_sorted_array(self, num1, num2):
size1 = len(num1)
size2 = len(num2)
if (size1 + size2) % 2 == 0:
return (self.find_k_th(num1, size1, num2, size2, (size1 + size2) // 2 + 1) + self.find_k_th(num1, size1,
num2, size2,
(size1 + size2) // 2)) / 2
else:
return self.find_k_th(num1, size1, num2, size2, (size1 + size2) // 2)
def find_k_th(self, num1, size1, num2, size2, k):
if len(num1) > len(num2):
return self.find_k_th(num2, size2, num1, size1, k)
if len(num1) == 0:
return num2[k - 1]
if k == 1:
return min(num1[0], num2[0])
k1 = min(k // 2, size1)
k2 = k - k1
if num1[k1 - 1] > num2[k2 - 1]:
return self.find_k_th(num1, size1, num2[k2:], size2 - k2, k - k2)
elif num1[k1 - 1] < num2[k2 - 1]:
return self.find_k_th(num1[k1:], size1 - k1, num2, size2, k - k1)
else:
return num1[k1 - 1]
s = Solution()
print(s.median_of_two_sorted_array([1, 2, 3, 4, 5], [2, 3, 4]))
print(s.median_of_two_sorted_array([1, 2, 3, 4, 5], [6, 7, 8]))
print(s.find_k_th([1, 2, 3, 4, 5], 5, [2, 3, 4], 3, 1))
|
'''
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
if root is None or root.val > expectNumber:
return []
if root.left is None and root.right is None:
if expectNumber == root.val:
return [[root.val]]
else:
return []
left = self.FindPath(root.left, expectNumber - root.val)
right = self.FindPath(root.right, expectNumber - root.val)
a = left + right
return [[root.val] + x for x in a]
|
'''
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def FindPath(self, root,target):
if root == None:
return
if root.left == None and root.right == None:
if root.val == target:
return [[root.val]]
else:
return []
a = self.FindPath(root.left, target-root.val) + self.FindPath(root.right,target-root.val)
return [[root.val] + i for i in a]
pNode1 = TreeNode(10)
pNode2 = TreeNode(5)
pNode3 = TreeNode(12)
pNode4 = TreeNode(4)
pNode5 = TreeNode(7)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
S = Solution()
print(S.FindPath(pNode1, 22)) |
'''
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,
重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution1:
def deleteDuplication(self, pHead):
if not pHead:
return pHead
res = []
while pHead:
res.append(pHead.val)
pHead = pHead.next
res = list(filter(lambda c: res.count(c) == 1, res))
dumpy = ListNode(0)
pre = dumpy
for i in res:
node = ListNode(i)
pre.next = node
pre = pre.next
return dumpy.next
class Solution2:
def deleteDuplication(self, pHead):
dummy = ListNode(None)
dummy.next = pHead
curr = dummy
while curr:
has_dup = False
# Remove duplicates and leave the last of the duplicates.
while curr.next and curr.next.next and curr.next.val == curr.next.next.val:
curr.next = curr.next.next
has_dup = True
if has_dup:
# Remove the last duplicate
curr.next = curr.next.next
else:
curr = curr.next
return dummy.next
a = ListNode(1)
b = ListNode(1)
c = ListNode(1)
d = ListNode(2)
e = ListNode(3)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution2()
print(s.deleteDuplication(a))
class Solution3:
def deleteDuplication(self, pHead):
if pHead is None or pHead.next is None:
# 首先判断是否为空,或是否只有一个结点。
return pHead
if pHead.val != pHead.next.val:
# 如果当前结点值不等于下一结点值,则该结点保留并返回
pHead.next = self.deleteDuplication(pHead.next)
else:
# 否则从下一个结点开始寻找下一个不重复的结点。找到后返回,并判断是否与当前结点相等。
temp = self.deleteDuplication(pHead.next.next)
if temp is not None and pHead.val == temp.val:
pHead = None
else:
pHead = temp
return pHead
|
'''
输入一个链表,反转链表后,输出链表的所有元素。
'''
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
last = None
while pHead:
temp = pHead.next
pHead.next = last
last = pHead
pHead = temp
return last
a = ListNode(3)
b = ListNode(1)
c = ListNode(4)
d = ListNode(2)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
g = s.ReverseList(a)
while g:
print(g.val)
g = g.next
|
def power1(base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
result = power1(base, exponent >>1)
result *= result
if exponent & 1 ==1:
result *= base
return result
print(power1(2,16))
|
'''
把只包含因子2、3和5的数称作丑数(Ugly Number)。
例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
'''
"""
解题思路:
丑数是另一个丑数乘以2 3 5 的结果
因此我们可以每个丑数分别乘以2 3 5
对于乘以2而言,一定存在某个丑数,排在它前面的每个丑数都小于当前已有丑数,在它之后每个丑数乘以2得到的结果都会太大
我们只需要记录这个值
对于3 5 类似
"""
class Solution:
def GetUglyNumber_Solution(self, index):
if index <= 0:
return 0
n = 1
uglyNumber = [1] * index
index2, index3, index5 = 0, 0, 0
while n < index:
minVal = min(uglyNumber[index2] * 2, uglyNumber[index3] * 3, uglyNumber[index5] * 5)
uglyNumber[n] = minVal
while uglyNumber[index2] * 2 <= uglyNumber[n]:
index2 += 1
while uglyNumber[index3] * 3 <= uglyNumber[n]:
index3 += 1
while uglyNumber[index5] * 5 <= uglyNumber[n]:
index5 += 1
n += 1
return uglyNumber[-1]
def isUgly(self, num):
while num % 2 == 0:
num /= 2
while num % 3 == 0:
num /= 5
while num % 3 == 0:
num /= 5
return True if num == 1 else False
def GetUglyNumber(self, index):
number = 0
found = 0
while found < index:
number += 1
found += 1 if self.isUgly(number) else 0
return number
|
'''
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。
HF作为牛客的资深元老,自然也准备了一些小游戏。
其中,有个游戏是这样的:
首先,让小朋友们围成一个大圈。
然后,他随机指定一个数m,让编号为0的小朋友开始报数。
每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,
从他的下一个小朋友开始,继续0...m-1报数....
这样下去....
直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。
请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
'''
class Solution:
def LastRemaining_Solution(self, n, m):
if n == 1:
return 0
else:
return (self.LastRemaining_Solution(n - 1, m) + m) % n
def LastRemaining_Solution2(self, n, m):
if n < 1 or m < 1:
return -1
last = 0
for i in range(1, n + 1):
last = (last + m) % i
return last
s = Solution()
print(s.LastRemaining_Solution2(4000, 997))
#
def josephus(n, m):
if type(n) != type(1) or n <= 0:
raise Exception('n must be an integer(n > 0)')
if n == 1:
return 0
else:
return (josephus(n - 1, m) + m) % n
# print(josephus(4000,997))
|
'''
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),
返回结果为复制后复杂链表的head。
(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
'''
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if pHead == None:
return pHead
self.cloneNode(pHead)
self.connectNode(pHead)
return self.reConnectNode(pHead)
def cloneNode(self, pHead):
while pHead:
Cloned = RandomListNode(0)
Cloned.label = pHead.label
Cloned.next = pHead.next
pHead.next = Cloned
pHead = Cloned.next
def connectNode(self, pHead):
while pHead:
Cloned = pHead.next
if pHead.random:
Cloned.random = pHead.random.next
pHead = Cloned.next
def reConnectNode(self, pHead):
cloneHead = cloneNode = pHead.next
pHead.next = cloneNode.next
pHead = pHead.next
while pHead:
cloneNode.next = pHead.next
cloneNode = pHead.next
pHead.next = cloneHead.next
pHead = pHead.next
return cloneHead
|
'''
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
'''
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convert(self,root):
if root == None:
return root
if not root.left and not root.right:
return root
def convert_node(self, tree, last):
if not tree:
return None
if tree.left:
last = self.convert_node(tree.left, last)
if last:
last.right = tree
|
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
@staticmethod
def level_order(root):
if root is None:
return []
cur = [root]
next = []
result = []
while cur:
for node in cur:
if node.left:
next.append(node.left)
if node.right:
next.append(node.right)
result.append(node.val)
cur = next
next = []
return result
@staticmethod
def level_order_2(root):
if root is None:
return []
cur = [root]
result = []
while cur:
node = cur.pop(0)
if node.left:
cur.append(node.left)
if node.right:
cur.append(node.right)
result.append(node.val)
return result
@staticmethod
def level_order_3(root):
if root is None:
return []
cur = [root]
result = []
while cur:
size = len(cur)
level = []
for i in range(size):
node = cur.pop(0)
if node.left:
cur.append(node.left)
if node.right:
cur.append(node.right)
level.append(node.val)
result.append(level)
return result
@staticmethod
def zig_order(root):
if root is None:
return []
cur = [root]
next = []
result = []
is_odd = True
while cur:
for node in cur:
if is_odd:
if node.right:
next.append(node.right)
if node.left:
next.append(node.left)
else:
if node.left:
next.append(node.left)
if node.right:
next.append(node.right)
result.append(node.val)
cur = next
next = []
is_odd = False if is_odd else True
return result
s = Solution()
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
e = TreeNode(5)
f = TreeNode(6)
a.left = b
a.right = c
b.left = d
b.right = e
print(s.level_order(a))
print(s.level_order_2(a))
print(s.level_order_3(a))
print(s.zig_order(a))
|
'''
一只青蛙一次可以跳上1级台阶,也可以跳上2级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
'''
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
if number < 2:
return number
a, b, c = 1, 0, 0
for i in range(1, number + 1):
c = a + b
b = a
a = c
return c
|
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def reverseList(self, node):
if node ==None or node.next == None:
return node
last = None
while node:
temp = node.next
node.next = last
last = node
node = temp
return last
a = ListNode(3)
b = ListNode(1)
c = ListNode(4)
d = ListNode(2)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
g = s.reverseList(a)
while g:
print(g.val)
g = g.next
|
'''
一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1。
将这个栈转置后,从栈顶到栈底为1、2、3、4、5,也就是实现栈中元素的逆序,
但是只能用递归函数实现,不能使用其他数据结构。
'''
'''
解决思路
首先实现一个递归函数 a,其功能是返回并移除栈底元素。
之后再实现一个递归函数 b,其功能是不断用递归的临时变量去接住 a 函数返回的栈底元素,
这样,最后一个栈底元素就是原来栈的栈顶元素,
之后一层一层的将递归中的临时变量压入栈中,这样就实现了逆序。
'''
class Solution:
def getAndRemoveLastElement(self, stack):
result = stack.pop()
if len(stack) == 0:
return result
else:
i = self.getAndRemoveLastElement(stack)
stack.append(result)
return i
def reverse(self,stack):
if len(stack) ==0:
return
i = self.getAndRemoveLastElement(stack)
self.reverse(stack)
stack.append(i)
return stack
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode(self, pHead, pNode):
if not pHead or not pNode:
return
if pNode == pHead:
pHead = pHead.next
elif pNode.next != None:
pNode.val = pNode.next.val
pNode.next = pNode.next.next
else:
Node = pHead
while Node.next != pNode:
Node = Node.next
Node.next = None
return pHead
|
"""
给一个只包含 '(' 和 ')' 的字符串,找出最长的有效(正确关闭)括号子串的长度。
对于 "(()",最长有效括号子串为 "()" ,它的长度是 2。
另一个例子 ")()())",最长有效括号子串为 "()()",它的长度是 4。
"""
"""
解题思路:
定义个start变量来记录合法括号串的起始位置,
我们遍历字符串,如果遇到左括号,则将当前下标压入栈,
如果遇到右括号,
如果当前栈为空,则将下一个坐标位置记录到start,
如果栈不为空,则将栈顶元素取出,
此时若栈为空,则更新结果和i - start + 1中的较大值,否
则更新结果和i - 栈顶元素中的较大值,
"""
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
size = len(s)
if size <= 1:
return 0
stack = []
start = 0
res = 0
for i in range(size):
if s[i] == "(":
stack.append(i)
else:
if len(stack) == 0:
start = i + 1
else:
stack.pop()
res = max(res, i - start + 1) if len(stack) == 0 else max(res, i - stack[-1])
return res
a=')()())'
s = Solution()
print(s.longestValidParentheses(a)) |
class Solution:
"""
@param numbers: Give an array numbers of n integer
@return: Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
if len(numbers) < 3:
return []
numbers.sort()
res = set()
for i, v in enumerate(numbers):
if i >= 1 and v == numbers[i - 1]:
continue
d = {}
for x in numbers[i + 1:]:
if x not in d:
d[-v - x] = 1
else:
res.add([v, -v - x, x])
return res
def threeSum2(self, numbers):
# write your code here
res = []
numbers.sort()
for i in range(len(numbers) - 1):
if i > 0 and numbers[i] == numbers[i - 1]:
continue
l, r = i + 1, len(numbers) - 1
while l < r:
s = numbers[i] + numbers[l] + numbers[r]
if s < 0:
l += 1
elif s >0:
r -= 1
else:
res.append((numbers[i], numbers[l], numbers[r]))
while l < r and numbers[l] == numbers[l + 1]:
l += 1
while l < r and numbers[r] == numbers[r - 1]:
r -= 1
l += 1
r -= 1
return res |
'''
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
{[2,3,4],2,6,2,5,1},
{2,[3,4,2],6,2,5,1},
{2,3,[4,2,6],2,5,1},
{2,3,4,[2,6,2],5,1},
{2,3,4,2,[6,2,5],1},
{2,3,4,2,6,[2,5,1]}。
'''
class Solution:
def maxInWindows(self, num, size):
if len(num) == 0:
return []
if size == 0 or len(num) < size:
return []
res = []
for i in range(len(num) - size + 1):
res.append(max(num[i:i + size]))
return res
|
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
'''
def getMoreHalfNumber(num):
hash = dict()
length = len(num)
for n in num:
hash[n] = hash[n] + 1 if hash.get(n) else 1
if hash[n] > length/2:
return n
a = [1,2,3,2,2,2,5,4,2,3,3,3]
print(getMoreHalfNumber(a))
|
def DisplayMenu():
print("DisplayMenu")
def ReadFile():
print("ReadFile")
NoOfAttempt = 0
while NoOfAttempt<3:
DisplayMenu()
choice = int(input("Make your choice:"))
if choice == 1:
ReadFile()
elif choice == 2:
print("Add customer code")
elif choice == 3:
print("Search customer code")
elif choice == 4:
NoOfAttempt = 3
NoOfAttempt+=1
print("NoOfAttempt",NoOfAttempt) |
fileHandler = open('records.txt','r') # to open pre-existing text file
id= input("enter the id you want to search") # string datatype
rec=fileHandler.readline() # reads the firsdt record of file
found=False # boolean variable
while(len(rec)>0):
list=rec.split('#') # split the record and shift in the list
if (list[0]==id):
print(list[1])
found=True
rec=fileHandler.readline()
if found==False:
print("Student ID not found")
#Task 3
fileHandler = open('records.txt','r') # to open pre-existing text file
id= input("enter the first two letters of Id which you want to search") # string datatype
rec=fileHandler.readline() # reads the firsdt record of file
found=False # boolean variable
while(len(rec)>0):
list=rec.split('#') # split the record and shift in the list
if (list[0][:2]==id):
print(list[1])
found=True
rec=fileHandler.readline()
if found==False:
print("Student ID not found")
|
# -*- coding: utf-8 -*-
# Two friends Anna and Brian, are deciding how to split the bill at a dinner.
# Each will only pay for the items they consume. Brian gets the check and
# calculates Anna's portion. You must determine if his calculation is correct.
#
# For example, assume the bill has the following prices: bill = [2, 4, 6].
# Anna declines to eat item k = bill[2] which costs '6'. If Brian calculates the
# bill correctly, Anna will pay (2 + 4) / 2 = 3. If he includes the cost of
# bill[2], he will calculate (2 + 4 + 6) / 2 = 6. In the second case, he should
# refund 3 to Anna.
#
# Function Description
#
# Complete the 'bonAppetit' function in the editor below. It should print
# 'Bon Appetit' if the bill is fairly split. Otherwise, it should print the
# integer amount of money that Brian owes Anna.
#
# 'bonAppetit' has the following parameter(s):
#
# * 'bill': an array of integers representing the cost of each item ordered
# * 'k': an integer representing the zero-based index of the item Anna doesn't eat
# * 'b' the amount of money that Anna contributed to the bill
#
# Input Format
#
# The first line contains two space-separated integers 'n' and 'k', the number
# of items ordered and the 0-based index of the item that Anna did not eat.
#
# The second line contains 'n' space-separated integers bill[i] where 0 <= i <= n.
#
# The third line contains an integer, 'b', the amount of money that Brian
# charged Anna for her share of the bill.
#
# Constraints
#
# 2 <= n <= 10^5
# 0 <= k < n
# 0 <= bill[i] <= 10^4
# 0 <= b <= sum(bill[i])
# The amount of money due Anna will always be an integer
#
# Output Format
#
# If Brian did not overcharge Anna, print 'Bon Appetit' on a new line; otherwise,
# print the difference (i.e., b_charged - b_actual) that Brian must refund to
# Anna. This will always be an integer.
#
# Sample Input 0
#
# 4 1
# 3 10 2 9
# 12
#
# Sample Output 0
#
# 5
#
# Explanation 0
#
# Anna didn't eat item bill[1] = 10, but she shared the rest of the items with
# Brian. The total cost of the shared items is 3 + 2 + 9 = 14 and, split in half,
# the cost per person is b_actual = 7. Brian charged her b_charged = 12 for her
# portion of the bill. We print the amount Anna was overcharged,
# b_charged - b_actual = 12 - 7 = 5, on a new line.
#
# Sample Input 1
#
# 4 1
# 3 10 2 9
# 7
#
# Sample Output 1
#
# Bon Appetit
#
# Explanation 1
#
# Anna didn't eat item bill[1] = 10, but she shared the rest of the items with
# Brian. The total cost of the shared items is 3 + 2 + 9 = 14 and, split in half,
# the cost per person is b_actual = 7. Because b_actual = b_charged = 7, we print
# 'Bon Appetit' on a new line.
#!/bin/python3
#
# Complete the 'bonAppetit' function below.
#
# The function accepts following parameters:
# 1. INTEGER_ARRAY bill
# 2. INTEGER k
# 3. INTEGER b
#
def bonAppetit(bill, k, b):
sum = 0
b_actual = 0
b_charged = b
for i in range(len(bill)):
if i != k:
sum += bill[i]
b_actual = int(sum / 2)
if b_actual == b_charged:
print('Bon Appetit')
else:
print('{}'.format(b_charged - b_actual))
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
k = int(first_multiple_input[1])
bill = list(map(int, input().rstrip().split()))
b = int(input().strip())
bonAppetit(bill, k, b)
|
# -*- coding: utf-8 -*-
# [collections.Counter()](https://docs.python.org/2/library/collections.html#collections.Counter)
#
# A counter is a container that stores elements as dictionary keys, and their
# counts are stored as dictionary values.
#
# Sample Code
#
# >>> from collections import Counter
# >>>
# >>> myList = [1, 1, 2, 3, 4, 5, 3, 2, 3, 4, 2, 1, 2, 3]
# >>> print Counter(myList)
# Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})
# >>>
# >>> print Counter(myList).items()
# [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)]
# >>>
# >>> print Counter(myList).keys()
# [1, 2, 3, 4, 5]
# >>>
# >>> print Counter(myList).values()
# [3, 4, 4, 2, 1]
#
# Task
#
# Raghu is a shoe shop owner. His shop has 'X' number of shoes.
# He has a list containing the size of each shoe he has in his shop.
# There are 'N' number of customers who are willing to pay 'x_i' amount of money
# only if they get the shoe of their desired size.
#
# Your task is to compute how much money Raghu earned.
#
# Input Format
#
# The first line contains 'X', the number of shoes.
# The second line contains the space separated list of all the shoe sizes in the
# shop.
# The third line contains 'N', the number of customers.
# The next 'N' lines contain the space separated values of the 'shoe size'
# desired by the customer and 'x_i', the price of the shoe.
#
# Contraints
#
# 0 < X < 10^3
# 0 < N <= 10^3
# 20 < x_i < 100
# 2 < shoe size < 20
#
# Output Format
#
# Print the amount of money earned by Raghu.
#
# Sample Input
#
# 10
# 2 3 4 5 6 7 6 5 18
# 6
# 6 55
# 6 45
# 6 55
# 4 40
# 18 60
# 10 50
#
# Sample Output
#
# 200
#
# Explanation
#
# Customer 1: Purchased size 6 shoe for $55.
# Customer 2: Purchased size 6 shoe for $45.
# Customer 3: Size 6 shoe no longer available, so no purchase.
# Customer 4: Purchased size 4 shoe for $40.
# Customer 5: Purchased size 18 shoe for $60.
# Customer 6: Size 10 not available, so no purchase.
#
# Total money earned = $55 + $45 + $40 + $60 = $200
from collections import Counter
if __name__ == '__main__':
X = int(input())
INVENTORY = Counter(map(int, input().split()))
N = int(input())
REVENUE = 0
for i in range(N):
SIZE_I, PRICE_I = map(int, input().split())
SIZE_COUNT = INVENTORY[SIZE_I]
if SIZE_COUNT > 0:
REVENUE += PRICE_I
INVENTORY[SIZE_I] = SIZE_COUNT - 1
print(REVENUE)
|
# -*- coding: utf-8 -*-
# You are given the first name and last name of a person on two different lines.
# Your task is to read them and print the following:
#
# Hello firstname lastname! You just delved into python.
#
# Input Format
#
# The first line contains the first name, and the second line contains the last
# name.
#
# Constraints
#
# The length of the first and last name <= '10'.
#
# Output Format
#
# Print the output as mentioned above.
#
# Sample Input
#
# Ross
# Taylor
#
# Sample Output
#
# Hello Ross Taylor! You just delved into python.
#
# Explanation
#
# The input read by the program is stored as a string data type. A string is a
# collection of characters.
def print_full_name(a, b):
print(f'Hello {a} {b}! You just delved into python.')
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name)
|
# -*- coding: utf-8 -*-
# Read an integer 'N'.
#
# Without using any string methods, try to print the following:
#
# 123...N
#
# Note that "..." represents the values in between.
#
# Input Format
#
# The first line contains an integer 'N'.
#
# Output Format
#
# Output the answer as explained in the task.
#
# Sample Input
#
# 3
#
# Sample Output
#
# 123
if __name__ == '__main__':
n = int(input())
for i in range(1, n + 1):
print(i, end='')
print()
|
def replicate_iter(times, data):
if ((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))):
raise ValueError("Invalid argument")
if(times <= 0):
return []
else:
result = []
for i in range(1, times+1):
result.append(data)
return result
def replicate_recur(times, data):
if ((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))):
raise ValueError("Invalid argument")
if (times <= 0):
return []
else:
result = replicate_recur(times-1, data)
result.append(data)
return result |
import sys
import numpy as np
import matplotlib.pyplot as plt
def get_params(filename):
print("Getting parameters. Opening file...")
file = open(filename)
file_str = file.read()
file.close()
'''
Params presumed to be
pow_i pow_f np
a dtype
Where the pows are the powers of 10 at which to start and end checking dx = 10^pow
np is the number of steps with which to span pow_i -> pow_f
a is the constant multiplying x in the argument of the exponent.
dtype is the datatype to use when storing/manipulating data.
'''
params = [ _.split(" ") for _ in file_str.split("\n")[:-1]]
print("Params:", params)
params[0] = [float(_) for _ in params[0]]
params[1] = [float(params[1][0]), np.dtype(params[1][1])]
print("Parameters obtained.")
return params
def get_2side_der(y, dx, n):
y_roll = np.roll(y, -int(2*n))
#Doing (y_roll - y)/(2*n*dx) creates the derivative.
#For example (y_roll[0] - y[0])/(2*n*dx) = (f(x_2n) - f(x_0))/(2n*dx) = f'(x_n)
y_der_num = (y_roll - y)/(2*n*dx)
#Cut off the last 2*n because they consist of nonsensical stuff like f(x_(N-2n))-f(x_0) and that
y_der_num = y_der_num[:int(-2*n)]
return y_der_num
def get_composite_2side_der(y, dx, dtype):
y_2side_der_1dx = get_2side_der(y, dx, np.float32(1).astype(dtype))
y_2side_der_2dx = get_2side_der(y, dx, np.float32(2).astype(dtype))
#The array of derivatives made using points 1 dx away from x will have two more points than the array of derivatives
#made using points 2*dx away from x so need to trim those off
y_2side_der_1dx = y_2side_der_1dx[1:-1]
y_composite_der = (4*y_2side_der_1dx - y_2side_der_2dx)/3
return y_composite_der
def main():
#Open parameter file and get params
argv = sys.argv
[[p_i, p_f, n_p], [a, dtype]] = get_params(argv[1])
a = np.float64(a).astype(dtype)
#Get all the p with which we want to try dx = 10^p
p_range = np.linspace(p_i, p_f, int(n_p))
print("p_range: ", p_range)
err_list = []
for i in range(len(p_range)):
dx = np.float64(10**p_range[i]).astype(dtype)
#Generate x and y for true function
x = np.array([1-2*dx, 1-dx, 1.0, 1+dx, 1+2*dx])
y = np.exp(a*x, dtype=dtype)
#generate true f'
y_der_t = a*y
#(I guess this will only deal with f(x) = c*exp(ax) for now since that's the relevant example and you kind of
#need to know the true derivative of the function you're examining beforehand)
#Compute numerical composite derivative of f for the current dx
y_composite_der = get_composite_2side_der(y, dx, dtype)
# print("Size of y_composite_der: ", len(y_composite_der))
#Compute mean error for this dx
err = np.abs(y_der_t[2] - y_composite_der)
err_list.append(err)
print("Obtained error for " + str(i+1) + " p out of " + str(len(p_range)))
plt.plot(p_range, err_list)#, p_range, n_xstep_list)
plt.show()
if __name__ == "__main__":
main() |
from Graph import Node
from heapq import heappush,heappop,heapify
#Note: This algoritm uses either Dijkstra or A*
#it all depends if the start node has a defined goal
#which can be used to calculate the heuristic cost
def graphSearch(start,goals):
d=[]
heapify(d)
#start.cost=0
f=[start]
heapify(f)
while len(f)>0:
n=heappop(f)
for goal in goals:
if((abs(n.x-goal.x)+abs(n.y-goal.y))<=start.step):
d.append(n)
return (d,f)
if not n in d:
d.append(n)
children=n.children()
#print(children)
for node in children:
if((not (node in f)) and (not (node in d))):
heappush(f,node)
elif(node in f):
if(node.cost()<f[f.index(node)].cost()):
f[f.index(node)]=node
return d
|
# imports
from requests import get
from bs4 import BeautifulSoup
import os
import pandas as pd
def get_blog_posts():
filename = './codeup_blog_posts.csv'
# check for presence of the file or make a new request
if os.path.exists(filename):
return pd.read_csv(filename)
else:
return make_new_request()
def make_dictionary_from_article(url):
# Set header and user agent to increase likelihood that your request get the response you want
headers = {'user-agent': 'Codeup Bayes Instructor Example'}
# This is the actual HTTP GET request that python will send across the internet
response = get(url, headers=headers)
# response.text is a single string of all the html from that page
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.get_text()
body = soup.select("div.mk-single-content.clearfix")[0].get_text()
output = {}
output["title"] = title
output["body"] = body
return output
def make_new_request():
urls = [
"https://codeup.com/codeups-data-science-career-accelerator-is-here/",
"https://codeup.com/data-science-myths/",
"https://codeup.com/data-science-vs-data-analytics-whats-the-difference/",
"https://codeup.com/10-tips-to-crush-it-at-the-sa-tech-job-fair/",
"https://codeup.com/competitor-bootcamps-are-closing-is-the-model-in-danger/",
]
output = []
for url in urls:
article_dictionary = make_dictionary_from_article(url)
output.append(article_dictionary)
df = pd.DataFrame(output)
df.to_csv('./codeup_blog_posts.csv')
return df
|
'''
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order.
Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?
'''
import string
total_sum = 0
alphabets = {}
capwords = string.ascii_uppercase
for index, value in enumerate(capwords):
alphabets.update({capwords[index]: index + 1})
with open('names.txt', 'r') as names:
lines = [name.strip('"') for name in names.read().strip('\n').split(',')]
lines.sort()
for line in lines:
total_sum += sum([alphabets[li] for li in line]) * (lines.index(line) + 1)
print(total_sum)
|
class Pattern_Two:
'''Pattern two
1 1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
'''
def __init__(self, strings='1', steps=10):
self.steps = steps
if isinstance(strings, str):
self.strings = strings
else: # If provided 'strings' is integer then converting it to string
self.strings = str(strings)
def method_one(self):
print('\nMethod One')
for step in range(self.steps, 0, -1):
print(' '.join(self.strings * step))
def method_two(self):
print('\nMethod Two')
steps = self.steps
while steps > 0:
print(' '.join(self.strings * steps))
steps -= 1
if __name__ == '__main__':
pattern_two = Pattern_Two()
pattern_two.method_one()
pattern_two.method_two()
|
class Pattern_Eight:
'''Pattern eight
P
P r
P r o
P r o g
P r o g r
P r o g r a
P r o g r a m
P r o g r a m m
P r o g r a m m i
P r o g r a m m i n
P r o g r a m m i n g
P r o g r a m m i n
P r o g r a m m i
P r o g r a m m
P r o g r a m
P r o g r a
P r o g r
P r o g
P r o
P r
P
'''
def __init__(self, strings='Programming'):
if isinstance(strings, str):
self.strings = strings
else: # If provided 'strings' is integer then converting it to string
self.strings = str(strings)
self.length = len(self.strings)
def method_one(self):
print('\nMethod One')
for i in range(1, self.length + 1):
print(' '.join(self.strings[:i]))
if i == self.length:
for j in range(self.length - 1, 0, -1):
print(' '.join(self.strings[:j]))
def method_two(self):
print('\nMethod Two')
i, j = 1, self.length - 1
while i != self.length + 1:
print(' '.join(self.strings[:i]))
if i == self.length:
while j != 0:
print(' '.join(self.strings[:j]))
j -= 1
i += 1
if __name__ == '__main__':
pattern_eight = Pattern_Eight()
pattern_eight.method_one()
pattern_eight.method_two()
|
import collections
class Count_Letter:
def __init__(self, strings):
self.strings = strings
def method_one(self):
'''Using for loop'''
dic = {}
for string in self.strings:
if string in dic:
dic[string] += 1 # If a character exists in dic then increasing its count by 1.
else:
dic[string] = 1 # Else assigning its count to 1.
keys = [key for key in dic.keys()] # Ssorting keys of dic alphabetically so that we can print keys and values in order.
keys.sort()
for key in keys:
print('{} : {}'.format(key, dic[key]))
def method_two(self):
'''Using built-in module : collections :'''
dic = collections.Counter(self.strings)
keys = [key for key in dic.keys()] # Ssorting keys of dic alphabetically so that we can print keys and values in order.
keys.sort()
for key in keys:
print('{} : {}'.format(key, dic[key]))
if __name__ == '__main__':
count = Count_Letter('pneumonoultramicroscopicsilicovolcanoconiosis')
print('Method One')
count.method_one()
print('\nMethod Two')
count.method_two()
|
import cv2
class Open_CV:
'''Capture image from your camera'''
def __init__(self, image_name):
self.image_name = image_name
self.download_link = 'pip install opencv-python'
def capture(self):
'''Capturing Image'''
try:
cam = cv2.VideoCapture(0) # Setting default camera
for _ in range(30): # This loop prevents black image
cam.read()
ret, frame = cam.read() # Reading each frame
cv2.imwrite(self.image_name, frame) # Saving captured frame
cam.release()
cv2.destroyAllWindows()
except cv2.error:
print('Camera is not connected')
if __name__ == '__main__':
open_cv = Open_CV('Image.jpg') # Don't forget to include '.jpg' or '.png' extension
open_cv.capture()
|
import requests
def is_internet():
'''Check if you are connected to internet'''
try:
requests.get("http://www.google.com")
return True
except requests.ConnectionError:
return False
if is_internet():
print('Internet Access')
else:
print('No Internet')
|
from tkinter import *
from tkinter.font import Font
class ShortCut:
def __init__(self, master):
self.master = master
self.font = Font(size=8)
def show_shortcut(self, button, text, rely=None):
'''Show text aside of the button when the cursor enters to the button'''
self.label = Label(self.master, text=text, border='1', relief='solid', font=self.font)
if rely:
self.id = self.master.after(800, lambda: self.label.place(in_=button, relx=0.7, x=0, rely=0))
else:
self.id = self.master.after(800, lambda: self.label.place(in_=button, relx=0, x=0, rely=1.0))
def destroy(self):
'''Remove text when the cursor leaves the button'''
self.master.after_cancel(self.id)
self.label.place_forget()
|
import random
class setup:
'''This class is responsible for:
1. Showing board each time when user as well as bot enters their turn
2. Asking user if he / she wants to go first'''
def __init__(self):
self.board = [str(i) for i in range(1, 10)]
def display_board(self, board):
'''Show board with human and bot enters their turn'''
for i in range(3):
display = ' | '.join(board[i * 3:i * 3 + 3])
if i in range(2):
sep = f"\n{'- ' * 5}\n"
else:
sep = '\n'
print(display, end=sep)
def get_turn(self):
'''Asking user if he/she wants to go first.
If user wants to go first then:
Human: X
Bot: O
else:
Human: O
Bot: X'''
option = True if input('Do you want to go first (y/n)? ').lower() == 'y' else False
if option:
return ('X', 'O')
return ('O', 'X')
class playing(setup):
'''This class is reponsible for:
1. Getting empty places
2. Asking user where he/she want to place their turn
> Checks if user inputs their turn in empty places. If not then shows warning.
3. Placing bot turn as per the user's turn
> Get empty places
> Checks if bot itself can win. If yes bot places its turn to that place and wins the game.
> If bot cannot win the game then it checks whether user can win the game. If yes, then bot blocks the user next move so user cannot win the game
4. Check where user or bot won or the game became TIE'''
def __init__(self):
super().__init__()
self.human, self.bot = setup().get_turn()
self.winner_combo = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 4, 8), (2, 4, 6), (0, 3, 6), (1, 4, 7), (2, 5, 8)]
def get_possible_moves(self):
return [self.board.index(place) for place in self.board if place in [str(i) for i in range(1, 10)]]
def human_move(self):
try:
place = int(input('\nWhere do you want to place?')) - 1
if place in self.get_possible_moves() and place > -1:
self.board[place] = self.human
else:
print('Invalid Move')
print(self.display_board(self.board))
self.human_move()
except:
print('Invalid Move')
print(self.display_board(self.board))
self.human_move()
def is_winner(self, board):
if not self.get_possible_moves():
return 'Tie'
for winner in self.winner_combo:
if board[winner[0]] == board[winner[1]] == board[winner[2]] == board[winner[0]]:
return board[winner[0]]
def bot_move(self):
possible_moves = self.get_possible_moves()
if possible_moves:
for move in possible_moves: # Checking if bot can win
self.board[move] = self.bot
if self.is_winner(self.board):
self.board[move] = self.bot
return
self.board[move] = str(move + 1)
for move in possible_moves: # Checking if player can win
self.board[move] = self.human
if self.is_winner(self.board):
self.board[move] = self.bot
return
self.board[move] = str(move + 1)
self.board[random.choice(possible_moves)] = self.bot
def main(self):
print(f'\nYou: {self.human}\nBot: {self.bot}\n')
if self.bot == 'X':
self.bot_move()
self.display_board(self.board)
while not self.is_winner(self.board):
self.human_move()
self.bot_move()
self.display_board(self.board)
if self.is_winner(self.board) == self.human:
print('\nHuman Won')
elif self.is_winner(self.board) == self.bot:
print('\nBot Won')
else:
print('\nHuman and Bot got tied')
playing().main()
|
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import math
def primes(n):
sums, sieve = [], [True] * n
for p in range(2, n):
if sieve[p]:
sums.append(p)
for i in range(p * p, n, p):
sieve[i] = False
return sums
if __name__ == '__main__':
nth_prime = 10001
upper_bound = int(nth_prime * math.log(nth_prime) + nth_prime * math.log(math.log(nth_prime)))
_primes = primes(upper_bound)
print(_primes[10000])
|
from datetime import *
import sqlite3
# This is our connection to the database
conn = sqlite3.connect('activities.db')
# This is the cursor. Using it we can add, delete or update information in the database
c = conn.cursor()
def create_table():
"""
This function creates a table with some columns that will be used later
"""
c.execute('CREATE TABLE IF NOT EXISTS activities(name TEXT, sort TEXT, category TEXT, estimated_time_hours REAL, '
'estimated_time_min REAL, '
'ratio REAL, date_now TEXT, date TEXT, frm TEXT, till TEXT, priority REAL, status TEXT, score TEXT, '
'frequency TEXT, Sunday TEXT, Monday TEXT, Tuesday TEXT, Wednesday TEXT, Thursday TEXT, Friday TEXT, '
'Saturday TEXT)')
data = strainer("", 'sort', 'category')
if data == []:
insert_category('None', 3)
def insert_todo(name, category, estimated_time_hours, estimated_time_min, day_when, priority, frequency):
# date: Time when the user has made this activity. It'll work later as an id for the activity
now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# score: Score of the activity. If the score is smaller, the activity is more important
# c.execute("SELECT priority FROM activities WHERE name=(?)"), [category]
category_int = strainer('priority', 'name', category)
score = int(len(frequency) + priority + category_int[0][0])
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, category, estimated_time_hours, estimated_time_min, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'todo', category, int(estimated_time_hours), int(estimated_time_min), now, day_when, priority,
score, 'undone'))
# Now we must commit the changes that happened in the database
conn.commit()
# The next bit of code will work at the frequency
# This is a list of all days in the week written in capital just like the one's in the database
list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# This for loop either puts in the column of the day a 1 if the activity will be done on that day. If not,
# the loop will ignore it
for i in list_of_days:
if i in frequency:
c.execute("UPDATE activities SET {} = 1 WHERE date_now=(?)".format(i), [now])
c.execute("UPDATE activities SET frequency='correct' WHERE date_now=(?)", [now])
# Now we must commit the changes that happened in the database
conn.commit()
def insert_event(name, category, frm, to, day_when, priority, frequency):
# root=Tk()
# frame=Frame(root)
# Label(frame,text="INSERTED").pack(side=LEFT)
# date: Time when the user has made this activity. It'll work later as an id for the activity
now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# score: Score of the activity. If the score is smaller, the activity is more important
# c.execute("SELECT priority FROM activities WHERE name=(?)"), [category]
category_int = strainer('priority', 'name', category)
score = len(frequency) + priority + category_int[0][0]
print("INSERT INTO activities (name, sort, category, frm, till, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'event', category, frm, to, now, day_when, priority,score, 'undone'))
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, category, frm, till, date_now, date, "
"priority, score, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(name, 'event', category, frm, to, now, day_when, priority,score, 'undone'))
# Now we must commit the changes that happened in the database
conn.commit()
# The next bit of code will work at the frequency
# This is a list of all days in the week written in capital just like the one's in the database
list_of_days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# This for loop either puts in the column of the day a 1 if the activity will be done on that day. If not,
# the loop will ignore it
for i in list_of_days:
if i in frequency:
c.execute("UPDATE activities SET {} = 1 WHERE date_now=(?)".format(i), [now])
c.execute("UPDATE activities SET frequency='correct' WHERE date_now=(?)", [now])
# Now we must commit the changes that happened in the database
conn.commit()
def insert_category(name, priority):
# The next code will be adding the information to the database
# First we tell the database in which table to put the info(here activities)
# After that we tell him which variables we will be writing
# Lastly we give him the variable
c.execute("INSERT INTO activities (name, sort, ratio, priority) VALUES (?, ?, ?, ?)",
(name, 'category', 1, priority))
# Now we must commit the changes that happened in the database
conn.commit()
def edit_anything(name, what, to):
"""
Using this function, the user can edit anything he wants in the activity
:param name: name of the activity
:param what: what the user wants to change in the activity
:param to: what that column should be
"""
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write UPDATE.
# WHERE determines which activity the user wants to change
c.execute("UPDATE activities SET {} = (?) WHERE name=(?)".format(what), [to, name])
# Now we must commit the changes that happend in the database
conn.commit()
def done(name):
"""
This function marks an activity as done
:param name: name of the activity
"""
# This here works just like the updating function
c.execute("UPDATE activities SET status = 'done' WHERE name=(?)", [name])
conn.commit()
def delete(name):
"""
This function deletes an activity from the database
:param name: name of the activity
"""
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("DELETE FROM activities WHERE name = (?)", [name])
# Now we must commit the changes that happened in the database
conn.commit()
def del_done():
"""
This function deletes all of the done activities which don't repeat every now and then
"""
# This function works just like the deleting function
c.execute("DELETE FROM activities WHERE status = 'done' AND Frequency != 'correct'")
conn.commit()
def strainer(select, strain, equals):
"""
This function works as a strainer. Using it you can get something specific from the database
:param select: Do you want to get all of the columns or only specific ones?
:param strain: What should all things you want to see have in common?
:param equals: What should it be equal to?
:return a list of what the user wants to see
"""
# This selects everything if the user didn't enter something for select
if select == "":
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("SELECT * FROM activities WHERE {}=(?)".format(strain), [equals])
return c.fetchall()
else:
# Just like adding something, we use the cursor, but instead of INSERT INTO, we write DELETE FROM.
# WHERE determines which activity the user wants to change
c.execute("SELECT {} FROM activities WHERE {}=(?)".format(select.upper(), strain), [equals])
return c.fetchall()
def organize(select, strain, equals):
"""
This function returns a list of numbers. These numbers are the numbers of scores in a specific order. The first
element is the most important one
:parameters all of these parameters are used to get the scores of specific activities in the table!
"""
scores = []
data = list(strainer(select, strain, equals))
while len(data) != 0:
number = lowest_number(data)
scores.append(number)
data.remove(number)
return scores
def lowest_number(list_int):
"""
This function uses recursion to find the lowest number of a list
:param list_int: list of int
:return: smallest number
"""
if len(list_int) == 1:
return list_int[0]
number = lowest_number(list_int[1:])
if list_int[0] < number:
return list_int[0]
else:
return number
def no_category():
if len(strainer('', 'sort', 'category')) == 0:
return False
else:
return True
def organizeM():
"""
This function returns a list of numbers. These numbers are the numbers of scores in a specific order. The first
element is the most important one
:parameters all of these parameters are used to get the scores of specific activities in the table!
"""
scores = []
today_listM = strainer('name', 'sort', 'event')
today_listM.extend(strainer('name', 'sort', 'todo'))
data = list(today_listM)
while len(data) != 0:
number = lowest_number(data)
scores.append(number)
data.remove(number)
return scores |
import pyperclip
plaintext = 'MKOCKBMSZROB.'
key = 10
mode = 'decrypt'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
plaintext = plaintext.upper()
for symbol in plaintext:
if symbol in letters:
num = letters.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
num = num - key
if num >= len(letters):
num = num - len(letters)
elif num < 0:
num = num + len(letters)
translated = translated + letters[num]
else:
translated = translated + symbol
print(translated)
pyperclip.copy(translated)
#python3 decrypt.py
|
"""Main cryptographic functions of the platform.
These are the fucntion that encrypt and decrypt all the content from the
backend side of the platform.
"""
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
"""Declare main variables like byte size (BS) and key."""
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
"""Encrypt content using AES."""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
"""Decrypt content."""
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
"""Pad the text if it doesn't match the byte size."""
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
"""Unpad the content for decryption."""
return s[:-ord(s[len(s) - 1:])]
|
from HW1.data_gen import DataSet
import numpy as np
import HW1.percept_learning as pla
def generate_target(data_set):
"""A method used to set the target vector for the linear regression.
Target vector i is set to -1 if point i dot f is negative (or zero) otherwise set to +1.
Params: DataSet
Return: Target vector as an numpy array (length == number points in DataSet)
"""
target_vector = np.empty(data_set.size, dtype=float)
for index, bool in enumerate(data_set.bools):
if bool:
target_vector[index] = 1
else:
target_vector[index] = -1
return target_vector
def linear_regression(data_set):
"""
A method to computed the least squares linear regression for classification.
Params: DataSet object
Return: g calculated using linear regression.
"""
target = generate_target(data_set)
if data_set.linear:
pseudo_inverse = np.linalg.pinv(data_set.points)
w = np.dot(pseudo_inverse, target)
else:
pseudo_inverse = np.linalg.pinv(data_set.transform)
w = np.dot(pseudo_inverse, target)
return w
def error_in(data_set, g):
"""Method to determine the in sample error of the linear regression classification method.
Params: DataSet object, and the vector for output from linear_regression method
Return: The in sample error probability
"""
error = 0.0
for index, point in enumerate(data_set.points):
if data_set.linear:
if not data_set.compare(point, g):
error += 1
else:
if not data_set.check(index, g):
error += 1
return error / data_set.size
def error_out(data_set, g):
"""Calculated out of sample error of linear regression classification algorithm stocastically.
Tests 1000 randomly generated points and compares the classification of the LR classification alg and target.
Params: DataSet object. Hypothesis vector.
Return: Stocastically determined out of sample error for LR classification algorithm.
"""
error = 0.0
points = np.random.uniform(-1, 1, (1000, 3))
if data_set.linear:
for point in points:
point[2] = 1
if not data_set.compare(point, g):
error += 1
else:
transform = np.empty((1000, 6))
data_set.do_transform(transform, points)
for vector in transform:
dot = np.dot(vector, g)
if ((dot > 0 and data_set.nonlinear_classify(vector) == False)
or (dot <= 0 and data_set.nonlinear_classify(vector) == True)):
error += 1
return error / 1000
def average_error(number, type="in", linear=True, threshold=0.0, noise=0.0):
"""Method to calculate the in sample or out of sample error average over 1000 runs
Params: Number of points in data set to be generated, type (valid types are "in" and "out"
Return: the average error over 1000 runs as a float
"""
error = 0.0
data_set = DataSet(number, linear=linear, threshold=threshold, noise=noise)
for i in range(1000):
data_set.new_set()
if type == "in":
temp = error_in(data_set, linear_regression(data_set))
error = (error * i + temp) / (i + 1)
elif type == "out":
temp = error_out(data_set, linear_regression(data_set))
error = (error * i + temp) / (i + 1)
else:
raise ValueError("type must be the string 'in' or 'out'.")
return error
def convergence_time(number):
"""Use LR as output for start vector of PLA algorithm. Outputs average time (1000 trials) of pla before convergence
Params: Number of points in data set
Return: Average time of convergence for modified PLA
"""
t_average = 0.0
data_set = DataSet(number)
for i in range(1000):
data_set.new_set()
w = linear_regression(data_set)
temp = pla.pla(w, data_set)
t_average = (t_average * i + temp) / (i + 1)
return t_average
# print(average_error(1000, type="out", linear=False, threshold=0.6, noise = 0.1)) |
class base():
def func(self,X1):
X = X1
print(X)
def __str__(self):
txt = "This is your object"
return txt
class child(base):
#def func(self,Z):
# print("in child class")
def func1(self):
print("inside child")
#super().func(20)
self.func(50) # via inheritance
#Bx = base()
#Bx.func(10)
Cx = child()
Cx.func1()
Bx = base()
print(Bx) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def display(Xrow, ImageName):
'''Display a digit by first reshaping it from the row-vector into the image. '''
plt.imshow(np.reshape(Xrow, (28, 28)))
plt.gray()
plt.savefig(str(ImageName) + ".png")
plt.show()
def loadData(digit, num):
'''
Loads all of the images into a data-array (for digits 0 through 5).
The training data has 5000 images per digit and the testing data has 200,
but loading that many images from the disk may take a while. So, you can
just use a subset of them, say 200 for training (otherwise it will take a
long time to complete.
Note that each image as a 28x28 grayscale image, loaded as an array and
then reshaped into a single row-vector.
Use the function display(row-vector) to visualize an image.
'''
X = np.zeros((num, 784), dtype=np.uint8) # 784=28*28
for i in range(num):
pth = 'D://bigdata2/train%d/%05d.pgm' % (digit,i)
with open(pth, 'rb') as infile:
#header = infile.readline()
#header2 = infile.readline()
#header3 = infile.readline()
image = np.fromfile(infile, dtype=np.uint8).reshape(1, 784)
X[i, :] = image
print('\n')
return X
def loadAllData(num):
X = np.zeros((num, 784), dtype=np.uint8) # 784=28*28
for k in range(3):
for i in range(int(num / 3)):
pth = '/Users/meredith/assignment/train%d/%05d.pgm' % (k, i)
with open(pth, 'rb') as infile:
image = np.fromfile(infile, dtype=np.uint8).reshape(1, 784)
X[i * (k + 1), :] = image
print('\n')
return X
# for question2
num = 5000
matrix = loadData(0, num)
'''
# for question3
matrix = loadData(2, num)
# for question4
num = 15000
matrix = loadAllData(num)
'''
features = 20
mean = matrix.mean(axis=0)
matrix = matrix - mean
display(mean, 'meanImage')
cov = np.dot(matrix, matrix.T) / num
evs, vec = np.linalg.eigh(cov)
index = np.argsort(evs)
index = index[::-1]
# show eigenvalues
x = range(1, 101)
y = [0] * 100
for i in range(100):
y[i] = evs[index[i]]
plt.plot(x, y, 'bo')
plt.show()
# show the first 20 eigenvectors(as image)
eigen = [0] * features
for i in range(features):
eigen[i] = vec[index[i]].tolist()
data = np.dot(np.transpose(matrix), np.transpose(eigen))
for j in range(features):
display(np.transpose(data)[j], j + 1) |
from database import fetch_entries, add_entry, create_table
menu = """Please select one of the following options:
1. Add new entry for today
2. View entries
3. Exit
Your Input: """
Welcome = """Welcome to the programming diary"""
def prompt_new_entry():
date = input("Enter a date:")
content = input("Enter the content:")
add_entry(date, content)
def view_entries(entries):
for entry in entries:
print(f"Date : {entry[1]}\nContent : {entry[0]}\n\n")
print(Welcome)
create_table()
while (user_input := input(menu)) != "3":
if user_input == "1":
prompt_new_entry()
print("***Entry added***")
elif user_input == "2":
entries = fetch_entries()
view_entries(entries)
else:
print("Invalid input, Please try again!")
|
class Node:
def __init__(self, data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def getMiddleNode(self):
slowptr = self.head
fastptr = self.head
if self.head != None:
while fastptr != None and fastptr.next != None:
fastptr = fastptr.next
fastptr = fastptr.next
slowptr = slowptr.next
print("the middle element is", slowptr.data)
llist = LinkedList()
llist.push(1)
llist.push(2)
llist.push(3)
llist.push(4)
llist.push(5)
llist.push(6)
llist.push(7)
llist.getMiddleNode()
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if not root.left and not root.right and root.val == sum:
return True
sum = sum - root.val
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
if __name__ == '__main__':
root = TreeNode(5, left=TreeNode(4, left=TreeNode(11)), right=TreeNode(8, left=TreeNode(13), right=TreeNode(4)))
s = Solution()
print(s.hasPathSum(root, 20))
|
import random
import simplegui
n=0
g=0
def f_r1():
global g,n
n=random.randint(0,100)
g=7
print "new game initialized: range from 0 to 100"
print "number of guesses are :"+str(g)
def check(t):
global g,n
g=g-1
if ((g+1)>0):
print "guess : "+t
print "number of remaining guesses :"+str(g)
if ((int(t)<n) and (g+1)>0):
print "higher"
elif ((int(t)>n) and (g+1)>0):
print "lower"
elif (int(t)==n):
print "correct"
print "\n"
f_r1()
if ((g+1)<=0):
print "no more guesses left, YOU LOOSE!!"
print "\n"
f_r1()
frame1=simplegui.create_frame("guess the number",200,200)
frame1.add_button("create game",f_r1)
frame1.add_input("enter your guess",check,100)
frame1.start() |
# x = 20
# y = 30
# +,-,*,/,%, **,//
# print(x + y)
# print(2**4)
# print(19//5)
# x = 10
# =,+=,-=,*=
# x = 10
#
# x += 20
#
# print(x)
# and,or,not
#
# userName = 'admin'
# password = 'admin002'
#
# if userName=='admin' and password=='admin002':
# print('Welcome')
# else:
# print('')
# ==,>,<,>=,<=
#
# print(3 > 5)
#
# print(3 < 5)
# Identity: is, is not
# Membership: in, not in
#
# x = 10
# y = 20
# z = x
#
# print(x is y)
# print(x is z)
# print(x is not y)
#
# name = "sophia"
#
# print('s' in name)
# print('z' in name)
# print('y' not in name)
# print(5 & 7)
|
# Polynomial regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
dataset = pd.read_csv('data.csv')
X = dataset.iloc[:, 1:2].values # matrix
y = dataset.iloc[:, 2].values # vector
#polynomial linear regression
poly_reg = PolynomialFeatures(degree=5)
X_poly = poly_reg.fit_transform(X)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)
#visualize polynomial regression
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color='red')
plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color='blue')
plt.title('Polynomial Regression')
plt.xlabel('Independent')
plt.ylabel('Dependent')
plt.show()
|
import math
def hypotenuse(a , b ):
#c = (a**2 + b**2)**(1/2)
try:
return math.sqrt(a**2 + b**2)
except TypeError:
return None
d = hypotenuse
print(d(2,3)) #print 2 numbers
print(d("2","3"))
print(d(2,"3"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.