text stringlengths 37 1.41M |
|---|
import time
print(ch06.module.time()) # 1970년 1월 1일 자정 이후를 초로 환산
print(time.localtime())
print(time.ctime()) # 날짜와 시간 요일 표시
print(time.strftime('%x', time.localtime()))
print(time.strftime('%c', time.localtime()))
# time.sleep(1) : 1초간 대기 :
# 파이썬에서는 1초를 1로 표기
for i in range(1, 11):
print(i)
time.sleep(1)
|
# test03
# 1번
a = "Life is too short, you need python"
if "wife" in a: print("wife")
elif "python" in a and "you" not in a: print("python")
elif "shirt" not in a: print("shirt")
elif "need" in a: print("need")
else: print("none")
# 2번
result = 0
i = 1
while i <= 1000:
if i % 3 == 0:
result += i
i += 1
print(result)
# 3번
i = 0
while True:
i += 1
if i > 5 : break
print(i*'*')
# 이중 for문
i = 0
for i in range(1, 6):
for j in range(1, i+1):
print('*', end='')
print()
# 4번
for i in range(1, 101):
print(i)
# 5번
A = [70, 60, 55, 75, 95, 90 ,80, 80, 85, 100]
total = 0
for score in A:
total += score
average = total / len(A)
print(average)
# 6번
numbers = [1, 2, 3, 4, 5]
result = []
for n in numbers:
if n % 2 == 1:
result.append(n*2)
numbers = [1, 2, 3, 4, 5]
result = [n*2 for n in numbers if n % 2 == 1]
print(result)
|
# 윈도우(폼) 만들기
from tkinter import *
root = Tk() # Tk()클래스의 객체 생성
root.title("window")
root.geometry("200x100+300+400") # width x height + x좌표 + y좌표
frame = Frame(root) # root 위에 위치하는 프레임 객체
frame.pack() # 레이아웃 담당하는 메서드
# 문자열 출력 - Label 클래스
Label(frame, text = "Hello Python").grid(row=0, column=0)
# 버튼 클래스
Button(frame, text = "확인").grid(row=1, column=0)
root.mainloop()
|
# 학생 클래스 생성과 사용
class Student:
def __init__(self, sid, name):
self.__sid = sid #학번
self.__name = name
def getsid(self):
return self.__sid
def getname(self):
return self.__name
s1 = Student(1001, '김산')
print(s1.getsid(), s1.getname())
s2 = Student(1002, '이강')
print(s2.getsid(), s2.getname())
|
import random
# 주사위 10번 던지기
'''
for i in range(10):
dice = random.randint(1, 6)
print(dice)
print('='*40)
'''
# 리스트에서 랜덤하게 단어 추출하기
word = ['sky', 'moon', 'space', 'earth']
w = random.choice(word)
print(w)
|
# mydb에 member 테이블 생성
# db프로세스
# 1. db에 연결
# 2. 테이블 생성
from libs.db.dbconn import getconn
def create_table():
conn = getconn() # dbconn 모듈에서 getconn 호출(객체 생성)
cur = conn.cursor() # db 작업을 하는 객체(cur)
# 테이블 생성 - sql 언어 DDL
sql = """
create table member(
mem_num int primary key,
name char(20),
age int
)
"""
cur.execute(sql)
conn.commit() # 커밋 - 트랜잭션 완료(수행)
conn.close() # 네트워크 종료
if __name__ == "__main__":
create_table() |
# -*- coding: utf-8 -*-
def combine(str1, str2):
ans = ""
#i = 0
str_len = max(len(str1), len(str2))
for i in range(0, str_len):
ans = ans + str1[i:i+1] + str2[i:i+1]
#ans = ans + str[str_len:]
return ans
print combine("cat","dog")
|
# Read in number of test cases.
t = int(input())
# For each test case.
for _ in range(t):
# Read the number of zucchinis.
n = int(input())
# Grab the heights of each zucchini in a list.
heights = list(map(int, input().split(" ")))
# Build our other list and initialize to False. We use two extra indices
# to avoid having to do bounds checking.
expect_next = [False] * (n + 2)
# We keep track of the number of sequences we have found in `count`.
count = 0
# For each zucchini, if we have not seen the previous zucchini
# (with height - 1) we increase our count by 1. We then set the value for
# our next zucchini (with height + 1) to True, indicating we expect to see
# it further along in the sequence.
for h in heights:
if not expect_next[h]:
count += 1
expect_next[h + 1] = True
# We take the ceiling of the log_2 of count...
log = 0
while 1 << log < count:
log += 1
# And print out our answer.
print(log)
|
def chess(n : int) -> int:
if n == 0:
return 1
return chess(n-1)*2
print(chess(4))
def sum_total(n : int) -> int:
if n == 0:
return 1
return sum_total(n - 1) + chess(n)
print(sum_total(4))
|
# -*- coding: utf-8 -*-
# @Time : 2018/9/5 08:37
# @Author : yunfan
class MyStack:
"""
ONLY CAN USE APPEND AND POP(0), Time COMPE IS TOO HIGHT
"""
def __init__(self):
"""
Initialize your data structure here.
"""
self._a = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self._a.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
t = self._a[-1]
self._a.pop()
return t
def top(self):
"""
Get the top element.
:rtype: int
"""
return self._a[-1]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self._a) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty() |
class Solution:
def addOperators(self, num, target):
def dfs(ops):
res = []
for op in ops:
res.append(op + ['-'])
res.append(op + ['+'])
res.append(op + ['*'])
res.append(op + [''])
return res
def check(ops, num):
s = ''
for i in range(0, len(num) - 1):
if num[i] == '0' and ops[i] == '':
return None, None
s += num[i]
s += ops[i]
s += num[-1]
return eval(s), s
ops = [['-'], ['+'], ['*'], ['']]
for i in range(1, len(num) - 1, 1):
ops = dfs(ops)
ans = []
for op in ops:
r, s = check(op, num)
if r == target:
ans.append(s)
return ans
if __name__ == '__main__':
print(Solution().addOperators("123456789", 45)) |
# -*- coding: utf-8 -*-
# @Time : 2018/8/31 14:04
# @Author : yunfan
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = -1
for i in range(len(nums)):
if nums[i] == 0:
l = i
break
if l == -1:
return
for i in range(l + 1, len(nums)):
if nums[i] != 0:
nums[l] = nums[i]
nums[i] = 0
l += 1
for i in range(l, len(nums)):
nums[i] = 0
|
# -*- coding: utf-8 -*-
# @Time : 2018/9/5 08:48
# @Author : yunfan
'''
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
'''
INF = 123456789
tx = [0, 1, 0, -1]
ty = [1, 0, -1, 0]
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if (matrix is None) or (len(matrix) == 0) or (len(matrix[0]) == 0):
return None
N, M = len(matrix), len(matrix[0])
res = [[INF for i in range(M)] for j in range(N)]
queue = []
for i in range(N):
for j in range(M):
if matrix[i][j] == 1:
flag = False
for k in range(4):
x, y = i + tx[k], j + ty[k]
if x >= 0 and x < N and y >= 0 and y < M and matrix[x][y] == 0:
flag = True
break
if flag:
res[i][j] = 1
queue.append((i, j))
else:
res[i][j] = 0
while queue:
size = len(queue)
x, y = queue.pop()
for i in range(4):
dx, dy = x + tx[i], y + ty[i]
if dx >= 0 and dx < N and dy >= 0 and dy < M and res[dx][dy] == INF:
res[dx][dy] = res[x][y] + 1
queue.append((dx, dy))
return res
|
# -*- coding: utf-8 -*-
# @Time : 2018/8/29 10:50
# @Author : yunfan
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def _length_node(self, head):
res = 0
while head is not None:
head = head.next
res += 1
return res
def _forward_steps(self, node, step):
if step < 0:
return None
for i in range(step):
node = node.next
return node
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA is None or headB is None:
return None
lenA, lenB = self._length_node(headA), self._length_node(headB)
if lenA > lenB:
headA = self._forward_steps(headA, lenA - lenB)
else:
headB = self._forward_steps(headB, lenB - lenA)
while True:
if (headA is None) or (headB is None):
return None
if headA is headB:
return headA
headA = headA.next
headB = headB.next
if __name__ == '__main__':
A = ListNode(1)
B = ListNode(2)
# C = ListNode(3)
# D = ListNode(4)
# E = ListNode(5)
#
# A.next = B
# B.next = D
# C.next = D
# D.next = E
#
# print(Solution().getIntersectionNode(A, B).val)
print(Solution().getIntersectionNode(A, B))
|
# -*- coding: utf-8 -*-
# @Time : 2018/8/29 16:50
# @Author :
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def _lenght_make_circle(self, head):
node = head
res = 1
while node.next is not None:
node = node.next
res += 1
node.next = head
return res
def _forward(self, node, steps):
for i in range(1, steps):
node = node.next
return node
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None:
return
list_len = self._lenght_make_circle(head)
k = k % list_len
node = self._forward(head, list_len - k)
res = node.next
node.next = None
return res
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/28 18:13
# @Author : yunfan
"""
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
"""
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
a = list(s)
s = a[:]
a.reverse()
for i in range(len(a)):
if a[i] == s[i]:
continue
else:
a1 = a[:i] + a[i + 1:]
s1 = s[:len(a) - i - 1] + s[len(a) - i:]
s2 = s[:i] + s[i + 1:]
a2 = a[:len(a) - i - 1] + a[len(a) - i:]
if a1 == s1 or a2 == s2:
return True
else:
return False
return True
if __name__ == '__main__':
print(Solution().validPalindrome("ebcbbececabbacecbbcbe"))
|
# -*- coding: utf-8 -*-
# @Time : 2018/9/2 14:25
# @Author : yunfan
'''
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image
(from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value
newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel
of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same
color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
'''
tx = [0, 0, 1, -1]
ty = [1, -1, 0, 0]
class Solution:
def _dfs(self, image, tag, x, y, newColor):
if image[x][y] == newColor:
return
image[x][y] = newColor
for i in range(4):
dx = x + tx[i]
dy = y + ty[i]
if dx >= 0 and dx < len(image) and dy >= 0 and dy < len(image[0]) and image[dx][dy] == tag:
self._dfs(image, tag, dx, dy, newColor)
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
if len(image) == 0 or len(image) == 0:
return None
self._dfs(image, image[sr][sc], sr, sc, newColor)
return image
# if __name__ == '__main__':
# a = [[1, 1, 1], [1, 1, 0], [1, 0, 1]]
# print(Solution().floodFill(a, 1, 1, 2))
|
'''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
foo = '1' + '$'
for i in range(1,n):
bar = ''
cnt = 1
for j in range(len(foo) - 1):
if foo[j] == foo[j + 1]:
cnt += 1
else:
bar += str(cnt) + foo[j]
cnt = 1
foo = bar + '$'
return foo[0:-1]
ss = Solution()
print(ss.countAndSay(1))
print(ss.countAndSay(2))
print(ss.countAndSay(3))
print(ss.countAndSay(4))
print(ss.countAndSay(5))
print(ss.countAndSay(6))
|
while True:
try:
w = int(input())
if w % 2 == 0:
if w > 2:
print("YES")
continue
print("NO")
except EOFError:
exit() |
def sum():
sum = 0
for n in range(1,101):
sum = sum + n
return sum
print(sum()
|
# Damien Connolly G00340321
# Project for Applied Databases
# Lecturer: Gerard Harrison
# Code for this project adapted from lectures and examples @ https://learnonline.gmit.ie/course/view.php?id=2564
# Import MySQL and Mongo to connect to database and call functions
import mysql
import mongo
# Main function
def main():
# Call the display menu function
display_menu()
while True:
# Ask user to select option choice
choice = input("Choice: ")
# 1 - View Films
if (choice == "1"):
# Call function from mysql
films = mysql.view_films()
# Return to display menu
display_menu()
# 2 - View Actors by Birth and Gender
elif (choice == "2"):
print("View by Age and Gender")
print("--------------------------")
# Ask user to input year
year = (input("Enter Year: "))
# Check if input is a number, if not ask user for input until number is entered
# Adapted from https://www.w3schools.com/python/ref_string_isdigit.asp
while not year.strip().isdigit():
year = input("Enter Year: ")
# Ask user to input gender
ActorGender = input("Enter Gender: ")
# Check if the input is male, female or blank
# Adapted from https://www.askpython.com/python/examples/in-and-not-in-operators-in-python
while ActorGender not in ("male", "female", ""):
# If input is not correct ask again
ActorGender = input("Please Enter (male/female): ")
# If input is correct break the loop and continue
while ActorGender in ("male", "female", ""):
break
# Call the function from mysql
results = mysql.viewByAgeAndGender(year, ActorGender)
# Return to display menu
display_menu()
# 3 - View Studios
elif (choice == "3"):
# Call function from mysql
mysql.view_studios()
# Return to display menu
display_menu()
# 4 - Add New Country
elif (choice == "4"):
print("\nAdd New Country")
print("--------------------------")
# Ask user for country id
CountryID = input("Enter CountryID: ")
# Check if input is a number, if not ask user for input until number is entered
# Adapted from https://www.w3schools.com/python/ref_string_isdigit.asp
while not CountryID.strip().isdigit():
CountryID = input("Enter CountryID: ")
# Ask user to enter country name
CountryName = input("Enter CountryName: ")
# If country name is not entered ask again until one is entered
while CountryName == "":
CountryName = input("Enter CountryName: ")
# Call function from mysql
mysql.add_country(CountryID, CountryName)
# Return to display menu
display_menu()
# 5 - View Movies With Subtitles
elif (choice == "5"):
print("\nView Movies With Subtitles")
print("--------------------------")
# Ask user to enter subtitles being searched for
subtitles = input("Choose Subtitles: ")
# If no subtitles are entered return to display menu
if (subtitles == ""):
display_menu()
continue
# Call the function from Mongo and store results as results
results = mongo.viewMoviesWithSubtitles(subtitles)
# Create an empty array to append results in
array = []
# Loop through results
for result in results:
# Append each result in the array as _id
array.append(result["_id"])
# Convert the array to a tuple(as search) to pass back to mysql
# Adapted from https://www.geeksforgeeks.org/python-convert-a-list-into-a-tuple/
search = tuple(array)
# Print heading for searched subtitles
print("\nMovies With", subtitles, "Subtitles")
print("--------------------------")
# Call function from mysql
mysql.filmByID(search)
# Return to display menu
display_menu()
# 6 - Add New MovieScript
elif (choice == "6"):
print("\nAdd New MovieScript")
print("--------------------------")
# Ask user to input ID
ID = (input("ID: "))
# Check if input is a number, if not ask user for input until number is entered
# Adapted from https://www.w3schools.com/python/ref_string_isdigit.asp
while not ID.strip().isdigit():
ID = (input("ID: "))
# Create empty array to store each word
array = []
while True:
# Ask user to input keywords
words = input('Keywords(-1 to end): ')
# If user enters -1 then quit
if words == "-1":
break
# Append words to array
array.append(words)
# Store array as keywords
keywords = array
# Create empty array to store each subtitle
array = []
while True:
# Ask user to input subtitle
subtitle = input('Subtitles(-1 to end): ')
# If user enter -1 then quit
if subtitle == "-1":
break
# Append subititles to array
array.append(subtitle)
# Store array as subtitles
subtitles = array
# Insert new movie into Mongo database
mongo.addNewMovieScript(ID, keywords, subtitles)
# Return to display menu
display_menu()
# Exit program if user enters x
elif (choice == "x"):
break
# Function for display menu
def display_menu():
print(f"\n-------------------------------------------")
print(f"----------------MAIN MENU--------------")
print(f"-------------------------------------------")
print(f"\n")
print(f" PLEASE SELECT AN OPTION ")
print(f"-------------------------------------------")
print(f"\n")
print(f"\n1 - View Films\n")
print(f"\n2 - View Actors by Birth and Gender\n")
print(f"\n3 - View Studios\n")
print(f"\n4 - Add New Country\n")
print(f"\n5 - View Movie with Subtitles\n")
print(f"\n6 - Add New MovieScript\n")
print(f"\nX - Exit Application\n")
print(f"\n")
main() |
# solve linear equation using Python
x= 10-500+79
print(x)
# for a second degree equation, use quadratic formula ax squared + bx+c = 0
# quadratic formula
#x1 and then x2 = -b + square root of b squared minus ac, everything divided by 2a
a = 1
b = 2
c = 1
D = ( b**2 - 4*a*c)**0.5
# now evaluate x1 and x2
x_1= (-b+D)/(2*a)
print(x_1)
x_2= (-b-D)/(2*a)
print(x_2)
# you can substitute the answer in the equation and see if it evaluates to 0
#warmup done
############################################
'''
Quadratic equation root calculator
'''
def roots(a,b,c):
D= (b*b -4*a*c)**0.5
x_1=(-b+D)/(2*a)
x_2=(-b-D)/(2*a)
print('x1:{0}'.format(x_1))
print('x2:{0}'.format(x_2))
if __name__ == '__main__':
a = input("Enter a: ")
b = input("Enter b: ")
c= input("Enter c: ")
roots(float(a), float(b), float(c))
|
'''
dispersion - tells us how far away the numbers in a data set are from the
mean of the data set
'''
# three methods of dispersion: range, variance, standard deviation
'''
Finding the range of a set of numbers
The range shows the difference between the highest and the lowest number
'''
# find the range
def find_range(numbers):
lowest= min(numbers)
highest= max(numbers)
# find the range
r = highest-lowest
return lowest, highest, r
if __name__ == '__main__':
donations= [100,60,70,900,100,200,500,500,503,600,1000,1200]
lowest, highest, r= find_range(donations)
print('Lowest:{0} Highest:{1} Range: {2}'.format(lowest, highest, r))
|
class Person:
def __init__(self, name, age):
self.name=name
self.age=age
def details(self):
print(self.name, self.age)
person_list = []
for i in range(0,5):
person = Person("person"+ str(i), 30+i)
person_list += [person]
for i in person_list:
i.details()
|
class Math:
def __init__(self, x, y):
self.x = x
self.y =y
def sum(self):
return self.x + self.y
class Mathextend(Math):
def __init__(self, x, y):
super().__init__(x, y)
def subtract(self):
return self.x - self.y
math_obj = Mathextend(5,2)
print(math_obj.subtract())
|
#!/usr/bin/env python3
import random
from utils import write
from block_at_three import *
def offense_next_to(x, y, map, check) :
pos_x = x - 1
while pos_x < x + 2:
pos_y = y - 1
while pos_y < y + 2 :
if pos_x == x and pos_y == y or pos_x > 19 or pos_y > 19 or pos_x < 0 or pos_y < 0:
pass
elif map[pos_x][pos_y] == '1' :
if pos_x > x :
map, check = check_right(pos_x, pos_y, map, check, y)
elif pos_x < x :
map,check = check_left(pos_x, pos_y, map, check, y)
elif pos_x == x :
map, check = check_vertical(pos_x, pos_y, map, check, y)
pos_y += 1
pos_x += 1
return map, check
def check_offense(map) :
check = False
for x in range(20) :
for y in range(20) :
if map[x][y] == '1' :
map, check = offense_next_to(x, y, map, check)
if check != True :
map = random_ia(map)
return map
def random_ia(map) :
x = random.randint(0,19)
y = random.randint(0,19)
if map[x][y] == '0' :
map[x][y] = '1'
write("{},{}".format(x, y))
else :
random_ia(map)
return map |
from sys import argv
script, file_name = argv
text = open(file_name, encoding = 'utf-8')
print(f"file {file_name}'s contents :")
print(text.read())
text.close()
print("Type the file name once again.")
file_again = input("> ")
text_again = open(file_again)
print(text_again.read())
text_again.close()
|
from sys import argv
script, user_name = argv
prompt = 'Your anwser is... '
print(f"Hello {user_name}, I'm {script} script.")
print("I'd like to ask you a few questions.")
print(f"Do you like me, {user_name}?")
likes = input(prompt)
print(f"Where do you live, {user_name}?")
lives = input(prompt)
print("What kind of computer do you want buy?")
computer = input(prompt)
print(f"""
Well, so you said {likes} about liking me.
You live in {lives}. Not sure where it is.
And you want to buy {computer}.
But I guess, you don't have enough money, lol lol.
""")
|
#-*-coding:utf-8-*-2:wq
# Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
t = '$#' + '#'.join(s) + "#_";
p = [0] * 4210;
mxRight = 0;
id = 0;
# calculate p array
reInd = 0;
for i in range(len(t)):
p[i] = mxRight > i and min(p[2*id-i], mxRight-i) or 1;
while (i-p[i] >= 0 and i+p[i] < len(t) and t[i-p[i]] == t[i+p[i]]):
p[i] += 1;
if(i + p[i] > mxRight):
mxRight = i + p[i];
id = i;
if p[reInd] < p[i]:
reInd = i;
# print t[i-p[i]+1:i+p[i]];
return s[reInd//2 - p[reInd]//2: reInd//2 + (p[reInd]-1)//2]
# 采用二维数组保存回文串, 仍然超时
#class Solution(object):
# def longestPalindrome(self, s):
# """
# :type s: str
# :rtype: str
# """
# fitI = 0;
# fitSize = 1;
# size = 1;
# pal = [[ 0 for c in range(1000)] for r in range(1000)]
# for i in range(len(s)):
# pal[i][i] = 1;
# lastCnt = 1;
# cntSize = [0 for c in range(1005)]
# cntSize[0] = len(s);
# cntSize[1] = len(s);
# for size in range(2, len(s)):
# if cntSize[size-2] == 0:
# break;
# for i in range(0, len(s)-size):
# if(s[i] == s[i+size-1] and ( size == 2 or pal[i+1][i+size-2] == 1)):
# cntSize[size] += 1;
# pal[i][i+size-1]=1;
# fitI = i;
# fitSize = size;
## print size, ",", s[fitI:fitI+size];
# if cntSize[size] == 0 and cntSize[size-1] == 0:
# break;
#
#
# return s[fitI:fitI + fitSize];
# 采用字典保存回文字串,但是超时, 果然字典还是比较慢的
#class Solution(object):
# def longestPalindrome(self, s):
# """
# :type s: str
# :rtype: str
# """
# lenS = len(s);
# palDict = {};
# fitI = 0;
# size = 1;
# for i in range(len(s)):
# palDict[self.encode(i,i)]=1;
# if i > 0 and s[i] == s[i-1]:
# palDict[self.encode(i-1,i)]=1;
# size = 2;
# fitI = i-1;
# for size in range(3, len(s)):
# cnt = 0;
# for i in range(0, len(s)-size):
# if(s[i] == s[i+size-1] and palDict.has_key(self.encode(i+1, i+size-2))):
# cnt += 1;
# palDict[self.encode(i,i+size-1)]=1;
# fitI = i;
# if cnt == 1:
# return s[fitI:fitI+size-1];
# elif cnt == 0:
# break;
# return s[fitI:fitI+size-1];
#
# def encode(self, i, j):
# return i* 1000 + j;
#
s = Solution();
print s.longestPalindrome("abcasebcecdabcabascb");
print s.longestPalindrome("rgczcpratwyqxaszbuwwcadruayhasynuxnakpmsyhxzlnxmdtsqqlmwnbxvmgvllafrpmlfuqpbhjddmhmbcgmlyeypkfpreddyencsdmgxysctpubvgeedhurvizgqxclhpfrvxggrowaynrtuwvvvwnqlowdihtrdzjffrgoeqivnprdnpvfjuhycpfydjcpfcnkpyujljiesmuxhtizzvwhvpqylvcirwqsmpptyhcqybstsfgjadicwzycswwmpluvzqdvnhkcofptqrzgjqtbvbdxylrylinspncrkxclykccbwridpqckstxdjawvziucrswpsfmisqiozworibeycuarcidbljslwbalcemgymnsxfziattdylrulwrybzztoxhevsdnvvljfzzrgcmagshucoalfiuapgzpqgjjgqsmcvtdsvehewrvtkeqwgmatqdpwlayjcxcavjmgpdyklrjcqvxjqbjucfubgmgpkfdxznkhcejscymuildfnuxwmuklntnyycdcscioimenaeohgpbcpogyifcsatfxeslstkjclauqmywacizyapxlgtcchlxkvygzeucwalhvhbwkvbceqajstxzzppcxoanhyfkgwaelsfdeeviqogjpresnoacegfeejyychabkhszcokdxpaqrprwfdahjqkfptwpeykgumyemgkccynxuvbdpjlrbgqtcqulxodurugofuwzudnhgxdrbbxtrvdnlodyhsifvyspejenpdckevzqrexplpcqtwtxlimfrsjumiygqeemhihcxyngsemcolrnlyhqlbqbcestadoxtrdvcgucntjnfavylip");
#print s.longestPalindrome("iopsajhffgvrnyitusobwcxgwlwniqchfnssqttdrnqqcsrigjsxkzcmuoiyxzerakhmexuyeuhjfobrmkoqdljrlojjjysfdslyvckxhuleagmxnzvikfitmkfhevfesnwltekstsueefbrddxrmxokpaxsenwlgytdaexgfwtneurhxvjvpsliepgvspdchmhggybwupiqaqlhjjrildjuewkdxbcpsbjtsevkppvgilrlspejqvzpfeorjmrbdppovvpzxcytscycgwsbnmspihzldjdgilnrlmhaswqaqbecmaocesnpqaotamwofyyfsbmxidowusogmylhlhxftnrmhtnnljjhhcfvywsqimqxqobfsageysonuoagmmviozeouutsiecitrmkypwknorjjiaasxfhsftypspwhvqovmwkjuehujofiabznpipidhfxpoustquzyfurkcgmioxacleqdxgrxbldcuxzgbcazgfismcgmgtjuwchymkzoiqhzaqrtiykdkydgvuaqkllbsactntexcybbjaxlfhyvbxieelstduqzfkoceqzgncvexklahxjnvtyqcjtbfanzgpdmucjlqpiolklmjxnscjcyiybdkgitxnuvtmoypcdldrvalxcxalpwumfx");
|
#!/usr/bin/env python
# encoding: utf-8
"""
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
"""
# python 位运算?
# 一次过
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
return (1 if n%2 == 1 else 0) + self.hammingWeight(n/2)
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
re, tlist = [], []
def find(tn):
if len(tlist) == k:
re.append(tlist[:])
return
if tn > n or n - tn + 1 < k - len(tlist):
return
tlist.append(tn)
find(tn+1)
tlist.pop()
find(tn+1)
find(1)
return re
s=Solution()
print s.combine(4,2)
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
"""
# 看答案, 3次过, 1:<<= 2:a,b=0
class Solution(object):
def singleNumber(self, nums):
xor = 0
for x in nums: xor ^= x
a, b = 0, 0
tag = 1
while tag & xor == 0: tag <<= 1
for x in nums:
if x & tag == 0: a ^= x
else: b ^= x
return [a, b]
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# 不符合规定,但是能过,1次过
nums.sort()
re = []
if nums[0] != nums[1]: re.append(nums[0])
for i in range(1, len(nums)-1):
if nums[i] != nums[i-1] and nums[i] != nums[i+1]: re.append(nums[i])
if nums[len(nums)-1] != nums[len(nums)-2]: re.append(nums[len(nums)-1])
return re
|
#-*-coding:utf-8-*-
"""
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
"""
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
re=[];
sn = sorted(candidates);
lt = [];
def find(i, lt, target):
if i >= len(sn):
return;
if target <= 0:
if target == 0:
#print lt;
re.append(lt[:]);
return;
if target >= sn[i]:
lt.append(sn[i]);
find(i, lt, target-sn[i]);
lt.pop();
find(i+1, lt, target);
find(0,lt,target);
return re;
s=Solution();
print s.combinationSum([2,3,6,7], 7);
|
#Write a function to find the longest common prefix string amongst an array of strings.
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) < 1:
return "";
elif len(strs) == 1:
return strs[0];
s1 = self.longestCommonPrefix(strs[0:len(strs)/2]);
s2 = self.longestCommonPrefix(strs[len(strs)/2:]);
#print 's1:', s1;
#print 's2:', s2;
pt = 0;
for i in range(len(s1)):
#print 'i:',i
if i >= len(s2) or s1[i] != s2[i]:
#print i, len(s2), s1[i], s2[i]
break;
pt = i+1;
return s1[0:pt];
s=Solution();
print s.longestCommonPrefix(['c','c']);
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
"""
# 看网上的答案,双向宽搜 470ms -> 356ms
# 1. 有条件的转换方向:每次选候选少的方向扩展 356ms -> 124ms
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
lword = len(beginWord)
dis = [{beginWord}, {endWord}]
disInt = [1,1]
while len(dis[0])>0 and len(dis[1])>0:
newDis = set()
for wd in dis[0]:
for i in range(lword):
for j in 'abcdefghijklmnopqrstuvwxyz':
nwd = wd[0:i] + j + wd[i+1:]
if nwd in dis[1]: return disInt[0] +disInt[1]
if nwd in wordList:
newDis.add(nwd)
wordList.remove(nwd)
dis[0] = newDis
disInt[0] += 1
dis.reverse()
disInt.reverse()
return 0
# 宽搜,超时
# 看网上的答案,思路没问题,数据结构用复杂了
# 1. 不用next,用pop:过了。。。。特别慢,后5%
# 2.
# 3. remove adj: 740ms -> 670ms
# 4. 形成下一个字符串的时候右`"".join(x)`改成切片`x[0:i]+j+x[i+1:]`:670ms->472ms (72%)
# 5. 看分布还有明显更优的解法!!!
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
ls = [beginWord]
lword = [len(beginWord)]
import string
thisDep=[[beginWord,1]]
depth = 1
while len(thisDep)>0:
tp = thisDep.pop(0)
depth = tp[1]+1
wd = tp[0]
for i in range(lword[0]):
s=list(wd)
ps = wd[0:i]; rs = wd[i+1:]
for j in string.ascii_lowercase:
ns = ps + j + rs
if ns == endWord: return depth
if ns in wordList:
thisDep.append([ns,depth])
wordList.remove(ns) # 2, 804ms -> 740ms
return 0
# 超时
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
# 每次变换一个字符,记录字典中的临近值
ls = [beginWord]
lword = [len(beginWord)]
adj = {}
re = [None]
import string
def find():
for i in range(lword[0]):
s=list(ls[-1])
for j in string.ascii_lowercase:
s[i] = j
ns = "".join(s)
if ns == endWord:
re[0] = len(ls)+1 if re[0] == None else min(re[0], len(ls)+1)
elif ns in wordList and (not ns in ls) and (re[0] == None or re[0] > len(ls)):
ls.append(ns)
find()
ls.pop()
find()
return re[0]
s=Solution()
print s.ladderLength('a','c',['a','b','c'])
|
#!/usr/bin/env python
# encoding: utf-8
"""
Sort a linked list using insertion sort.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 不满足题意,但是快
class Solution(object):
def insertionSortList(self, head):
re = []
t = head
while t != None:
re.append(t.val)
t = t.next
re.sort()
i = 0; t = head
while t != None:
t.val = re[i]
i += 1; t = t.next
return head
# 一次过,速度超级慢
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 插入排序
if head == None: return head
head, tail, tmp = head, head, head.next
head.next = None
while tmp != None:
ntmp = tmp.next
t = head; pre = None
while t != None:
if t.val > tmp.val: break
t, pre = t.next, t
if pre == None:
tmp.next = head
head = tmp
else:
pre.next = tmp
tmp.next = t
tmp = ntmp
return head
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
"""
class Solution(object):
def jump(self, nums):
thisMax=0;
nextMax=nums[0];
i = 0;re=0;
while i < len(nums):
if i <= thisMax:
nextMax=max(nextMax,i+nums[i])
i+=1;
else:
thisMax=nextMax;
re += 1;
return re;
#class Solution(object):
# def jump(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# import Queue;
# qu=Queue.Queue();
# qu.put([0,0]);
# m=[-1 for i in range(len(nums))];
# inQ=[False for i in range(len(nums))];
# inQ[0]= True;
#
# while not qu.empty():
# top=qu.get();
# if m[top[0]]>=0:continue;
# m[top[0]]=top[1];
# if(top[0]==len(nums)-1):
# break;
# #print top[0];
# i=top[0];
# for j in range(i+nums[i], i, -1):
# if j < len(nums) and m[j]<0 and not inQ[j]:
# qu.put([j,top[1]+1]);
# inQ[j]=True;
# elif j < len(nums) and m[j]>=0: break;
# #print m;
# return m[len(nums)-1];
s=Solution();
#print s.jump([2,3,1,1,4]);
print s.jump([10,9,8,7,6,5,4,3,2,1,1,0]);
print s.jump([1,2,0,1]);
|
#!/usr/bin/env python
# encoding: utf-8
"""
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
"""
# 贪心,连续的上升序列
class Solution(object):
def maxProfit(self, prices):
l = len(prices)
if l == 0: return 0
us, ue = prices[0],prices[0]
re = 0
for i in range(1, l):
if prices[i] >= ue:
ue = prices[i]
else:
re += ue - us
us = ue = prices[i]
re += ue - us
return re
# 超时
class Solution(object):
def maxProfit(self, prices):
l = len(prices)
re = [0,0]
for i in range(1, l):
re.append(re[-1])
for j in range(0,i):
if prices[j] < prices[i]:
re[-1] = max(re[-1], re[j]+prices[i]-prices[j])
return re[-1]
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# 错误:同一天只能卖一个:找每天之后的最大值,如果比今天大,则在今天买的在之后的最大值天卖掉
l = len(prices)
maxAf = prices[-1]
re = 0
for i in range(l-2, -1, -1):
maxAf = max(maxAf, prices[i])
re += maxAf - prices[i]
return re
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
x1, x2, y1, y2 = 0, len(matrix)-1, 0, len(matrix[0])-1
re = []
while x1 < x2 and y1 < y2:
for j in range(y1, y2):
re.append(matrix[x1][j])
for i in range(x1, x2):
re.append(matrix[i][y2])
for j in range(y2, y1, -1):
re.append(matrix[x2][j])
for i in range(x2, x1, -1):
re.append(matrix[i][y1])
x1, x2, y1, y2 = x1+1, x2-1, y1+1, y2-1;
if x1 == x2:
for j in range(y1, y2+1):
re.append(matrix[x1][j])
elif y1 == y2:
for i in range(x1, x2+1):
re.append(matrix[i][y1])
return re
s=Solution()
print s.spiralOrder([[1,2,3],[4,5,6],[7,8,9]])
|
"""
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
"""
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def valid(x, y, tmp):
for i in range(0,9):
if board[i][y] == tmp or board[x][i] == tmp:
return False;
b1,b2 = (int)(x/3), (int)(y/3);
for k1 in range(3*b1, 3*b1+3):
for k2 in range(3*b2, 3*b2+3):
if board[k1][k2] == tmp: return False;
return True;
def dfs():
for i in range(0,9):
for j in range(0,9):
if board[i][j] == '.':
for k in '123456789':
if valid(i,j, k):
board[i][j] = k;
if( dfs()): return True;
return False;
return True;
dfs();
s=Solution();
s.solveSudoku(["....2....",".4..9....","...1.....","....4....",".1....69.",".5....7.3","4........","..3......","...4...74"]);
#s.solveSudoku(["........1",".37...5..",".....6...",".8...9...",".....2..7","...4....5",".........","...93....","..2......"]);
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
"""
class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
ls, lt = len(s), len(t)
re = [[1] + [0 for i in range(lt)] for j in range(2)]
re[0][0] = 1
for i in range(0, ls):
for j in range(0, lt):
r = i%2
if s[i] == t[j]:
re[r][j+1] = re[1-r][j] + re[1-r][j+1]
else: re[r][j+1] = re[1-r][j+1]
return re[(ls+1)%2][lt]
|
#-*-coding:utf-8-*-
"""
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:
相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
在一个数的上面画一条横线,表示这个数增值 1,000 倍,如=5000。
"""
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
ten=["","I","II","III","IV","V","VI","VII","VIII","IX","X"];
hundred=["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","C"];
thousands=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","M"];
k=["","M","MM","MMM"];
re = k[num/1000] + thousands[(num%1000)/100] + hundred[(num%100)/10] + ten[num%10];
return re;
s= Solution();
print s.intToRoman(1992);
print s.intToRoman(99);
print s.intToRoman(2015);
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
def getn(x, p):
re = 0
while x >= p:
re, x = re + x/p, x/p
return re
return getn(n, 5)
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given an array of integers, every element appears twice except for one. Find that single one.
"""
# Xor 的用法,一次过
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
re = 0
for x in nums: re ^= x
return re
|
"""
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
"""
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
re = 1;
while n> 1:
re = self.countAndSay2(re);
n -=1 ;
return str(re);
def countAndSay2(self, n):
ns = str(n);
c=ns[0];cn = 1;
re = '';
for i in range(1, len(ns)):
if ns[i] == c:
cn +=1;
else:
re = re + str(cn) + c;
cn = 1; c = ns[i];
re = re + str(cn) + c;
return int(re);
s=Solution();
print s.countAndSay(1);
print s.countAndSay(11);
print s.countAndSay(21);
|
#!/usr/bin/env python
# encoding: utf-8
"""
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
"""
# 网上答案,速度一般
class Solution(object):
def evalRPN(self, tokens):
stk = []
opr = {'-': lambda x,y: x-y, '+': lambda x,y:x+y, '*': lambda x,y:x*y, '/': lambda x,y: x/y}
for t in tokens:
try:
stk.append(float(t))
except:
stk.append(int(opr[t](stk.pop(-2), stk.pop(-1))))
return int(stk[0])
# 时间效率很差,调了很多次,在/这里,系统要求 6/-132=0,13/5=2
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
ns = []
for x in tokens:
if x in "+-*/":
tp2 = ns.pop()
tp1 = ns.pop()
if x == '+': ns.append(tp1+tp2)
if x == '-': ns.append(tp1-tp2)
if x == '*': ns.append(tp1*tp2)
if x == '/': ns.append(int((1.0*tp1/tp2)))
#if x == '/': ns.append((tp1/tp2))
print x, tp1, tp2, ns[-1]
else: ns.append(int(x))
return ns[0]
|
#!/usr/bin/env python
# encoding: utf-8
"""
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K) -3 3
-5 -10 1
10 30 -5 (P)
Notes:
The knight's health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
"""
# 听jess的方法
class Solution(object):
def calculateMinimumHP(self, dungeon):
if len(dungeon) == 0 or len(dungeon[0]) == 0: return 1
r, c = len(dungeon), len(dungeon[0])
init = [[0] * (c + 1) for j in range(r + 1)]
for i in range(r-1, -1, -1):
for j in range(c-1, -1, -1):
if j == c-1: # 只和下面有关
need = dungeon[i][j] - init[i+1][j]
init[i][j] = 0 if need >= 0 else -need
else : # 只和右面有关
needr = dungeon[i][j] - init[i][j+1]
needr = 0 if needr >= 0 else -needr
if i != r-1:
needd = dungeon[i][j] - init[i+1][j]
needd = 0 if needd >= 0 else -needd
needr = min(needd, needr)
init[i][j] = needr
return init[0][0]+1
# 1. re[k]写成re[i]
# 2. [[-3],[-7]] =>8?
# 3. 调整了更新策略还是不能过,在一个复杂的样例,应该是边界没有考虑清楚
# 4. 调整的判断策略,最后一个测试样例过不了43/44
# 5. 错误:比如maxBound=(12,2),maxLeft(20,200),但是最后一个点是(-20),中间有一条路径是(15,21),答案应该是15
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
if len(dungeon) == 0 or len(dungeon[0]) == 0: return 1
r, c = len(dungeon), len(dungeon[0])
minBound = [[[0,0] for i in range(c+1)] for j in range(r+1)]
maxLeft = [[[0,0] for i in range(c+1)] for j in range(r+1)]
# init [0][0] [bound, left]
def get(p1, p2, ind):
return p1[:] if p1[ind] > p2[ind] or (p1[ind] == p2[ind] and p1[1-ind] > p2[1-ind]) else p2[:]
for i in range(0, r):
for j in range(0, c):
#b1, l1, b2, l2
re = [minBound[i][j-1][:], maxLeft[i][j-1][:], minBound[i-1][j][:], maxLeft[i-1][j][:]]
for k in range(4):
re[k][1] += dungeon[i][j]
if re[k][1] <= 0:
re[k][0] += re[k][1] -1
re[k][1] = 1
elif i == 0 and j == 0:
re[k][1] += 1
if j != 0:
minBound[i][j] = get(re[0], re[1], 0)
maxLeft[i][j] = get(re[0], re[1], 1)
if i > 0:
t = get(re[2], re[3], 0)
minBound[i][j] = get(minBound[i][j], t, 0)
s = get(re[2],re[3],1)
maxLeft[i][j] = get(maxLeft[i][j], s, 1)
else:
minBound[i][j] = get(re[2], re[3], 0)
maxLeft[i][j] = get(re[2], re[3], 1)
print i,j,minBound[i][j], maxLeft[i][j],
print ""
return max(1,-minBound[r-1][c-1][0])
s=Solution()
#print s.calculateMinimumHP([[-3],[-7]])
#print s.calculateMinimumHP([[3,-20,30],[-3,4,0]])
#print s.calculateMinimumHP([[1,-3,3],[0,-2,0],[-3,-3,-3]])
|
"""
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# bug1: [[1,1,2],[1,2,2]]返回了第一个,没有合并:
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
lens = len(lists);
if lens == 0:
return None;
elif lens == 1:
return lists[0];
l1 = self.mergeKLists(lists[0:lens/2]);
l2 = self.mergeKLists(lists[lens/2:]);
return self.merge2List(l1, l2);
def merge2List(self, l1, l2):
if l1 is None:
return l2;
elif l2 is None:
return l1;
head = l1; p1 = l1.next; p2 = l2;
if l1.val > l2.val:
p1 = l1; p2 = l2.next;head = l2;
p = head;
while p1 != None and p2 != None:
if p1.val < p2.val:
p.next = p1; p1 = p1.next;
else:
p.next = p2; p2 = p2.next;
p = p.next;
p.next = p1 if p1 != None else p2;
return head;
|
#!/usr/bin/env python
# encoding: utf-8
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the eval built-in library function.
"""
# 8次过,考虑的不清楚
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
# 1. str => opers + nums
# 1.1 数字:做一次操作;+/-/(:不做;):一直做到(
v = -1
ops, num = [], []
for x in s:
if x in ')+-':
if v >= 0:
num.append(v)
v = -1
if len(ops) > 0:
op = ops.pop()
if op == '(':
if x != ')':
ops.append(x);
continue
n1, n2 = num.pop(), num.pop()
num.append(n2 - n1 if op == '-' else n1 + n2)
if x == ')' and len(ops) > 0 and ops[-1] == '(': ops.pop()
if x in '+-(':
ops.append(x)
elif x in '0123456789':
v = v*10 + int(x) if v >= 0 else int(x)
if v >= 0:
num.append(v)
if len(ops) > 0:
return num[0] - num[1] if ops[0] == '-' else num[1] + num[0]
return num[0]
|
#!/usr/bin/env python
# encoding: utf-8
"""
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
"""
# 看网上答案,9次过
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
l, r, size = 0, len(nums)-1, len(nums)
while l < r:
m = (l+r)/2
if nums[m] == target: return True
while l < m and nums[l] == nums[m]:
l += 1
if nums[l] < nums[m]:
if nums[l] <= target < nums[m]:
r = m-1
else: l = m+1
else:
if nums[m] < target < nums[r]:
l = m+1
else: r = m-1
return False
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
"""
# 13次过,递归没有考虑请
class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
# dn[i]表示所有i位数字含有的1个数
# re[i]表示n的后i位数字含有的1个数
if n <= 0: return 0
rn = (str(n))[-1::-1]
nl = len(rn)
dn, re, p10, leftn = [0]*nl, [0]*nl, 1, 0
for i in range(nl):
t = int(rn[i])
if t > 1:
re[i] = re[i-1] + p10 + t * dn[i-1]
elif t == 1:
re[i] = re[i-1] + (leftn+1) + dn[i-1]
else: re[i] = re[i-1]
dn[i] = dn[i-1] * 10 + p10
leftn, p10 = leftn + t * p10, p10 * 10
return re[-1]
|
#!/usr/bin/env python
# encoding: utf-8
"""
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
Return:
["AAAAACCCCC", "CCCCCAAAAA"].
"""
# 2次过,-9,,10搞混了
class Solution(object):
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
wf = {}
for i in range(0, len(s)-9):
ss = s[i:i+10]
wf[ss] = wf.get(ss, 0) + 1
re = []
for i in wf:
if wf[i] > 1:
re.append(i)
return re
|
#!/usr/bin/env python
# encoding: utf-8
"""
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
"""
# 提交12次,各种情况没考虑到,python自定义函数不会写,排序的方向,判断的终止条件
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
if len(nums) < 1: return ""
def cpr2(i1, i2):
s1, s2 = str(i1), str(i2)
l1, l2 = len(s1), len(s2)
t1, t2 = -1, -1
while True:
t1, t2 = (t1+1)%l1, (t2+1)%l2
if s2[t2] > s1[t1]: return 1
elif s2[t2] < s1[t1]: return -1
if t1 == l1-1 and t2 == l2-1: return 0
nums.sort(cpr2)
#print nums
i = -1
re = "".join(str(x) for x in nums)
while i + 2 < len(re) and re[i+1] == '0':
i += 1
return re[i+1:]
|
# -*- coding: utf-8 -*-
roomList = {
"livingRoom",
"masterBedroom",
# "secondBedroom",
# "thirdBedroom",
"bathroom",
"kitchen",
"diningRoom",
"studyRoom"
}
width = 30
height = 30
from houses import house
# myHouse = house(roomList, width, height)
# myHouse.printHouseInfo()
from human import human
# class T:
# # value = 0
# # _vlist = []
# def __init__(self, value):
# self.setValue(value)
# def setValue(self, value):
# self._vlist = []
# self.value = value
# def getValue(self):
# return self.value
# def appendValueList(self, value):
# self._vlist.append(value)
# def printValueList(self):
# for v in self._vlist:
# print " ", v,
# print ''
# tt = T(1234)
# tt.appendValueList(666)
# myList = []
# for i in range(5):
# tempT = T(i)
# tempT.setValue(i + 5)
# myList.append(tempT)
# T.value = 100
# count = 0
# for tT in myList:
# for i in range(5):
# tT.appendValueList(i + count * 5)
# count = count + 1
# # print tempT.getValue()
# # myList[0].vlist[3] = 44
# for ttT in myList:
# ttT.printValueList()
# print ttT.getValue(), T.value
# print 't: ', tt.printValueList()
# roomDict = {
# "livingRoom" : 0,
# "masterBedroom" : 100,
# "secondBedroom" : 200,
# "thirdBedroom" : 300,
# "bathroom" : 400,
# "kitchen" : 500,
# "diningRoom" : 600,
# "studyRoom" : 700
# }
# print roomDict.get('asdasdad') == None
# import matplotlib.pyplot as plt
# import turtle
# import time
# from graphics import *
# graphics.test()
# win = GraphWin()
# pt = Point(100, 50)
# win.getMouse()
# pt.draw(win)
# win.getMouse()
# cir = Circle(pt, 25)
# win.getMouse()
# cir.draw(win)
# win.getMouse()
# cir.setOutline('red')
# win.getMouse()
# cir.setFill('blue')
# win.getMouse()
# line = Line(pt, Point(150, 100))
# win.getMouse()
# line.draw(win)
# win.getMouse()
# win.close()
# # plt.
# # plt.show()
# turtle.color("purple")
# # turtle.size(5)
# turtle.goto(10,10)
# turtle.forward(100)
# time.sleep(100)
# win = GraphWin()
# pt1 = Point(10,10)
# pt2 = Point(10,100)
# line = Line(pt1, pt2)
# pt1.draw(win)
# pt2.draw(win)
# line.draw(win)
# # line.draw(win)
# for i in range(10,300):
# for j in range(10,300):
# pt2._move(i,j)
# # line.draw(win)
# win.getMouse()
import time
currentTimeStr = "2016 6 18 00:00:00"
currentTime = time.mktime(time.strptime(currentTimeStr, "%Y %m %d %H:%M:%S"))
endTimeStr = "2016 6 19 00:00:00"
endTime = time.mktime(time.strptime(endTimeStr, "%Y %m %d %H:%M:%S"))
# startTimeStr = time.strftime("%Y %m %d", time.localtime(currentTime))
# print startTimeStr
# startTime = time.mktime(time.strptime( startTimeStr + " 16:49:19", "%Y %m %d %H:%M:%S"))
# print time.strftime("%H:%M:%S", time.localtime(startTime))
fp = open('light.txt', 'w')
from light import lightSimulator
simL = lightSimulator(currentTime)
while (currentTime < endTime):
fp.write(time.strftime("%H:%M:%S", time.localtime(currentTime)))
fp.write("\t")
fp.write(str(simL.getCurrentLight(currentTime)))
fp.write("\n")
currentTime += 30
if(simL.getCurrentLight(currentTime) > 10):
simL.setLightOff(currentTime)
if(simL.isDarkness(currentTime)):
simL.setLightOn(currentTime)
|
# Print message for user.
print("What is your name?")
# Take user name as input
name = input()
print(f"hello, {name}") |
#skip by twos
#use slices
number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def oddnumber(number):
odds = number[0:11:2]
return odds
print oddnumber(number) |
a, b, c, d = 0, 0, 0, 0
x = input("please Enter Your Password: ")
if len(x) >= 6 :
for i in x:
if i.islower():
a+=1
elif i.isupper():
b+=1
elif i.isdigit():
c+=1
elif(i=='@'or i=='$' or i=='_'or i=="!" or i=="%" or i=="^" or i=="&" or i=="*" or i=="(" or i==")" or i=="-" or i=="+"):
d+=1
if (a>=1 and b>=1 and c>=1 and d>=1 and a+b+c+d==len(x)):
print(" \n************** Your Password is Strong *****************")
else:
print("\n!!!!!!!!!!!!!!!!! Weak Password !!!!!!!!!!!!!!!!!!!!!!!!!")
|
x=list(input("Pleas Enter your list fo data: ").split())
x.sort()
print("Your Max is :",x[0])
x.reverse()
print("Your Min is :",x[0])
|
"""[Matrix operation simulate Neural network operation]"""
#Y_output = activation(X_input * Weight + bias)
X = tf.Variable([[0.4, 0.2, 0.4]])
W = tf.Variable([[-0.5, -0.2],
[-0.3, 0.4],
[-0.5, 0.2]])
b = tf.Variable([[0.1, 0.2]])
XWb = tf.matmul(X, W) + b
Y1 = tf.nn.relu(tf.matmul(X,W) + b) #relu feature : >0~X, <0N0
Y2 = tf.nn.sigmoid(tf.matmul(X,W) + b)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(XWb))
print(sess.run(Y1))
print(sess.run(Y2))
(_XWb, _Y1, _Y2) = sess.run((XWb, Y1, Y2)) #i@oҦ_XWb, _Y1, _Y2
#Random variable
W = tf.Variable(tf.random_normal([3, 2])) #3*2 matrix = 3rows * 2columns = 3C * 2
#input ʺAJ
import numpy as np
W = tf.Variable(tf.random_normal([3, 2]))
b = tf.Variable(tf.random_normal([1, 2]))
X = tf.placeholder("float", [None,3]) #"float"data type, NoneĤ@ǤJƤ, 3ĤGƶq3ӭ
Y1 = tf.nn.relu(tf.matmul(X,W) + b)
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
X_array = np.array([[0.4, 0.2, 0.4]])
(_b, _W, _X, _Y) = sess.run((b, W, X, Y1), feed_dict = {X:X_array})
print(_b)
print(_W)
print(_X)
print(_Y)
#layer , Create 2 layers neurals network
def layer(output_dim, input_dim, inputs, activation = None): #Xneuronsƶq, Jneuronsƶq, Jmatrix,
W = tf.Variable(tf.random_normal([input_dim, output_dim]))
b = tf.Variable(tf.random_normal([1, output_dim]))
XWb = tf.matmul(inputs, W) + b
if activation is None:
outputs = XWb
else:
outputs = activation(XWb)
return outputs
#3 layers neurals network
X = tf.placeholder("float", [None, 4])
h = layer(output_dim = 3, input_dim = 4, inputs = X, activation = tf.nn.relu) #hidden layer
y = layer(output_dim = 2, input_dim = 3, inputs = h) #output layer
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
X_array = np.array([[0.4, 0.2, 0.4, 0.5]])
(LX, Lh, Ly) = sess.run((X, h, y), feed_dict = {X:X_array})
print(LX)
print(Lh)
print(Ly)
"""[Layer Debug, iweight & bias]"""
def layer_d(output_dim, input_dim, inputs, activation = None):
W = tf.Variable(tf.random_normal([input_dim, output_dim]))
b = tf.Variable(tf.random_normal([1, output_dim]))
XWb = tf.matmul(inputs, W) + b
if activation is None:
outputs = XWb
else:
outputs = activation(XWb)
return outputs, W, b
X = tf.placeholder("float", [None, 4])
h, W1, b1 = layer_d(output_dim = 3, input_dim = 4, inputs = X, activation = tf.nn.relu) #hidden layer
y, W2, b2 = layer_d(output_dim = 2, input_dim = 3, inputs = h) #output layer
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
X_array = np.array([[0.4, 0.2, 0.4, 0.5]])
(LX, Lh, Ly, w_1, w_2, b_1, b_2) = sess.run((X, h, y, W1, W2, b1, b2), feed_dict = {X:X_array})
print(LX)
print(w_1, b_1)
print(Lh)
print(w_2, b_2)
print(Ly)
|
#!/bin/python3
# -*- coding: utf-8 -*-
'''
Created on 2016年2月24日
@author: qiuxiangu
'''
class MyNgram(set):
def __init__(self, N=0):
self.N = N
def split(self,string):
self.str = string
tmp = ''
bigram = []
if self.N == 0 :
bigram.append(self.str)
else:
for item in self.str:
tmp = tmp+item
if(self.N == len(tmp)):
bigram.append(tmp)
tmp = tmp[1:]
return bigram
if __name__ =="__main__":
doc = "东方大幅降低了"
print(MyNgram(0).split(doc)) |
# coding=utf-8
# encoding=utf8
import sys
# from aetypes import end
#[1] No sistema de numeração romana as cifras escrevem-se com as letras I, V, X, L, C, D e M.
# Exemplo: 125 é representado por CXXV. Implemente um programa que leia um número inteiro,
# caso ele esteja dentro do intervalo de 1 a 999, mostre o número romano equivalente,
# caso contrário mostre “valor fornecido fora dos limites operacionais”.
# DICA: Utilize um vetor de strings para representar as unidades em números romanos,
# outro para as dezenas e outro para as centenas.
# Separe, usando mod e div, o valor da unidade, da dezena e da centena do número fornecido e use estes valores como i
# ́ndices de consulta aos vetores em romanos.
# Observação: tabela com as referências da numeração romana disponível em
# http://pt.wikipedia.org/wiki/Números_romanos
def UnidadeEmRomanos(uni):
if uni == 1: return "I"
elif uni == 2: return "II"
elif uni == 3: return "III"
elif uni == 4: return "IV"
elif uni == 5: return "V"
elif uni == 6: return "VI"
elif uni == 7: return "VII"
elif uni == 8: return "VIII"
elif uni == 9: return "IX"
else: return ""
def DezenaEmRomanos(dez):
if dez == 10: return "X"
elif dez == 20: return "XX"
elif dez == 30: return "XXX"
elif dez == 40: return "XL"
elif dez == 50: return "L"
elif dez == 60: return "LX"
elif dez == 70: return "LXX"
elif dez == 80: return "LXXX"
elif dez == 90: return "XC"
else: return ""
def CentenaEmRomanos(cen):
if cen == 100 : return "C"
elif cen == 200 : return "CC"
elif cen == 300 : return "CCC"
elif cen == 400 : return "CD"
elif cen == 500 : return "D"
elif cen == 600 : return "DC"
elif cen == 700 : return "DCC"
elif cen == 800 : return "DCCC"
elif cen == 900 : return "CM"
else: return ""
def alg1():
n = int(input("Digite um número entre 1 e 999: "))
if n > 999:
print("Fora dos limites operacionais")
else:
temp = n
centena = divmod(temp, 100)[0]*100
temp -= centena
dezena = divmod(temp, 10)[0]*10
temp -= dezena
unidade = n - centena - dezena
romCentena = CentenaEmRomanos(centena)
romDezena = DezenaEmRomanos(dezena)
romUnidade = UnidadeEmRomanos(unidade)
romN = romCentena + romDezena + romUnidade
print("{} = {}".format(n, romN))
def alg2():
import json
#Escreva um “Mini-conjugador de verbos regulares”, ou seja, um programa que receba como entrada um verbo regular
# no infinitivo e mostre a sua conjugação. Como limitações: (i) considerar apenas verbos regulares da primeira
# conjugação (terminação “ar”), segunda conjugação (terminação “er”) e terceira conjugação (terminação “ir”);
# (ii) mostrar apenas os tempos Presente do Indicativo, Pretérito Perfeito e Futuro do Presente.
# DICA: Utilize um vetor de strings para representar os pronomes pessoais,
# e um vetor de desinências verbais para cada tempo/conjugação. A base deste exercício será resolvida em sala e
# estará disponível no BlackBoard, consulte-o com inspiração para sua implementação e como conceito para a
# solução dos demais problemas.
# Observação: modelo de conjugação em http://pt.wikipedia.org/wiki/Modelos_de_conjugação_dos_verbos
file_obj = open("LISTA_11_CONJUGACOES_VERBAIS.txt","r")
text = file_obj.read()
database = json.loads(text,encoding="utf-8")
#1
# primeira = info["1"]
# primPP = primeira["Preterito Perfeito"]
# nos = primPP[("nós")]
verbo = input("Digite um verbo: ")
termino = verbo[-2]
conjugacao = ""
if termino == "a" : conjugacao = "1"
elif termino == "e" : conjugacao = "2"
elif termino == "i" : conjugacao = "3"
else:
print("Erro ao ler verbo")
return
print("")
radical = verbo[:len(verbo) -2]
print("radical: {}".format(radical))
pronomes = ["eu", "tu", "ele", "nós", "vós", "eles"]
tempos = ["presente" , "preterito perfeito", "futuro do presente"]
for tempo in tempos:
print("--{}--".format(tempo))
for pronome in pronomes:
# pronomeUtf = pronome
terminacao = database[conjugacao][tempo][pronome]
print("{} {}{} ".format(pronome, radical, terminacao))
print("\n")
def alg3():
import json
# Leet (ou l33t) é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras,
# como números ou caracteres similares graficamente.
# O uso do leet reflete uma subcultura relacionada ao mundo dos jogos de computador e da Internet;
# veja explicação em: http://pt.wikipedia.org/wiki/Leet
# Usando vetores de strings e a tabela do alfabeto leet disponível no link acima,
# desenvolva um pequeno tradutor de leet, cuja função é ler uma frase do usuário e depois mostrá-la
# em seu formato original e 3m $3μ f0rm4t0 l33t.
# Como são várias as possibilidades de tradução para cada caracter, mostre três formatos,
# fácil (deixando algumas letras normais),
# médio (trocando a maior parte das letras, mas com equivalentes mais conhecidos) e
# difícil (trocando todas as letras por equivalentes elaborados).
# DICA: Utilize um vetor de strings para armazenar cada uma das versões dos caracteres em leet
# (fácil, médio e difícil), use o valor de cada caracter fornecido na frase original como indice de acesso
# ao vetor (a função ord devolve o código do caracter).
file_obj = open ("LISTA_11_DICIONARIO_NORMAL_PARA_LEET.txt", "r")
text = file_obj.read ( )
database = json.loads (text, encoding="utf-8")
facilDict = database["facil"]
print(facilDict)
text = (input("Digite um texto: "))
textLength = len(text)
leetText = ""
for c in text:
upC = c.upper()
exist = upC in facilDict
if (upC in facilDict) and (facilDict[upC] != ""): leetText += facilDict[upC]
else: leetText += upC
print(leetText)
def alg4():
# Elabore um algoritmo que leia um número inteiro (n), e se este número atender a condição 1 ≤ n ≤ 999,
# mostre seu valor por extenso (exemplo: para n = 38, a saída será trinta e oito);
# caso contrário mostre “Entrada fora dos limites operacionais”.
#fazer com string fica mais fácil de pegar os valores
# Elabore um algoritmo que leia um número inteiro (n), e se este número atender a condição 1 ≤ n ≤ 99,
# mostre seu valor por extenso (exemplo: para n = 38, a saída será trinta e oito);
# caso contrário mostre “Entrada fora dos limites operacionais”.
n = int(input ("Digite um número entre 0 e 99: "))
if n < 1 and n > 999:
print ("Fora dos limites operacionais")
return
text = strNumero (n)
print ("{} = {}".format (n, text))
def strNumero(n):
import math
if n < 1 and n > 999:
print ("Fora dos limites operacionais")
return ""
else:
if n < 10:
return strUnidade (n)
elif n == 10:
return strDezena (n/10)
elif n < 20:
return strDezVinte (n)
elif n == 100:
return "cem"
else:
#424 n/100 = 4,24 = 4
c = math.floor(n / 100)
txtCentena = strCentena(c)
print("c: {}".format(c))
#424 -> 424 - 400 = 24 -> 24/10 = 2,4 -> 2
d = n - c * 100
txtDezena = ""
if d > 10 and d < 20:
txtDezena = strDezVinte(d)
else:
d = math.floor((n - c * 100)/10)
txtDezena = strDezena(d)
print ("d: {}".format (d))
u = n - d * 10 - c * 100
txtUnidade = strUnidade(u)
print ("u: {}".format (u))
e1 = ""
e2 = ""
if (txtCentena != "" and (txtDezena != "")) : e1 = " e "
if txtUnidade != "" : e2 = " e "
return "{}{}{}{}{}".format(txtCentena, e1, txtDezena, e2, txtUnidade)
def strUnidade(n):
if n == 1: return "um"
elif n == 2: return "dois"
elif n == 3: return "tres"
elif n == 4: return "quatro"
elif n == 5: return "cinco"
elif n == 6: return "seis"
elif n == 7: return "sete"
elif n == 8: return "oito"
elif n == 9: return "nove"
else: return ""
def strDezena(n):
if n == 1: return "dez"
elif n == 2: return "vinte"
elif n == 3: return "trinta"
elif n == 4: return "quarenta"
elif n == 5: return "cinquenta"
elif n == 6: return "sessenta"
elif n == 7: return "setenta"
elif n == 8: return "oitenta"
elif n == 9: return "noventa"
else: return ""
def strDezVinte(n):
if n == 11: return "onze"
elif n == 12: return "doze"
elif n == 13: return "treze"
elif n == 14: return "quatorze"
elif n == 15: return "quinze"
elif n == 16: return "dezesseis"
elif n == 17: return "dezessete"
elif n == 18: return "dezoito"
elif n == 19: return "dezenove"
else: return ""
def strCentena(n):
#deve-se passar o numero total e a funcao vai retornar a centena
if n == 1 : return "cento"
elif n == 2 : return "duzentos"
elif n == 3 : return "trezentos"
elif n == 4 : return "quatrocentos"
elif n == 5 : return "quinhentos"
elif n == 6 : return "seiscentos"
elif n == 7 : return "setecentos"
elif n == 8 : return "oitocentos"
elif n == 9 : return "novecentos"
else: return ""
def alg5():
import os
# Use the next line every time you wish to 'clear' the screen. Works with Windows and Linux.
os.system ('cls' if os.name == 'nt' else 'clear')
# Desenvolva um programa para o “Jogo da Forca”.
# Para tal, crie um vetor de strings inicializado com um conjunto de palavras-chave
# (por exemplo: nomes de capitais do Brasil, ou times de futebol da Serie A ou Países da América do Sul, etc).
# Sorteie uma das palavras para ser o segredo e forneça seis vidas para o usuário acertar o segredo.
# A cada rodada informe o número de vidas disponíveis e a disposição das letras acertadas e ausentes
# na palavra segredo (lembre de quando brincava com este jogo em caderno na infância),
# mostre também quais as letras que já foram usadas
# (e não compute acerto ou erro no caso do usuário repetir uma letra já fornecida).
selecionado = EscolhaUmaPalavra()
palavra = selecionado[ "valor" ].upper()
# print("selecionado: {}".format(selecionado))
titulo = "---FORCA---\n"
titulo += "Categoria: {}".format(selecionado["categoria"]) + "\n"
titulo += "Dica: {}\nnúmero de letras: {}".format(selecionado["dica"], len(palavra))
print(titulo)
vidas = 5
charOculto = "*"
palpite = ""
for (i,char) in enumerate(palavra):
if char == " " : palpite += char
else: palpite += charOculto
# tira os espacos em branco do palpite
#COLOCAR UM ARRAY COM AS LETRAS QUE JA FORAM USADAS
letras = []
mensagem = ""
fimDeJogo = False
continuaLoop = True
while (continuaLoop):
os.system('cls' if os.name == 'nt' else 'clear')
strLetras = "Letras já palpitadas:["
for (i, letra) in enumerate(letras):
strLetras += letra
if i < len(letras) - 1:
strLetras += ","
strLetras += "]"
print(titulo)
print(strLetras)
print("PALAVRA: {}".format (palpite))
print(mensagem)
printForca(vidas)
if fimDeJogo :
continuaLoop = False
continue
c = input("Digite uma letra: ").upper()
if letras.__contains__(c):
mensagem = "Você já tentou essa letra."
else:
letras.append(c)
letras.sort()
if palavra.find(c) == -1 :
mensagem = "Palavra secreta não possui a letra: {}".format(c)
vidas -= 1
if vidas == 0 :
mensagem = "Você perdeu.\nPalavra secreta é: {}".format(palavra)
fimDeJogo = True
else:
temp = ""
for (i, char) in enumerate(palavra):
if char == c : temp += char
else: temp += palpite[i]
palpite = temp
print("-"*30)
if palpite.find(charOculto) == -1:
mensagem = "Você venceu"
fimDeJogo = True
def printForca(vidasRestantes):
# strForca = "Vidas restantes: {}\n".format(vidasRestantes)
strForca = "_____\n"
if vidasRestantes == 5:
strForca += "|\n"*3
if vidasRestantes == 4:
strForca += "| O\n"
strForca += "|\n" * 2
if vidasRestantes == 3:
strForca += "| O\n"
strForca += "| |\n"
strForca += "|\n"
if vidasRestantes == 2:
strForca += "| O\n"
strForca += "| -|\n"
strForca += "|\n"
if vidasRestantes == 1:
strForca += "| O\n"
strForca += "| -|-\n"
strForca += "|\n"
if vidasRestantes == 0:
strForca += "| O\n"
strForca += "| -|-\n"
strForca += "| / \\\n"
print(strForca)
def EscolhaUmaPalavra():
import json
import random
file_obj = open ("LISTA_11_FORCA.txt", "r")
text = file_obj.read()
database = json.loads(text, encoding="utf-8")
categorias = ["filmes", "estados e capitais", "paises e capitais", "times", "nomes dos alunos"]
#escolhe uma categoria
categoria = categorias[random.randrange(0,len(categorias))]
#pega todos os itens daquela categoria
itens = database[categoria]
#escolhe um item daquela categoria
item = itens[random.randrange(0,len(itens))]
textoDica = ""
chave = ""
#como o banco de dados nao esta padronizado, dependendo da categoria escolhida tem que
#ser feita a busca em chaves diferentes
if categoria == "filmes":
chave = "titulo"
textoDica = "Ganhador da {}a edicao do Oscar".format(item["edicao"])
elif categoria == "times":
chave = "nome"
textoDica = "Time da 1a divisão do Campeonato Brasileiro de 2018"
elif categoria == "estados e capitais":
chave = "capital"
estado = item["estado"]
textoDica = "Capital de {}".format(estado)
elif categoria == "paises e capitais":
chave = "pais"
continente = item["continente"]
textoDica = "Continente: {}".format(continente)
elif categoria == "nomes dos alunos":
chave = "nome"
textoDica = "Nome de um aluno(a)"
valor = item[chave]
retornar = {"categoria" : categoria, "valor" : valor, "dica" : textoDica}
return retornar
a = 1
nProblemas = 5
while 0 < a <= nProblemas:
print("-"*40)
a = int(input ('Qual algoritmo voce deseja?: '))
if (a == 1) : alg1()
elif (a == 2) : alg2()
elif (a == 3) : alg3()
elif (a == 4) : alg4()
elif (a == 5) : alg5()
|
# coding=utf-8
#PONTIFÍCIA UNIVERSIDADE CATÓLICA DO PARANÁ ESCOLA POLITÉCNICA
#RACIOCÍNIO ALGORÍTMICO
#PROF. HENRI FREDERICO EBERSPÄCHER
#Estudante: Ricardo Varjão
# PROBLEMAS LISTA 5: Selecao Composta
def alg1():
#[1] A partir das informações contidas na tabela abaixo, elabore um algoritmo que leia a massa em kg de um
# boxeador e mostre a qual categoria ele pertence.
# Caso ele não se encaixe, informe “Categoria inferior a Super-médio”.
# Lembrando que 1 quilograma = 2,20462262 libras.
# Massa Categoria
# 201 lb ou mais Peso-pesado
# 176 até 200 lb Cruzador
#169 até 175 lb Meio-pesado
#161 até 168 lb Super-médio
massaKg = float(input("Massa do lutador (kg): "))
massaLb = 2.20462262 * massaKg
limites = [161, 169, 176, 201]
categorias = ["Super-médio", "Meio Pesado", "Cruzador", "Peso-Pesado"]
print("massa em lb: {}".format(massaLb))
if massaLb < limites[0] :
print("Categoria inferior a Super-médio")
return
categoria = categorias[3]
for (i, limite) in enumerate(limites):
if i == 0 : continue #ja foi feita essa verificacao
else:
#print("i:{} limite:{} categoria: {}".format(i, limites[i], categorias[i]))
if massaLb <= limite :
categoria = categorias[i-1]
break
print("-"*10)
print("Peso (kg): {:.2f} \nPeso (lb): {:.2f}".format(massaKg, massaLb))
print("Categoria: {}".format(categoria))
print("-" * 10)
def alg2():
# Uma determinada loja de varejo classifica seus produtos utilizando códigos conforme
# descrito na tabela abaixo. Elabore um algoritmo que leia o código de um produto e mostre sua classificação.
# Para qualquer código inexistente, mostre “Código inválido”.
# Código Classificação
# 1 Alimento não perecível
# 2, 3 ou 4 Alimento perecível
# 5 ou 6 Vestuário
# 7 Higiene Pessoal
# 8 até 15 Limpeza e utensílios domésticos
#cadastro das categorias
categorias = []
categorias.append({"codigoInicial" : 1, "codigoFinal" : 1, "descricao" : "Alimento não perecível"})
categorias.append ({"codigoInicial": 2, "codigoFinal": 4, "descricao": "Alimento perecível"})
categorias.append ({"codigoInicial": 5, "codigoFinal": 6, "descricao": "Vestuário"})
categorias.append ({"codigoInicial": 7, "codigoFinal": 7, "descricao": "Alimento perecível"})
categorias.append ({"codigoInicial": 8, "codigoFinal": 15, "descricao": "Limpeza e utensílios domésticos"})
inputCodigo = int(input("Digite o codigo do produto: "))
categoriaSelecionada = "Código inválido"
for categoria in categorias:
if categoria["codigoInicial"] <= inputCodigo <= categoria["codigoFinal"]:
categoriaSelecionada = categoria["descricao"]
break
print("Categoria Selecionada: {}".format(categoriaSelecionada))
def alg3():
#Em uma determinada loja de eletrodomésticos, os produtos podem ser adquiridos da seguinte forma:
#Opção Condição Cálculo
# 1 à vista 8% de desconto
# 2 em 2 parcelas 4% de desconto, dividido em duas vezes
# 3 em 3 parcelas sem desconto, dividido em três vezes
# 4 em 4 parcelas 4% de acréscimo, dividido em quatro vezes
#Elabore um algoritmo que leia a opção do cliente e o preço de tabela do produto,
#mostrando então o valor calculado conforme a condição escolhida.
valorDoProduto = float(100) #valor lido do sistema
opcoes = []
opcoes.append({"codigo" : 1, "nParcelas" : 1 , "fator" : -0.08})
opcoes.append({"codigo" : 2, "nParcelas" : 2 , "fator" : -0.04})
opcoes.append({"codigo" : 3, "nParcelas" : 3 , "fator" : 0.00})
opcoes.append({"codigo" : 4, "nParcelas" : 4 , "fator" : 0.04})
inputOpcao = int(input("Digite a opcao de pagamento: "))
valorDasParcelas = valorDoProduto
nParcelas = 0
valorTotal = 0
for opcao in opcoes:
if inputOpcao == opcao["codigo"]:
fator = opcao["fator"]
nParcelas = opcao["nParcelas"]
valorTotal = valorDoProduto *(1 + fator)
valorDasParcelas = valorTotal / nParcelas
break
print("\n\n")
print(" Valor do produto: R$ {:.2f}".format(valorDoProduto))
print(" Número de parcelas: {}".format(nParcelas))
print(" Valor das parcelas: R$ {:.2f}".format(valorDasParcelas))
print("Valor total a pagar: R$ {:.2f}".format(valorTotal))
print("\n\n")
def alg4():
import requests
import json
#Uma empresa de câmbio permite a compra de dólares, libras e euros.
# Elabore um algoritmo que leia o código da moeda que o cliente quer comprar e qual o
# montante que ele quer adquirir nessa moeda. Mostre então quanto ele deverá pagar em reais
# para concretizar a operação.
# Além da cotação, a empresa cobra uma comissão de 5% (quando o valor for menor que R$ 1.000),
# ou de 3% (quando maior ou igual a R$1.000).
#fiz de uma forma diferente, o app faz uma requisicao utilizando a api: https://www.exchangerate-api.com/app/dashboard
# inputMoeda = str(input("moeda\nUSD - Dolar\nGBP United Kingdom Pound\nEUR Euro Member Countries: "))
# primeiro puxa a cotacao de todos e mostra numa tabela
# Where USD is the base currency you want to use (i'm using BRL)
url = 'https://v3.exchangerate-api.com/bulk/4d52cef7ad4a863ae9e86e9e/BRL'
# Making our request
response = requests.get(url)
data = response.json()
# Your JSON object
# print data
# dumps the json object into an element
json_str = json.dumps (data)
# load the json to a string
resp = json.loads (json_str)
# print the resp
# print (resp)
rates = resp['rates']
print("Cotacao: BRL 1,00")
print("Data:")
print("resp: {}".format(resp))
for key in rates:
print("BRL 1,00 = {} {} ".format(key, rates[key]))
moeda = str(raw_input("moeda: ")).upper()
valor = input("valor a comprar ({}): ".format(moeda))
# extract an element in the response
cotacao = resp['rates'][moeda]
valorTransacao = valor / cotacao
# Além da cotação, a empresa cobra uma comissão de 5% (quando o valor for menor que R$ 1.000),
# ou de 3% (quando maior ou igual a R$1.000).
comissao = 0
if valorTransacao < 1000 : comissao = 0.05
else: comissao = 0.03
valorComissao = valorTransacao * comissao
valorTotal = valorTransacao + valorComissao
print("\n\n---------------------------------")
print("Cotacao: BRL 1,00 = {} {}".format(moeda, cotacao))
print("Valor da transacao: BRL {:.2f}".format(valorTransacao))
print("Valor da comissao: BRL {:.2f}".format(valorComissao))
print("Valor total: BRL {:.2f}".format(valorTotal))
print("---------------------------------\n\n")
def alg5():
import random
#Escreva um algoritmo que jogue Joquempô (Pedra, Papel e Tesoura) com o usuário;
# ou seja ele escolhe randomicamente sua jogada, lê a opção do usuário e mostra o resultado:
# vitória do computador, vitória do usuário ou empate.
jogador = "a"
while jogador != "e":
print("P - PEDRA")
print("L - PAPEL")
print("T - TESOURA")
possiveis = []
possiveis.append({"id" : 0, "codigo" : "p" , "descricao" : "PEDRA"})
possiveis.append({"id" : 1, "codigo" : "l" , "descricao" : "PAPEL"})
possiveis.append({"id" : 2, "codigo" : "t" , "descricao" : "TESOURA"})
jogador = raw_input("JOGADA: ")
jogador = jogador.lower() #garantir que nao tem letra maiscula
computador = possiveis[random.randrange(0,2,1)]["id"]
resultado = joquempoResultado(jogador, computador)
ganhador = ""
if resultado == 0 : ganhador = "Jogador ganhou"
elif resultado == 1 : ganhador = "Computador ganhou"
else : ganhador = "Empate"
# mydict = {'george': 16, 'amber': 19}
# print(list (mydict.keys ( ))[ list (mydict.values ( )).index (16) ]) # Prints george
print(possiveis[0])
print("{} jogador: {} X {} computador".format(ganhador, jogador, computador))
def joquempoResultado(a, b): #returna 0 -> a ganhou, 1 -> b ganhou, -1 -> empate
if a == b : return -1
else:
if a == 'p' and b == 't': return 0
elif a == 'p' and b == 'l': return 1
elif a == 'l' and b == 't': return 1
elif a == 'l' and b == 'p': return 0
elif a == 't' and b == 'l': return 0
elif a == 't' and b == 'p': return 1
def alg6():
# O plano cartesiano está divido em quatro partes pelos eixos X (eixo das abcissas)e Y (eixo das ordenadas)
# chamadas de quadrantes. O quadrante superior da direita é o primeiro,
# o superior esquerdo é o segundo, o inferior esquerdo é o terceiro e o inferior direito é o quarto.
# Elabore um algoritmo que leia uma coordenada (x, y) do plano cartesiano e informe em qual quadrante
# este ponto se encontra.
ponto = raw_input("Digite o ponto (x, y): ")
valores = stringSeparetedBy(ponto, ",")
print("words: {}".format(valores))
x = float(valores[0])
y = float(valores[1])
if x == 0 : print("Sobre o eixo x")
elif y == 0 : print("Sobre o eixo y")
if x > 0 and y > 0 : print("Primeiro quadrante")
if x < 0 and y > 0 : print("Segundo quadrante")
if x < 0 and y < 0 : print("Terceiro quadrante")
if x > 0 and y < 0 : print("Quarto quadrante")
def stringSeparetedBy(text, separator):
words = []
cWord = ""
for char in text:
if char == separator:
words.append(cWord)
cWord = ""
else:
cWord += char
if cWord != "" : words.append(cWord)
return words
def alg7():
#Elabore um algoritmo que leia um número inteiro (n), e se este número atender a condição 1 ≤ n ≤ 99,
# mostre seu valor por extenso (exemplo: para n = 38, a saída será trinta e oito);
# caso contrário mostre “Entrada fora dos limites operacionais”.
n = input("Digite um número entre 0 e 99: ")
if n < 1 and n > 99 :
print("Fora dos limites operacionais")
return
text = strNumero(n)
print("{} = {}".format(n, text))
def strNumero(n):
if n < 1 and n > 99 :
print("Fora dos limites operacionais")
return ""
else:
if n < 10: return strUnidade(n)
elif n == 10 : return strDezena(n)
elif n < 20 : return strDezVinte(n)
else:
text = ""
d = round(n / 10)
text = strDezena(d)
u = n - d * 10
if u != 0 : text += " e " + strUnidade(u)
return text
def strUnidade(n):
if n == 1 : return "um"
elif n == 2 : return "dois"
elif n == 3 : return "tres"
elif n == 4 : return "quatro"
elif n == 5 : return "cinco"
elif n == 6 : return "seis"
elif n == 7 : return "sete"
elif n == 8 : return "oito"
elif n == 9 : return "nove"
def strDezena(n):
if n == 1 : return "dez"
elif n == 2 : return "vinte"
elif n == 3 : return "trinta"
elif n == 4 : return "quarenta"
elif n == 5 : return "cinquenta"
elif n == 6 : return "sessenta"
elif n == 7 : return "setenta"
elif n == 8 : return "oitenta"
elif n == 9 : return "noventa"
def strDezVinte(n):
if n == 11 : return "onze"
elif n == 12 : return "doze"
elif n == 13 : return "treze"
elif n == 14 : return "quatorze"
elif n == 15 : return "quinze"
elif n == 16 : return "dezesseis"
elif n == 17 : return "dezessete"
elif n == 18 : return "dezoito"
elif n == 19 : return "dezenove"
a = 0
while 0 <= a <= 7:
a = input ('Qual algoritmo voce deseja?: ')
if (a == 1) : alg1()
elif (a == 2) : alg2()
elif (a == 3) : alg3()
elif (a == 4) : alg4()
elif (a == 5) : alg5()
elif (a == 6) : alg6()
elif (a == 7) : alg7()
|
# coding=utf-8
import requests
import json
#Uma empresa de câmbio permite a compra de dólares, libras e euros.
# Elabore um algoritmo que leia o código da moeda que o cliente quer comprar e qual o
# montante que ele quer adquirir nessa moeda. Mostre então quanto ele deverá pagar em reais
# para concretizar a operação.
# Além da cotação, a empresa cobra uma comissão de 5% (quando o valor for menor que R$ 1.000),
# ou de 3% (quando maior ou igual a R$1.000).
#fiz de uma forma diferente, o app faz uma requisicao utilizando a api: https://www.exchangerate-api.com/app/dashboard
# inputMoeda = str(input("moeda\nUSD - Dolar\nGBP United Kingdom Pound\nEUR Euro Member Countries: "))
# primeiro puxa a cotacao de todos e mostra numa tabela
# Where USD is the base currency you want to use (i'm using BRL)
url = 'https://v3.exchangerate-api.com/bulk/4d52cef7ad4a863ae9e86e9e/BRL'
# Making our request
response = requests.get(url)
data = response.json()
# Your JSON object
# print data
# dumps the json object into an element
json_str = json.dumps (data)
# load the json to a string
resp = json.loads (json_str)
# print the resp
# print (resp)
rates = resp['rates']
print("Cotacao: BRL 1,00")
print("Data:")
print("resp: {}".format(resp))
for key in rates:
print("BRL 1,00 = {} {} ".format(key, rates[key]))
moeda = str(raw_input("moeda: ")).upper()
valor = input("valor a comprar ({}): ".format(moeda))
# extract an element in the response
cotacao = resp['rates'][moeda]
valorTransacao = valor / cotacao
# Além da cotação, a empresa cobra uma comissão de 5% (quando o valor for menor que R$ 1.000),
# ou de 3% (quando maior ou igual a R$1.000).
comissao = 0
if valorTransacao < 1000 : comissao = 0.05
else: comissao = 0.03
valorComissao = valorTransacao * comissao
valorTotal = valorTransacao + valorComissao
print("\n\n---------------------------------")
print("Cotacao: BRL 1,00 = {} {}".format(moeda, cotacao))
print("Valor da transacao: BRL {:.2f}".format(valorTransacao))
print("Valor da comissao: BRL {:.2f}".format(valorComissao))
print("Valor total: BRL {:.2f}".format(valorTotal))
print("---------------------------------\n\n")
|
from Tkinter import * #0
root=Tk() #1
root.title("demo") #2
l=Label(root, text="Hello World", width=20) #3
l.pack() #4
root.mainloop() #5
"""
Step 0 : Import classes from Tkinter module
Step 1 : Create a tk root widget. This is created in almost all programs. It acts
as a parent to all the widgets and is a simple window with a title bar.
Step 2 : Set the title.
Step 3 : Create a label using Label class with root as its parent widget.
Step 4 : Call the pack method on the widget which tells it to size itself to fit the given text and make itself visible.
Step 5 : Enter the Tkinter main loop.
http://www.linuxforu.com/2011/03/quickly-write-gui-using-python/
"""
|
ac=int(input("Dati anul curent:"))
bc=int(input("Dati luna curenta:"))
cc=int(input("Dati ziua curenta:"))
an=int(input("Dati anul nasterii:"))
bn=int(input("Dati luna nasterii:"))
cn=int(input("Dati ziua nasterii:"))
if bn>bc:
print((ac-an)-1,"ani")
elif(bn==bc):
if( cc==cn or cc>cn):
print(ac-an,"ani")
if(cc!=cn or cc<cn):
print((ac-an)-1,"ani")
else:
print(ac-an,"ani") |
a=int(input("Dati prima varsta:"))
b=int(input("Dati a doua varsta:"))
c=int(input("Dati a treia varsta:"))
if((a>18) and (a<60)):
print(a)
if((b>18) and (b<60)):
print(b)
if((c>18) and (c<60)):
print(c)
else:
print("Nimeni nu are varsta cuprinsa intre 18-60 ani") |
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
@app.route('/')
def index():
return "There's nothing here. Try '/hardcoded', '/first_template', or '/second_template/<name>'"
# Below you see an example of hardcoding: programming without the possibility
# of any variability. This HTML cannot be changed using Flask or anything else.
# Not very useful...
@app.route('/hardcoded/')
def hardcoded_index():
return '<html><body><h1>Hi, this is hardcoded HTML. BAD!</h1></body></html>'
# Instead, we can make use of templates. The .html files are in a subfolder "templates"
@app.route('/first_template')
def first_template():
return render_template('first_template.html')
@app.route('/second_template/')
def second_template_no_name():
return "No dummy, go to /second_template/some_name"
# To make use of the variables, let's use the second template:
@app.route('/second_template/<name>')
def second_template(name):
return render_template('second_template.html', name=name)
@app.route('/third_template/')
def third_template_no_number():
return "Enter a number after /third_template/"
# You can also use conditionals and other python code inside the template.
@app.route('/third_template/<int:number>')
@app.route('/third_template/<float:number>')
def third_template(number):
return render_template('third_template.html', number=number)
dict = {"Apple": "Red", "Pear": "Green", "Tomato": "Red Again"}
@app.route('/fourth_template/')
def fourth_template():
return render_template('fourth_template.html', dict=dict)
if __name__ == '__main__':
app.run(debug=True) |
#python3
from time import sleep
from random import choice
palavras = ['hello word','dinheiro','vida','complexidade','inferior','gta','comida']
pontos = 0
jogas = 0
while True:
jogas += 1
ale = choice(palavras)
print(20 * '-')
print(ale)
print(20 * '-')
pergunta = input('PALAVRA: ')
if pergunta == ale:
print('você acertou!')
pontos += 1
if pergunta != ale:
print('você errou!')
if jogas == 10:
pontos_perdidos = 10 - pontos
print(20 * '-')
print(f'você acertou {pontos} e errou {pontos_perdidos}')
break
|
import sqlite3
conn = sqlite3.connect('films.db')
c = conn.cursor()
def CREATE_TABLES():
c.executescript('''/* Delete the tables if they already exist */
drop table if exists Movie;
drop table if exists Reviewer;
drop table if exists Rating;
/* Create the schema for our tables */
create table Movie(mID int, title text, year int, director text);
create table Reviewer(rID int, name text);
create table Rating(rID int, mID int, stars int, ratingDate date);
/* Populate the tables with our data */
insert into Movie values(101, 'Gone with the Wind', 1939, 'Victor Fleming');
insert into Movie values(102, 'Star Wars', 1977, 'George Lucas');
insert into Movie values(103, 'The Sound of Music', 1965, 'Robert Wise');
insert into Movie values(104, 'E.T.', 1982, 'Steven Spielberg');
insert into Movie values(105, 'Titanic', 1997, 'James Cameron');
insert into Movie values(106, 'Snow White', 1937, null);
insert into Movie values(107, 'Avatar', 2009, 'James Cameron');
insert into Movie values(108, 'Raiders of the Lost Ark', 1981, 'Steven Spielberg');
insert into Reviewer values(201, 'Sarah Martinez');
insert into Reviewer values(202, 'Daniel Lewis');
insert into Reviewer values(203, 'Brittany Harris');
insert into Reviewer values(204, 'Mike Anderson');
insert into Reviewer values(205, 'Chris Jackson');
insert into Reviewer values(206, 'Elizabeth Thomas');
insert into Reviewer values(207, 'James Cameron');
insert into Reviewer values(208, 'Ashley White');
insert into Rating values(201, 101, 2, '2011-01-22');
insert into Rating values(201, 101, 4, '2011-01-27');
insert into Rating values(202, 106, 4, null);
insert into Rating values(203, 103, 2, '2011-01-20');
insert into Rating values(203, 108, 4, '2011-01-12');
insert into Rating values(203, 108, 2, '2011-01-30');
insert into Rating values(204, 101, 3, '2011-01-09');
insert into Rating values(205, 103, 3, '2011-01-27');
insert into Rating values(205, 104, 2, '2011-01-22');
insert into Rating values(205, 108, 4, null);
insert into Rating values(206, 107, 3, '2011-01-15');
insert into Rating values(206, 106, 5, '2011-01-19');
insert into Rating values(207, 107, 5, '2011-01-20');
insert into Rating values(208, 104, 3, '2011-01-02');''')
conn.commit()
CREATE_TABLES()
print ("1:")
for i in c.execute("SELECT title FROM Movie WHERE director='Steven Spielberg'"):
print (i)
print ("2:")
for i in c.execute("SELECT Reviewer.name FROM Reviewer, Rating, Movie WHERE Rating.rID = Reviewer.rID AND Rating.mID = Movie.mID AND Movie.title='Gone with the Wind'"):
print (i)
print ("3:")
s = 0
for i in c.execute("SELECT Rating.stars FROM Rating, Movie WHERE Rating.mID = Movie.mID AND Movie.title='Gone with the Wind'"):
s += i[0]
print (s)
print ("4:")
for i in c.execute("SELECT Rating.ratingDate FROM Rating WHERE Rating.stars > 3 ORDER BY Rating.ratingDate"):
print (i)
print ("5:")
c.execute("UPDATE Movie SET director='Shangul' WHERE Movie.title='Avatar'")
print ("6:")
c.execute("DELETE FROM Movie WHERE Movie.director='James Cameron'")
print ("7:")
temp = ""
ts = 0
ns = 0
for i in c.execute("SELECT Movie.title, Rating.stars FROM Movie, Rating WHERE Rating.mID = Movie.mID"):
if (temp != "" and temp != i[0]):
print (temp, ": Average Score:", float(ts)/ns)
ts = i[1]
ns = 1
temp = i[0]
elif (temp == ""):
temp = i[0]
ts = i[1]
ns = 1
else:
ts += i[1]
ns += 1
print (temp, ": Average Score:", float(ts)/ns)
|
import math
def dynamic(money,coins):
table=[] # table list for maintaining the results for reusing
newValue = money + 1
for x in range(newValue):
table.append(0) # appends 0 to table list
table[0] = [] # creates list at 0th index of table
for i in range(1, newValue):
for j in coins:
if j > i: continue # skip if coin value is greater than the amount of money
elif not table[i] or len(table[i - j]) + 1 < len(table[i]):
if table[i - j] != None:
table[i] = table[i - j][:] #calulate and store the result
table[i].append(j) #insert the coin value in the table
coin25 = 0
coin10 = 0
coin5 = 0
coin1 = 0
for i in range(len(table[-1])): # calculating number of each coins used
temp = table[-1]
if (temp[i] == 25):
coin25+=1
elif(temp[i] == 10):
coin10+=1
elif(temp[i] == 5):
coin5+=1
elif(temp[i] == 1):
coin1+=1
print "##########Dynamic#########" # printing details
print "Total Number of coins: " + str(len(table[-1]))
print "Number of $25 coins: "+ str(coin25)
print "Number of $10 coins: "+ str(coin10)
print "Number of $5 coins: "+ str(coin5)
print "Number of $1 coins: "+ str(coin1)
totalCoins = len(table[-1])
return totalCoins #return total coins required for the change
coins = [25,10,5,1] # denomination set
print dynamic(63,coins) #calling the function
|
# encoding UTF-8
# Autor: Jaime Orlando López Ramos, A01374696
# Descripción: Un programa que lea el radio de una esfera y calcue diámetro, área y volumen para luego imprimirlos
# Crear una función que calcule el diámetro tomando el radio como parámetro, multiplicando el radio por 2
def calcularDiametro(radio):
dm = 2 * radio
return dm
#Crear una función que calcule el área tomando el radio como parámetro. Usando la fórmula área = 4(pi)(radio)**2
def calcularArea(radio):
a = 4 * 3.1416 * (radio**2)
return a
# Crear una función que calcule el voumen, tomando el radio como parámetro.
# Usando la fórmula volumen = (4/3)(pi)(radio)**3
def calcularVolumen(radio):
v = (4/3)* 3.1416 * (radio**3)
return v
# Crear una función main que lea el radio de la esfera y posteriormente
# llame a las funciones previamente creadas para darle una variable a cada uno de los valores
# que las funciones regresaron, para así imprimir los datos requeridos
def main():
r= float(input("Introduzca el radio de la esfera: "))
dm = calcularDiametro(r)
a = calcularArea(r)
v = calcularVolumen(r)
print("Esfera con radio:", r)
print("Diámetro: %.2f" % (dm))
print("Área: %.2f" % (a))
print("Volumen: %.2f" % (v))
main() |
import numpy as np
import matplotlib.pyplot as plt
from util import get_data
X,Y = get_data()
label = ['Anger', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
def main():
while True:
for n in range(7):
x,y = X[Y==n],Y[Y==n]
N =len(y)
i = np.random.choice(N)
plt.imshow(x[i].reshape(48,48),cmap='gray')
plt.title(label[y[i]])
plt.show()
stop_choice = input('Quit or Comtinue? enter Q to quit \n')
if stop_choice.upper() == 'Q':
break
if __name__ == '__main__':
main() |
#In this game, we roll two dice and the player guesses whether the resulting number will be odd or even. For example, if the first die scores 1 and the second die scores 2, the total score is 3 (odd).
#import packages - random
import random
#create a list of possible numbers (let's make it two lists - imagine there are two dice)
#(possible refactor - even if I want to have two numbers, I don't really need two lists - I could just repeat a function for one list)
first_die = [1, 2, 3, 4, 5, 6]
second_die = [1, 2, 3, 4, 5, 6]
#create a function to roll the dice. this will include adding the result to the results list
#use random.choice() to select a single item from a list.
def roll_dice():
print("Here goes - the dice are rolling...")
odd_or_even_result = ""
result = 0
first_die_result = random.choice(first_die)
second_die_result = random.choice(second_die)
result += first_die_result + second_die_result
print("... The first die scores a {first}. And the second die scores a {second}.".format(first=first_die_result, second=second_die_result))
if result % 2 == 0:
odd_or_even_result += "even"
else:
odd_or_even_result += "odd"
return odd_or_even_result
#get the user to guess the outcome
def guess_the_outcome():
print("I'm going to roll two dice. Your task is to guess whether the total number showing on the two dice will be odd or even.")
guess = input("Do you think the dice will roll odds or even?: ").lower()
return guess
#play a round (combine roll dice and guess)
def play():
guess = guess_the_outcome()
outcome = roll_dice()
print("A reminder: you guessed {}.".format(guess))
print("And the outcome was ... {}.".format(outcome))
if guess == outcome:
print("You're a winner!")
else:
print("You lost.")
play()
|
# input
nums = [[1,2,3],[3,4,5]]
r = 3
c = 2
# algorithm
row = len(nums)
col = len(nums[0])
m = []
mat = []
if r*c != row*col:
print(nums)
else:
for i in range(row):
m += nums[i]
for i in range(r):
mat.append(m[c*i:c*i+c])
print(mat)
|
nums = [1,3,4,5]
target = 6
i,l = 0,len(nums)
# if target not in nums:
# i = 0 if target<nums[0] else l
# else:
# while target > nums[i]:
# i += 1
while i < l and target > nums[i]:
i += 1
print(i)
|
def repeat_until_valid(input_prompt, *valid_values, case_insensitive=True, output_change_case=True):
choice, raw_choice = '', ''
compare_values = valid_values
invalid_choice = True
if case_insensitive:
compare_values = {str(v).lower() for v in valid_values}
while invalid_choice:
raw_choice = input(input_prompt)
if case_insensitive:
choice = raw_choice.lower()
else:
choice = raw_choice
if choice not in compare_values:
print('"{}" is not a valid choice. Please choose one of {}'.format(raw_choice, list(valid_values)))
invalid_choice = True
else:
invalid_choice = False
if output_change_case:
return raw_choice.lower()
else:
return raw_choice
|
def shorten(package_name: str, max_length: int, level: int = 1) -> str:
"""
Shorten package name like Convention Word in logback - but in a simpler
version.
Eg: package.name.class.Function will be shorten to p.n.c.Function
@param package_name: name of package to shorten
@param max_length: max length of shortened name - shortened name will be
smaller or equal this value. If smaller - add space.
@param level: to use this function recursive, add level to travel over dots
>>> assert shorten("thit.cho.mam.tom", 9) == "t.c.m.tom"
>>> assert shorten("thit.cho.mam.tom", 11) == "t.c.mam.tom"
>>> assert shorten("thit.cho.mam.tom", 10) == "t.c.m.tom "
"""
package_len = len(package_name)
if package_len < max_length:
return package_name.ljust(max_length, " ")
elif package_len == max_length:
return package_name
dots = package_name.count(".")
if dots < level:
return package_name
names = package_name.split(".")
names[level-1] = names[level-1][0]
new_package_name = ".".join(names)
return shorten(new_package_name, max_length, level+1)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 08:21:14 2019
@author: rasik
"""
def findDuplicate(A):
arr = {}
for e in A:
if e not in arr:
arr[e]=1
else:
arr[e] = arr[e]+1
duplicates = []
for e in arr:
if arr[e]>1:
duplicates.append(e)
return duplicates
A= [2,2, 4, 5, 6,1,1]
print(findDuplicate(A)) |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 00:57:50 2019
@author: rasik
"""
"""
Given a length n, l, r of a string “lllmmmmmmrrr”, write a function to calculate the length m of middle sub-string
where n is the length of whole string, l is the length of left sub-string, r is the length of right sub-string
and l = r. (l+r=m, n=m+l+r)
"""
def findLengthOfM(Str,l):
ending = len(Str)-l
return Str[l:ending]
Str = "llmmmmrr"
l=2
print(findLengthOfM(Str,l)) |
currentYear = int(input("What year are we in now? "))
birthYear = int(input("Please enter the year in whitch you were born. "))
if birthYear > currentYear:
print("You are not yet born.")
exit(0)
if birthYear <= 1900:
print("That is too old!")
exit(0)
if (currentYear - birthYear) > 120:
print("You can not be that old.")
exit(0)
theYearIEntered = int(input("Please enter a year in the future. "))
if (theYearIEntered-birthYear) < 0:
print("That is impossible!.")
exit(0)
if birthYear == currentYear:
print("Congratulations on being born!!!")
if (currentYear - birthYear) == 100:
print("Congratulations on 100 years!!!")
if 13 <= (currentYear - birthYear) <=19:
print("Greeting teenager!")
decade = 10
while decade <= (currentYear - birthYear):
if (currentYear - birthYear) == decade:
print("Welcome to a new decade!!")
decade = decade + 10
age = (currentYear - birthYear)
if age > 1:
for i in range(2,age):
if (age % i) == 0:
print("Your age is not a prime number.")
break
else:
print("Your age is a prime number!")
strAge = str(age)
added = 0
for ch in strAge:
added = added + int(ch)
print("The numbers in your age added together is:",added)
print("Your age in", theYearIEntered, "Will be:", theYearIEntered - birthYear)
#Tasks for homework
# 1) What iff irs a new born baby? Greet him/her.
# 2) What if someone's age comes up as 100! congratulat him/her.
# 3) What if someone's age is between 13 and 19? Say hello to the teenager.
# 4) If the person is 10, 20, 30... invite them to a new decade
# 5) If the person's age is a prime number, tell them about it
# 6) Add up the digits in their birth year
|
#This is a variable.
radius = 5
#This is a constant
myConstPi = 3.14
print("The radius of the circle is", radius)
print("The circumference of a circle is :", 2*myConstPi*radius)
print("The circumference of crcle as an integer s:", int(2*myConstPi*radius))
|
"""
# 查看变量类型
A = 10
print(type(A))
B = "小明"
print(type(B))
# 怎一个爽字了得,根本不用可考虑类型的取值范围
C = 450000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
print(type(C))
print(type(2**32))
print(type(2**64))
print(C)
"""
"""
# python之间不同的数据类型如何进行计算
# 在python中只要是数字型变量就可以直接计算,
# 无论是什么类型的数字,也无论是哪种类型的算术 运算都可以
# bool类型的数字在参与运算的时候,如果保存的是true那就是1
# 否则的话,也就是false就当作0来运算
A = 10
B = 20.5
C = True
print(A+B+C)
"""
"""
# 字符串相拼接
B = "晨辉"
A= "董"
print(A+B)
# 使用乘号可以重复的拼接字符串
print(A*10)
# 除了上述的两种的字符串和数字的相关的操作之外,其他的字符串和数字的操作
# 都会是错误的
print(A+"10+20")
"""
"""
# 用户和操作系统进行交互,提醒用户输入内容
# input函数实现从键盘输入语句
# input函数得到的类型都是str(字符串类型的)
password = input("请输入银行密码:")
print("密码错误")
"""
"""
# 类型转换函数
# 将字符串类型转换成int和float类型
print(int("123"))
print(float("152.3"))
"""
"""
# 实现买苹果的案例
price_str = input("请输入苹果的价格:")
weight = input("请输入苹果的重量:")
# money = weight * price_str直接这样输出是错误的,因为我说过,input默认都是str类型,
# 在字符串的操作里面除了我之前提到的两个操作之外其他的操作都是非法的
# 所用应该先进行str到int的转换
print(int(price_str)*int(weight))
"""
"""
# 上面的代码使用了太多的变量,现在我们来做一个简化(但是尼玛这叫转换吗?眼睛都花了)
print((int(input("请输入苹果的单价:")))*int(int(input("请输入苹果的重量:"))))
"""
"""
# 变量的格式化输出
price = float(input("请输入单价:"))
weigh = float(input("请输入重量:"))
# 单纯的我以为这样就可以输出了,和C语言一样,万万没想到,吉多这大佬脑回路够清晰的
# print("苹果单价是%f元/斤,购买了%f斤,需要支付%f元",price,weigh,price*weigh)
# 原来要这样写,不禁感叹大佬就是脑回路清晰
print("苹果单价是%.2f元/斤,购买了%.2f斤,需要支付%.2f元"% (price, weigh, price*weigh))
"""
"""
# 定义一个小数,scale,输出数据比例是10.00%
scale = 0.1
print("数据的比例是%.2f%%" % (scale*100))
"""
"""
# 通过下面的命令查看python中的关键字
import keyword
print(keyword.kwlist)
"""
"""
# 判断语句
age = int(input("请输入你的年龄")) # 这里要先记得把输入的str类型转换成int类型
if age < 18:
print("你太小了不能进网吧嗨皮")
else:
print("你可以开始嗨皮了")
"""
"""
# 逻辑运算演练
# 下面进行的是多次判断是否年龄合适
# 注意这里使用的不是else if 而是elif
age = int(input("请输入你的年龄"))
if age <18: #if语句这里的()是可以加也是可以不加的
print("不允许进入网吧,你年龄太小了")
elif age <50:
print("欢迎进入网吧嗨皮")
else:
print("你年纪太大了容易嗨死,请不要进入网吧")
"""
"""
# if的嵌套
# 火车站安检
print("请问你是否打算回家?\n"
"1.不回家\n"
"2.回家")
chose_1 = int(input())
if chose_1 == 1:
print("不回家你选个毛线,滚!!!")
else:
print("这位爷,这边走")
print("请选择你是否准备购买车票?\n"
"1.没钱不买\n"
"2.乞讨车费")
chose_2 = int(input())
if chose_2 == 1:
print("没钱回个屁,赶紧滚!!!")
else:
print("来你先进门,检查一下有没有危险品")
print("有没有带刀?\n"
"1.没有带\n"
"2.带刀了")
chose_3 = int(input())
if chose_3 == 1:
print("好孩子,你可以上车回家了")
else:
print("你先过来,先扇你一巴掌,谁让你带刀了,教育半小时")
print("带了多大的刀?\n"
"1.小于20cm\n"
"2.大于20cm")
chose_4 = int(input())
if chose_4 == 1:
print("算了,刀也不长,赶紧滚上车")
else:
print("你带了20m的大砍刀你还想回家,憨批。赶紧滚下车")
"""
|
def longest_pallindrome(s):
if s == s[::-1]:
return len(s), s
else:
if len(s) > 2:
left = longest_pallindrome(s[:-1])
right = longest_pallindrome(s[1:])
if left[0] > right[0]:
return left
else:
return right
else:
return [0,0]
# s = "asdfghjklqwekasdfghjklkjhgfdsaqweewq"
# s = "asaabcd"
s = "babkanakbc"
test = longest_pallindrome(s)
print(test)
|
import random
print('I am thinking of a 3-digit number. Try to guess what it is.\n\
Here are some clues:\n\
When I say: That means:\n\
Cold No digit is correct.\n\
Warm One digit is correct but in the wrong position.\n\
Hot One digit is correct and in the right position.\n\
I have thought up a number. You have 10 guesses to get it.')
random_digit = str(random.choice(range(100, 1000)))
# print(random_digit)
tries = 1
digit_input = input("Guess digit: ")
while digit_input != random_digit:
print('Guess #', tries)
if tries == 1:
pass
else:
digit_input = input("Guess digit: ")
list_random = [random_digit[0], random_digit[1], random_digit[2]]
list_input = [digit_input[0], digit_input[1], digit_input[2]]
index_of_hot = []
count_hot = 0
count_warm = 0
count_cold = 0
for i in range(len(list_input)):
if list_input[i] == list_random[i]:
count_hot += 1
index_of_hot.append(i)
list_to_check_warm = [0, 1, 2]
for i in range(len(index_of_hot)):
list_to_check_warm.remove(index_of_hot[i])
for i in list_to_check_warm:
if list_input[i] in list_random:
count_warm += 1
else:
count_cold += 1
if count_cold == 3:
print("Cold")
else:
print("Hot " * count_hot, "Warm " * count_warm)
tries += 1
print('You got it!')
|
import pygame;
import random;
class Point():
def __init__(self, x, y):
self.x = x;
self.y = y;
def x(self):
return self.x;
def y(self):
return self.y;
class maze(pygame.sprite.Sprite):
size = 1;
def __init__(self):
print("Maze Being Generated");
def generate(self, w, h, m):
body = [];
body.append(Point(0 + m, 0 + m));
body.append(Point(w - 2*m, h - 2*m));
#for
return body;
|
from bintreeFile import Bintree
def makeTree():
tree = Bintree()
data = input().strip()
while data != "#":
tree.put(data)
data = input().strip()
return tree
def searches(tree):
findme = input().strip()
while findme != "#":
if findme in tree:
print(findme, "found")
else:
print(findme, "not found")
findme = input().strip()
def main():
tree = makeTree()
searches(tree)
main()
|
#A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(num):
num_d = []
while num != 0:
num_d.append(num%10)
num = num // 10
num_d.reverse()
#print num_d
for i in range(len(num_d)):
if num_d[i] != num_d[-i-1]:
#print num_d[i], num_d[-i-1]
return False
return True
max_pal = 100
num1 = range(100, 1000)
num2 = range(100, 1000)
for n1 in num1:
for n2 in num2:
if is_palindrome(n1*n2):
if max_pal < n1*n2:
max_pal = n1*n2
print (max_pal)
|
##For a positive integer n and digits d, we define F(n, d) as the number of the divisors of n whose last digits equal d.
##For example, F(84, 4) = 3. Among the divisors of 84 (1, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84), three of them (4, 14, 84) have the last digit 4.
##
##We can also verify that F(12!, 12) = 11 and F(50!, 123) = 17888.
##
##Find F(106!, 65432) modulo (1016 + 61).
def fact(x):
if x==1:
return 1
else:
return x * fact(x-1)
def is_prime(num):
if num <= 3:
if num <= 1:
return False
return True
if not num%2 or not num%3:
return False
for i in range(5, int(num**0.5) + 1, 6):
if not num%i or not num%(i + 2):
return False
return True
def num_digits(num):
count = 0
while num != 0:
num = num//(10)
count += 1
return count
def F(num, digit):
result = []
if num == 1:
return result
if digit == 1:
result = [1]
div = 10 ** num_digits(digit)
flag = True
i = 2
min = 0
if not is_prime(num):
while (flag):
if num%i == 0:
min = i
flag = False
if i % div == digit:
result.append(i)
i += 1
for j in range(i, num//(min) + 1):
if not num%j:
if j % div == digit:
result.append(j)
if num % div == digit:
result.append(num)
return result
import math
print (len((F(math.factorial(50), 123))))
|
print('Введіть дату в форматі: ХХ.ХХ.XXXX:\n')
day, month, year = map(int, input().split('.'))
a = ((14 - month) / 12)
y = year - int(a)
m = month + 12*int(a) - 2
day_number = (day + int(y) + int(y/4) - int(y/100) + int(y/400) + int((31*m) /12)) % 7
if day_number == 0:
day_name = "Sunday"
elif day_number == 1:
day_name = "Monday"
elif day_number == 2:
day_name = "Tuesday"
elif day_number == 3:
day_name = "Wednesday"
elif day_number == 4:
day_name = "Thursday"
elif day_number == 5:
day_name = "Friday"
elif day_number == 6:
day_name = "Saturday"
print(day_name)
|
from IPython.display import clear_output
class ROIcalc():
def __init__(self):
self.income = []
self.expenses = []
self.investment = []
self.proplist = []
self.totalincome = {}
self.totalexpenses = {}
self.totalinvestment = {}
self.ROI = {}
def prop_name(self):
property_name = input("What name would you like to refer to this property as? ")
if property_name in self.proplist:
print(f"There is already a property with that name. Please try using a different name.")
self.prop_name()
else:
self.proplist.append(property_name)
self.totalincome[property_name] = 0
self.totalexpenses[property_name] = 0
self.totalinvestment[property_name] = 0
self.ROI[property_name] = 0
def rent_income(self):
rent = input("How much do you charge for rent? ")
try:
rent = int(rent)
self.income.append(rent)
except:
print(f"Error. Please enter a number. ")
self.rent_income()
def extra_income(self):
extra = input("As this is a commercial rental, please add any additional monthly income that you expect to earn: ")
try:
extra = int(extra)
self.income.append(extra)
except:
print(f"Error. Please enter a number. ")
self.extra_income()
def total_income(self):
fullincome = sum(self.income)
for key, value in self.totalincome.items():
if value == 0:
self.totalincome[key] = fullincome
def tax_exp(self):
taxes = input("How much are the taxes? ")
try:
taxes = int(taxes)
self.expenses.append(taxes)
except:
print(f"Error. Please enter a number. ")
self.tax_exp()
def ins_exp(self):
insurance = input("How much is the insurance? ")
try:
insurance = int(insurance)
self.expenses.append(insurance)
except:
print(f"Error. Please enter a number. ")
self.ins_exp()
def utilities_exp(self):
water = input("How much is the water? ")
try:
water = int(water)
self.expenses.append(water)
except:
print(f"Error. Please enter a number. ")
self.utilities_exp()
garbage = input("How much is trash pickup? ")
try:
garbage = int(garbage)
self.expenses.append(garbage)
except:
print(f"Error. Please enter a number. ")
self.utilities_exp()
electric = input("How much is the electric? ")
try:
electric = int(electric)
self.expenses.append(electric)
except:
print(f"Error. Please enter a number. ")
self.utilities_exp()
gas = input("How much is the gas? ")
try:
gas = int(gas)
self.expenses.append(gas)
except:
print(f"Error. Please enter a number. ")
self.utilities_exp()
def HOA_exp(self):
HOA = input("How much are the HOA fees? ")
try:
HOA = int(HOA)
self.expenses.append(HOA)
except:
print(f"Error. Please enter a number. ")
self.HOA_exp()
def yard_exp(self):
yard = input("How much are your landscaping fees? ")
try:
yard = int(yard)
self.expenses.append(yard)
except:
print(f"Error. Please enter a number. ")
self.yard_exp()
def vacancy_exp(self):
vacancy = input("How much are you setting aside in case of a vacancy? ")
try:
vacancy = int(vacancy)
self.expenses.append(vacancy)
except:
print(f"Error. Please enter a number. ")
self.vacancy_exp()
def repair_exp(self):
repair = input("How much are you setting aside for repairs? ")
try:
repair = int(repair)
self.expenses.append(repair)
except:
print(f"Error. Please enter a number. ")
self.repair_exp()
def capex_exp(self):
capex = input("How much are you setting aside for capital expenditures? ")
try:
capex = int(capex)
self.expenses.append(capex)
except:
print(f"Error. Please enter a number. ")
self.capex_exp()
def manage_exp(self):
manage = input("How much are you paying for property management? ")
try:
manage = int(manage)
self.expenses.append(manage)
except:
print(f"Error. Please enter a number. ")
self.manage_exp()
def mortgage_exp(self):
mortgage = input("How much is the mortgage? ")
try:
mortgage = int(mortgage)
self.expenses.append(mortgage)
except:
print(f"Error. Please enter a number. ")
self.mortgage_exp()
def down_payment(self):
downpayment = input("How much was your down payment on the property? ")
try:
downpayment = int(downpayment)
self.investment.append(downpayment)
except:
print(f"Error. Please enter a number. ")
self.down_payment()
def closing_costs(self):
closingcosts = input("How much did you pay in closing costs? ")
try:
closingcosts = int(closingcosts)
self.investment.append(closingcosts)
except:
print(f"Error. Please enter a number. ")
self.closing_costs()
def reno_costs(self):
renovations = input("How much did you spend on renovations? ")
try:
renovations = int(renovations)
self.investment.append(renovations)
except:
print(f"Error. Please enter a number. ")
self.reno_costs()
def total_expenses(self):
fullexpense = sum(self.expenses)
for key, value in self.totalexpenses.items():
if value == 0:
self.totalexpenses[key] = fullexpense
def total_investments(self):
fullinvestment = sum(self.investment)
for key, value in self.totalinvestment.items():
if value == 0:
self.totalinvestment[key] = fullinvestment
def roi_calc(self):
cashflow = ((sum(self.income)) - (sum(self.expenses))) * 12
roi = round(((cashflow / (sum(self.investment))) * 100), 2)
for key, value in self.ROI.items():
if value == 0:
self.ROI[key] = roi
print(f"This property's ROI is: {roi}%.")
self.income.clear()
self.expenses.clear()
self.investment.clear()
def prev_property(self):
which_prop = input("Please type your property name to view your data: ")
if which_prop.lower() in self.ROI:
print(self.totalincome[which_prop])
print(self.totalexpenses[which_prop])
print(self.totalinvestment[which_prop])
print(self.ROI[which_prop])
else:
print(f"Error. Please try again.")
self.prev_property()
def prop_list(self):
print(self.proplist)
test = ROIcalc()
def runROI():
print(f"Hello and welcome to our ROI calculator!")
while True:
response = input("Would you like to calculate your ROI or look up a previous properties values? (Please input 'Calculate' or 'Previous Property') ")
if response.lower() == 'calculate':
clear_output()
test.prop_name()
prop_type = input("Is this a 'residential' or 'commercial' property? ")
if prop_type.lower() == 'residential':
test.rent_income()
test.total_income()
test.tax_exp()
test.ins_exp()
test.HOA_exp()
test.yard_exp()
test.vacancy_exp()
test.repair_exp()
test.capex_exp()
test.manage_exp()
test.mortgage_exp()
test.down_payment()
test.closing_costs()
test.reno_costs()
test.total_expenses()
test.total_investments()
test.roi_calc()
elif prop_type.lower() == 'commercial':
test.rent_income()
test.extra_income()
test.total_income()
test.tax_exp()
test.ins_exp()
test.utilities_exp()
test.HOA_exp()
test.yard_exp()
test.vacancy_exp()
test.repair_exp()
test.capex_exp()
test.manage_exp()
test.mortgage_exp()
test.down_payment()
test.closing_costs()
test.reno_costs()
test.total_expenses()
test.total_investments()
test.roi_calc()
else:
print(f"Error. Please try again.")
elif response.lower() == 'previous property':
clear_output()
test.prop_list()
test.prev_property()
else:
print(f"Error. Please try again.")
runROI() |
import datetime
import random
class Cache:
def __init__(self):
# Constructor
self.cache = {}
self.MaxSize = 5
def empty(self):
return self.cache == {}
def size(self):
return len(self.cache)
def __contains__(self, key):
return key in self.cache
def view(self):
return self.cache
# Update cache and remove oldest item, when size reaches maximum
def update(self, value):
if (len(self.cache) == self.MaxSize):
freed_key = self.delete() # remove element with LRU
# add once freed up some space
self.cache[freed_key] = {'time added': datetime.datetime.now().isoformat(), 'value': value}
else: # adds while there is free space
self.cache[self.size()] = {'time added': datetime.datetime.now().isoformat(), 'value': value}
def delete(self):
# Find and Remove oldest item from cache based on "time added" parameter
old_entry = None
for key in self.cache:
if old_entry is None:
old_entry = key
elif self.cache[key]['time added'] < self.cache[old_entry]['time added']:
old_entry = key
print('Removed Element:\t' + str(self.cache[old_entry]))
self.cache.pop(old_entry)
return old_entry
def start_cache(self):
# Test the cache
Keys = [i for i in range(5)] # Total Space in cache
sites = ['str1 ', 'str2', 'str3', 'str4', 'str5', 'str6', 'str7', 'str8', 'str9', 'str10']
# Cache object
cache = Cache()
# Updating Cache with entries
for i in range(20):
print("Iteration: {0}".format(i + 1))
value = ''.join([random.choice(sites)]) # randomly add a new value to the cache
print('Added Element:\t' + value)
cache.update(value)
print("# Cached Entries: {0}\n".format(cache.size()))
# Cache List
print('\n\n\t\t', '*' * 10, ' CACHE LIST ', '*' * 10)
for k, v in cache.view().items():
print("Index {0} : {1}".format(k, v))
LRU_cache = Cache
Cache.start_cache(LRU_cache)
|
user = int(input("Choose one level for the game:"))
while user == 1:
if user == 1:
import random
numero = random.randint(0,100)
print(numero)
print("Choose an integer between 0 and 99")
intento_1 = int(input()) |
# -*- coding: utf-8 -*-
class Vehicle(object):
def __init__(self, vehicle_brand, vehicle_model, number_of_kilometers, date_service):
self.vehicle_brand = vehicle_brand
self.vehicle_model = vehicle_model
self.number_of_kilometers = number_of_kilometers
self.date_service = date_service
def get_vehicle_full_name(self):
return self.vehicle_brand + " " + self.vehicle_model
def add_new_vehicle(vehicles):
vehicle_brand = raw_input("Vpišite znamko vozila: ")
vehicle_model = raw_input("Vpišite model vozila: ")
number_of_kilometers = raw_input("Vpištite prevožene kilometre: ")
date_service = raw_input("Vpišite datum servisa: ")
new_vehicle = Vehicle(vehicle_brand=vehicle_brand, vehicle_model=vehicle_model, number_of_kilometers=number_of_kilometers, date_service=date_service)
vehicles.append(new_vehicle)
print "Vozilo " + vehicle_brand + " ste uspešno dodali na vaš seznam."
def list_all_vehicles(vehicles):
for key, vehicle in enumerate(vehicles):
print "Znamka vozila: " + vehicle.vehicle_brand
print "Model vozila: " + vehicle.vehicle_model
print "Prevoženi kilometri: " + vehicle.number_of_kilometers
print "Datum servisa: " + vehicle.date_service
print ""
if not vehicles:
print "Nimate vozil v vašem seznamu"
print ""
def edit_number_of_kilometers_or_date_service(vehicles):
while True:
print "Kaj želite urediti?"
print "a) Število kilometrov"
print "b) Datum servisa"
print "c) Izhod iz urejevalnika"
selection = raw_input("Izberite opcijo (a, b ali c): ")
if selection.lower() == "a":
for index, vehicle in enumerate(vehicles):
print "ID: " + str(index) + " - " + vehicle.get_vehicle_full_name()
print ""
selected_vehicle_id = raw_input("Vpišite ID vozila: ")
selected_vehicle = vehicles[int(selected_vehicle_id)]
print ""
new_number_of_kilometers = raw_input("Vnesite novo število kilometrov %s: " % selected_vehicle.get_vehicle_full_name())
selected_vehicle.number_of_kilometers = new_number_of_kilometers
print ""
print "Uspešno posodobljeno!"
if selection.lower() == "b":
for index, vehicle in enumerate(vehicles):
print "ID: " + str(index) + " - " + vehicle.get_vehicle_full_name()
print ""
selected_vehicle_id = raw_input("Vpišite ID vozila: ")
selected_vehicle = vehicles[int(selected_vehicle_id)]
print ""
new_date_service = raw_input("Vnesite novo število kilometrov %s: " % selected_vehicle.get_vehicle_full_name())
selected_vehicle.date_service = new_date_service
print ""
print "Uspešno posodobljeno!"
elif selection.lower() == "c":
break
else:
continue
def delete_vehicle(vehicles):
print "Izberite ID vozila ki ga želite izbrisati:"
for index, vehicle in enumerate(vehicles):
print "ID: " + str(index) + " - " + vehicle.get_vehicle_full_name()
print ""
selected_vehicle_id = raw_input("Vpišite ID vozila: ")
selected_vehicle = vehicles[int(selected_vehicle_id)]
vehicles.remove(selected_vehicle)
print ""
print "Avtomobil uspešno izbrisan!"
vehicles = []
def save_vehicles_in_txt(vehicles):
text_file = open("vehicles.txt", "w+")
for vehicle in vehicles:
text_file.write("Znamka: " + vehicle.vehicle_brand + "\n")
text_file.write("Model: " + vehicle.vehicle_model + "\n")
text_file.write("Število prevoženih kilometrov: " + vehicle.number_of_kilometers + "\n")
text_file.write("Datum servisa: " + vehicle.date_service + "\n")
text_file.write("\n")
text_file.close()
print "Uspešno shranjeno!" |
def subtotal_calc(c_price, a_price, t_childrem, t_adults):
return (c_price * t_childrem) + (a_price * t_adults)
def sales_tax_calc(subtotal, tax):
return (subtotal * tax) / 100
def total_calc(subtotal, sales_tax):
return subtotal + sales_tax
def change_calc(payment_amout, total):
return payment_amout - total
def request_payment_amout():
return float(input('\nWhat is the payment amount? '))
childs_price = float(input('What is the price of a child\'s meal? '))
adults_price = float(input('What is the price of an adult\'s meal? '))
total_of_children = int(input('How many children are there? '))
total_of_adults = int(input('How many adults are there? '))
tax_rate = float(input('What is the sales tax rate? '))
subtotal = subtotal_calc(childs_price, adults_price,
total_of_children, total_of_adults)
sales_tax = sales_tax_calc(subtotal, tax_rate)
total = total_calc(subtotal, sales_tax)
print(f'\nSubtotal: ${subtotal:.2f}')
print(f'Sales Tax: ${sales_tax:.2f}')
print(f'Total: ${total:.2f}')
payment_amout = request_payment_amout()
if (payment_amout < total):
print('\nthe payment amount cannot be less than the total, please provide a valid value')
payment_amout = request_payment_amout()
change = change_calc(payment_amout, total)
print(f'Change: ${change:.2f}')
|
print('Please enter the following:\n')
# inputs
adjective = input('adjective: ')
animal = input('animal: ')
verb_1 = input('verb: ')
exclamation = input('exclamation: ')
verb_2 = input('verb: ')
verb_3 = input('verb: ')
# preparing the story
finalStyory = f'The other day, I was really in trouble. It all started when I saw a very {adjective} {animal} {verb_1} down the hallway. "{exclamation}!" I yelled. But all I could think to do was to {verb_2} over and over. Miraculously, that caused it to stop, but not before it tried to {verb_3} right in front of my family.'
# output
print('Your story is:\n')
print(finalStyory)
|
import random
number = random.randint(1, 100)
user_input = -1
while number != user_input:
user_input = int(input('What is your guess? '))
if (user_input < number):
print('Higher')
else:
print('Lower')
print('You guessed it!') |
def convertToPigLatin(inputString):
# inputString = [[j for j in i] for i in inputString.split(" ") ]
# print(inputString)
# seperate into words
inputString = inputString.split(" ")
# Move initial consonants to end
for index, word in enumerate(inputString):
for i in word:
if i.lower() in ["a","e","i","o","u"]:
break
else:
word = inputString[index] = word[1:]+i.lower()
# print("Word: "+word)
# Add suffix
inputString[index] = word+ "ay"
print(" ".join(inputString))
# print(inputString)
convertToPigLatin(input("Phrase to covert: ")) |
# 6.00 Problem Set 4
#
# Caesar Cipher Skeleton
#
import string
import random
WORDLIST_FILENAME = "/Users/macbookpro/Documents/CS/CS600/hw/ps4/words.txt"
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
wordlist = load_words()
def is_word(wordlist, word):
"""
Determines if word is a valid word.
wordlist: list of words in the dictionary.
word: a possible word.
returns True if word is in wordlist.
Example:
>>> is_word(wordlist, 'bat') returns
True
>>> is_word(wordlist, 'asdf') returns
False
"""
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in wordlist
def random_word(wordlist):
"""
Returns a random word.
wordlist: list of words
returns: a word from wordlist at random
"""
return random.choice(wordlist)
def random_string(wordlist, n):
"""
Returns a string containing n random words from wordlist
wordlist: list of words
returns: a string of random words separated by spaces.
"""
return " ".join([random_word(wordlist) for _ in range(n)])
def random_scrambled(wordlist, n):
"""
Generates a test string by generating an n-word random string
and encrypting it with a sequence of random shifts.
wordlist: list of words
n: number of random words to generate and scamble
returns: a scrambled string of n random words
NOTE:
This function will ONLY work once you have completed your
implementation of apply_shifts!
"""
s = random_string(wordlist, n) + " "
shifts = [(i, random.randint(0, 26)) for i in range(len(s)) if s[i-1] == ' ']
return apply_shifts(s, shifts)[:-1]
def get_fable_string():
"""
Returns a fable in encrypted text.
"""
f = open("fable.txt", "r")
fable = str(f.read())
f.close()
return fable
# (end of helper code)
# -----------------------------------
#
# Problem 1: Encryption
#
def build_coder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation and numbers.
shift: -27 < int < 27
returns: dict
Example:
>>> build_coder(3)
{' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J',
'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O',
'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X',
'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd',
'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l',
'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q',
'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z',
'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'}
(The order of the key-value pairs may be different.)
"""
### TODO.
def build_encoder(shift):
"""
Returns a dict that can be used to encode a plain text. For example, you
could encrypt the plain text by calling the following commands
>>>encoder = build_encoder(shift)
>>>encrypted_text = apply_coder(plain_text, encoder)
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation and numbers.
shift: 0 <= int < 27
returns: dict
Example:
>>> build_encoder(3)
{' ': 'c', 'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G', 'G': 'J',
'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M': 'P', 'L': 'O',
'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V', 'R': 'U', 'U': 'X',
'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'A', 'X': ' ', 'Z': 'B', 'a': 'd',
'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g', 'g': 'j', 'f': 'i', 'i': 'l',
'h': 'k', 'k': 'n', 'j': 'm', 'm': 'p', 'l': 'o', 'o': 'r', 'n': 'q',
'q': 't', 'p': 's', 's': 'v', 'r': 'u', 'u': 'x', 't': 'w', 'w': 'z',
'v': 'y', 'y': 'a', 'x': ' ', 'z': 'b'}
(The order of the key-value pairs may be different.)
HINT : Use build_coder.
"""
### TODO.
def build_decoder(shift):
"""
Returns a dict that can be used to decode an encrypted text. For example, you
could decrypt an encrypted text by calling the following commands
>>>encoder = build_encoder(shift)
>>>encrypted_text = apply_coder(plain_text, encoder)
>>>decrypted_text = apply_coder(plain_text, decoder)
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation and numbers.
shift: 0 <= int < 27
returns: dict
Example:
>>> build_decoder(3)
{' ': 'x', 'A': 'Y', 'C': ' ', 'B': 'Z', 'E': 'B', 'D': 'A', 'G': 'D',
'F': 'C', 'I': 'F', 'H': 'E', 'K': 'H', 'J': 'G', 'M': 'J', 'L': 'I',
'O': 'L', 'N': 'K', 'Q': 'N', 'P': 'M', 'S': 'P', 'R': 'O', 'U': 'R',
'T': 'Q', 'W': 'T', 'V': 'S', 'Y': 'V', 'X': 'U', 'Z': 'W', 'a': 'y',
'c': ' ', 'b': 'z', 'e': 'b', 'd': 'a', 'g': 'd', 'f': 'c', 'i': 'f',
'h': 'e', 'k': 'h', 'j': 'g', 'm': 'j', 'l': 'i', 'o': 'l', 'n': 'k',
'q': 'n', 'p': 'm', 's': 'p', 'r': 'o', 'u': 'r', 't': 'q', 'w': 't',
'v': 's', 'y': 'v', 'x': 'u', 'z': 'w'}
(The order of the key-value pairs may be different.)
HINT : Use build_coder.
"""
### TODO.
def apply_coder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
Example:
>>> apply_coder("Hello, world!", build_encoder(3))
'Khoor,czruog!'
>>> apply_coder("Khoor,czruog!", build_decoder(3))
'Hello, world!'
"""
### TODO.
def apply_shift(text, shift):
"""
Given a text, returns a new text Caesar shifted by the given shift
offset. The empty space counts as the 27th letter of the alphabet,
so spaces should be replaced by a lowercase letter as appropriate.
Otherwise, lower case letters should remain lower case, upper case
letters should remain upper case, and all other punctuation should
stay as it is.
text: string to apply the shift to
shift: amount to shift the text
returns: text after being shifted by specified amount.
Example:
>>> apply_shift('This is a test.', 8)
'Apq hq hiham a.'
"""
### TODO.
#
# Problem 2: Codebreaking.
#
def find_best_shift(wordlist, text):
"""
Decrypts the encoded text and returns the plaintext.
text: string
returns: 0 <= int 27
Example:
>>> s = apply_coder('Hello, world!', build_encoder(8))
>>> s
'Pmttw,hdwztl!'
>>> find_best_shift(wordlist, s) returns
8
>>> apply_coder(s, build_decoder(8)) returns
'Hello, world!'
"""
### TODO
#
# Problem 3: Multi-level encryption.
#
def apply_shifts(text, shifts):
"""
Applies a sequence of shifts to an input text.
text: A string to apply the Ceasar shifts to
shifts: A list of tuples containing the location each shift should
begin and the shift offset. Each tuple is of the form (location,
shift) The shifts are layered: each one is applied from its
starting position all the way through the end of the string.
returns: text after applying the shifts to the appropriate
positions
Example:
>>> apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)])
'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?'
"""
### TODO.
#
# Problem 4: Multi-level decryption.
#
def find_best_shifts(wordlist, text):
"""
Given a scrambled string, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: Make use of the recursive function
find_best_shifts_rec(wordlist, text, start)
wordlist: list of words
text: scambled text to try to find the words for
returns: list of tuples. each tuple is (position in text, amount of shift)
Examples:
>>> s = random_scrambled(wordlist, 3)
>>> s
'eqorqukvqtbmultiform wyy ion'
>>> shifts = find_best_shifts(wordlist, s)
>>> shifts
[(0, 25), (11, 2), (21, 5)]
>>> apply_shifts(s, shifts)
'compositor multiform accents'
>>> s = apply_shifts("Do Androids Dream of Electric Sheep?", [(0,6), (3, 18), (12, 16)])
>>> s
'JufYkaolfapxQdrnzmasmRyrpfdvpmEurrb?'
>>> shifts = find_best_shifts(wordlist, s)
>>> print apply_shifts(s, shifts)
Do Androids Dream of Electric Sheep?
"""
def find_best_shifts_rec(wordlist, text, start):
"""
Given a scrambled string and a starting position from which
to decode, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: You will find this function much easier to implement
if you use recursion.
wordlist: list of words
text: scambled text to try to find the words for
start: where to start looking at shifts
returns: list of tuples. each tuple is (position in text, amount of shift)
"""
### TODO.
def decrypt_fable():
"""
Using the methods you created in this problem set,
decrypt the fable given by the function get_fable_string().
Once you decrypt the message, be sure to include as a comment
at the end of this problem set how the fable relates to your
education at MIT.
returns: string - fable in plain text
"""
### TODO.
#What is the moral of the story?
#
#
#
#
#
|
# Question 11
# Level 2
#
# Question:
# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# Example:
# 0100,0011,1010,1001
# Then the output should be:
# 1010
# Notes: Assume the data is input by console.
#
# Hints:
# In case of input data being supplied to the question, it should be assumed to be a console input.
string = input().split(",")
p =[]
for i in string:
if int(i,2)%5==0:
p.append(i)
print(",".join(p))
|
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head, k) -> ListNode:
if not head:
return None
if not head.next:
return head
p = head
n = 1
while p.next:
n += 1
p = p.next
p.next = head
new_tail = head
for i in range(n-k%n-1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_head
l1 = ListNode(1)
l2 = ListNode(2);l1.next = l2
l3= ListNode(3); l2.next = l3
l4 = ListNode(4);l3.next = l4
p = l1
while p:
print(p.val)
p = p.next
sol = Solution()
head = sol.rotateRight(l1,2)
while head:
print(head.val)
head = head.next
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.