text
stringlengths
37
1.41M
''' completeWord function --- takes 2 inputs --- ''' # completeWord function def completeWord(aString, aList): for each in aList: if len(aString) == len(each): print "Before: " + aString + " After: " + each # calling function completeWord("h.llo", ["hello", "halo", "cat"]) completeWord("l.d.a", ["lydia", ...
import numpy as np def sample_equal_proportion(y, proportion=0.667, random_state=None): """Sample in equal proportion. Sample in equal proportion. Parameters ---------- y : array, shape (n_obs) Input data to be split proportion : float, default: 0.667 Proportion to split into t...
#!/usr/bin/python import sys key = None currentKey = None currentCount = 0 # The reducer receives its input (through STDIN) from the mapper output for line in sys.stdin: # Trim whitespaces line = line.strip() key, count = line.split('\t', 1) try: count = int(count) except ValueError: continue ...
from moveSortHandler import MoveSortHandler class SearchHandler: """ MiniMax search algorithm with alpha-beta pruning. """ def __init__(self,board,broadth=None): self._board = board self._moveSortHandler = MoveSortHandler(board,broadth) return def getBestMove(self,depth=4):...
#!/usr/bin/env python import first laugh_test = first.Person() for i in range(3): laugh_test.laugh() def square_sum(a, b): c = a**2 + b**2 return a,b,c def int_inc(b): b[0] = b[0] + 1 return b def leap_year(year): if year%400 == 0 or (year%100 != 0 and year%4 == 0): print "%d is leap...
#Bokai Chen #The program uses MAX MIN heap to find the median of the array. #additional number can be added repetitively after initial array is created #input format is 1,2,3,4 #note: if size of input is even, the middle 2 numbers are averaged import heapq import numpy as np import statistics def randarr(): """g...
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys, math combination=0 atmost=0 atleast=0 line = map(float, sys.stdin.readline().split()) F=line[0] n=line[1] def binomialDist(x,n,p): combination = (math.factorial(n) / (math.factorial(n-x) * math.factorial(x))) return math.pow(p,x)...
# Enter your code here. Read input from STDIN. Print output to STDOUT numerator, denominator = [int(x) for x in raw_input().split()] fail = 1.0 * numerator/denominator number = int(raw_input().strip()) success = 1 - fail # ** is power of operator ans_1 = 1 - success ** number print'{:0.3f}'.format(ans_1)
def nextGreatest(list): size=len(list) max_from_right=list[size-1] list[size-1]=-1 for i in range(size-2,-1,-1): temp = list[i] list[i] = max_from_right if(max_from_right < temp): max_from_right = temp def printArray(arr): for i in range(0,len(list)): ...
class Node: def __init__(self,data): self.data=data self.next=None self.prev=None class DLL: def __init__(self): self.head=None def push(self,new_data): new_node=N...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/build a string ''' #6-4L #33 - 1 L #35 - 32 L = 3 - 2 R #37 - 32 L = 5 - 4 R #39 - 32 L = 7 - 4 R 3 - 2 L count = 0 a = ["3", "4", "7"] goal = 40 for i in range(15000...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/ ''' l1 = [1, 2] l2 = [2, 3] l3 = [1, 3] def stones(du): for i in range(len(du)): cp = list(du) print(cp) toR = int(cp[0] / 2) i...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/alternating-characters ''' test_cases = int(raw_input()) for t in range(test_cases): word = list(raw_input()) prev = word[0] count_deletions = 0 for i...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/bigger-is-greater ''' for t in range(int(input())): l = [ord(i) for i in input()] flag = False for i in range(len(l)-1, 0, -1): if l[i] > l[i-1]: ...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Incomplete' ''' Problem Statement: https://www.hackerrank.com/challenges/half ''' def perm(orphans): for i in range(len(orphans)): newOrphans = list(orphans) if newOrphans[i] == 1: del newOrphans[i] ...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/caesar-cipher-1 ''' waste = input() arr = [ord(i) for i in list(input())] r = int(input()) % 26 for i in range(len(arr)): if arr[i] >= 97 and arr[i] <= 122: ...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/countingsort4 ''' waste = int(input()) arr = [] for i in range(waste): arr.append(input().split()) dicto = {} for i in range(waste): a = arr[i] k = int(a[0...
__author__ = 'Igor Sorokin' __email__ = 'igor.sorokin66@gmail.com' __status__ = 'Completed' ''' Problem Statement: https://www.hackerrank.com/challenges/the-time-in-words ''' def numToWord(num): if num == 1: return "one " elif num == 2: return "two " elif num == 3: return "three " elif num == 4: r...
import pandas as pd from galaxy_data import GalaxyData def get_reduced_solutions(solutions=None, upper_threshold=1, lower_threshold=0, classification=False): """Reduces solutions to only deal with class1.1, class1.2, and class1.3. Only values with one of these classes having more than the upper_threshold will ...
print(list(range(10))) num = list(range(5, 11)) print(num[2]) print(num) num = list(range(2, 101, 2)) print(num)
num = {1, 2, 3, 4, 5, 5} print(num) num2 = set([4, 5, 6]) num2.add(7) num2.remove(7) print(num2) print(7 in num2) print(7 not in num2) num3 = set([4, 5, 6, 7]) print(num | num3) print(num & num3) print(num - num3)
# 1 + 2 + 3 + 4 + ... + n n = int(input('Enter the last number: ')) sum = 0 for x in range(1, n+1, 1): sum += x print(sum) # 2 + 4 + 6 + ... + n sum = 0 for x in range(2, n+1, 2): sum += x print(sum) # 1*1 + 2*2 + 3*3 + ... + n*n sum = 0 for x in range(1, n+1, 1): sum += x*x print(sum) # Factorial sum =...
try: list = [20, 0, 30] result = list[0] / list[3] print(result) print('Done') except ZeroDivisionError: # except IndexError: print('Dividing by zero is not possible') finally: # finally keyword block must be work if there any error print("Successful") '''except (ZeroDivisionError, IndexErr...
num1 = 50 num2 = 20 print(num1 if num1 > num2 else num2)
#import tkinter as tk #window = tk.Tk() #greeting = tk.Label(text="Python Rocks") #greeting.pack() #window.mainloop() class Node: def __init__(self, val, name): self.val = val self.name = name self.prev = None self.next = None first = Node('sup', 'John') second = Node('bro', 'Mi...
# Import the os library import os # Ask the user to input the directory address nameOfDirctry = input("Enter Directory Address to store the new file: ") # Ask the user to input the file name of the file to be created nameOfFileToBeMade = input("Please enter the name of file to be created: ") # Ask the user to input hi...
####################################Tasks: # 1 .Write a script which accepts a sequence of comma-separated # numbers from user and generate a list and a tuple with those numbers. # Sample data : 1, 5, 7, 23 # Output : # List : [‘1', ' 5', ' 7', ' 23'] # Tuple : (‘1', ' 5', ' 7', ' 23') ...
######################################################## '''Task 6. Вводиться число. Якщо це число додатне, знайти його квадрат, якщо від'ємне, збільшити його на 100, якщо дорівнює 0, не змінювати.''' def my_fun(a): if a>0: a=a**2 elif a<0: a+=100 else: a return a ###############...
####################################Tasks: #3. Write a script to sum of the first n positive integers. s=0 n=int(input('n=')) for i in range(n+1): s=s+i print('s=',s)
import sys import functools # direction: 0 - north, 1 - east, 2 - south, 3 - west # intersectMemory: 0 - left, 1 - straight, 2 - right class Cart: def __init__(self, x, y, direction): self.x = x self.y = y self.direction = direction self.intersectMemory = 0 def get_pos_string(s...
# -*- coding: utf-8 -*- import socket #https://docs.python.org/2/library/socket.html#module-socket """ - Se foi fornecido um nome de protocolo de transporte converter em número; - Criar o socket (função socket); - Coloca um endereço local, endereço IP e porta, no socket (função bind); - Instrui o sistema operacional ...
#!/usr/bin/python3 import turtle import random STEP = 5 def rw_step0() -> None: turtle.forward(STEP) turtle.left(random.randint(0, 360)) def rw_step1() -> None: x, y = turtle.pos() dirr = random.randint(0,3) if (dirr == 0): x += STEP elif (dirr == 1): x -= STEP elif (dirr...
# import math module from math import pi # take input from user r = float(input ("Input the radius of the circle :1.1 ")) # compute the area from radius of a circle given by user calculateArea = str(pi * r**2); #print result print ("The area of the circle with radius: 1.1 " + str(r) + " is: " + calculateAr...
def bubble(arr): for i in range(len(arr)): for j in range(len(arr)-1-i): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] print('Enter the numbers seperated by space: ',end = '') arr = [int(x) for x in input().split()] bubble(arr) print('Sorted array:',*arr)
#!/usr/bin/env python3 """ simplegcn/demo.py While simplegcn.model gives the core implementation of the graph convolutional layer, this module seeks to demonstrate how you could use that layer in a broader network. This module demonstrates the canonical two-layer GCN with ??? Will Badart created: NOV 2018 """ __al...
from os import system, path from tkinter import Tk, Label,Button,N,E,W,S root=Tk() root.configure(background="white") def onClickCreateDataSet(): system("python3 dataSetCreater.py") print("Data Set created") def onClickTrainDataSet(): system("python3 trainer.py") print("Trained classifier") def onC...
V = {'a', 'b', 'c', 'd', 'e'} # 节点集 E = {'ab', 'ac', 'bd', 'cd', 'de'} # 边集 class graph: def __init__(self,gdict=None): if gdict is None: gdict = {} self.gdict = gdict # Get the keys of the dictionary def getVertices(self): return list(self.gdict.keys()) # Add t...
import csv def readCsv(fileName): quotes = [] with open(fileName, newline='') as csvFile: next(csvFile) reader = csv.DictReader(csvFile, [ 'date', 'open', 'high', 'low', 'close', 'adjClose', 'volume' ]) ...
import tensorflow as tf class DiscriminativeClass(object): """ Represents a class (e.g. a class of digits) that should be used within training. Args: positives_initializer_fn: A function that returns some sort of ImageProvider. This function should take no arguments. negatives_initializer_fn:...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: #brute force O(m*n) while headA!=None: node=headB while ...
class Solution: def searchInsert(self, nums, target): self.list=nums self.len=len(nums) self.target=target middle=self.len//2 return self.findplace(0,self.len-1) # find middle of array, # compare middle of array with target middle=(beginIndex+endIndex+1)//2 ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findLeaves(self, root: TreeNode) -> List[List[int]]: def getDepth(node, ans_list): ...
class Solution: #hashmap def majorityElement(self, nums: List[int]) -> int: len_nums = len(nums) dict_nums = {} for num in nums: if num in dict_nums: dict_nums[num] += 1 if dict_nums[num] > len_nums//2: retu...
class Solution: def findComplement(self, num: int) -> int: #self times = 0 begin = num while num != 0: num = num >> 1 print(num) times += 1 times = 1 if times == 0 else times return (1 << (times)) -1 - begin class Solution1: def...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: #the most intuitive solution def recursionsearch(node,val)...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructMaximumBinaryTree(self, nums): #first intuition answer #not great. Since for everytime we look for the index...
class Node: def __init__(self, val): self.val = val self.word = False self.children = dict() class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node(0) def insert(self, word: str) -> None: """ ...
class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: count = 0 for direction in shift: if direction[0]==0: #shift left count += direction[1] else: count -= direction[1] count= count%len(s) r...
class Node: def __init__(self,value): self.val = value self.next = None self.before = None class DoublelyLinkedlist: def __init__(self): self.head = None self.tail = self.head def append_left(self, value): new_node = Node(value) new_node.next = self.he...
#backtracking thinking #keep going to the last one if stuck then return false #orders are top to bottom, results bottom up. from functools import lru_cache class Solution: def canJump(self, nums: List[int]) -> bool: len_n = len(nums) def helper(index): if index == len_n-1: ...
class Solution: def wallsAndGates(self, rooms: List[List[int]]) -> None: """ Do not return anything, modify rooms in-place instead. """ if rooms == []: return row = len(rooms) column = len(rooms[0]) visited = [[False for i in range(column)...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def verticalOrder(self, root: TreeNode) -> List[List[int]]: verticalDict = dict() if root == None: return [] ...
class Solution: def generateAbbreviations(self, word): #recursion method if word == "": return [""] resultL = [] for item in self.generateAbbreviations(word[1:]): if item == "" or item[0].isalpha(): resultL.append(word[0]+item) ...
class goodNumber: #input: N. # output: numbers of number that are from 1 to N #is valid after each digit #rotation.ArithmeticError def checkGoodNumber(self, N): self.validdigit = {0:0,1:1,8:8,2:5,5:2,6:9,9:6} def checkRotationValid(numberX): '''check if input is a valid ...
import math class Solution2: #Aug, 2019 divide and conquer. def maxSub(self,nums): if len(nums)==0: return "It's an empty list" elif len(nums)==1: return nums[0],nums[0],nums[0],nums[0] elif len(nums)>=2: middle=math.ceil(len(nums)/2) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution1: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': #recursive # this question...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: #look through the list # if val is val, then do something # if val is not, then move ...
from functools import lru_cache class Solution: def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int: #if target == 0 now, shouldn't initiate new color # have options to choose between N colors for each house really unless you can't initiate a new color. ...
class ValidWordAbbr: #a lot of edge cases. first AC answer. def __init__(self, dictionary): self.listW = dictionary self.lenL = len(dictionary) self.dictSet = dict() self.mark = set() for item in self.listW: if item not in self.mark: self.mark...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) carry = 0 currentNode = dummy while l1 or l2: ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findMode(self, root): self.resultL = {} if root == None: return [] self.maxN = 1 def dfs(root): ...
class Solution: def expand(self, S): #first part, clean up S #second part backtrack dealing with permutation. flag = False listOfItem = [] for cha in S: if cha == "{": flag = True currentS = "" elif cha == "}": ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def largestValues(self, root: TreeNode) -> List[int]: # BFS resultL = [] if root == None: return resu...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool: #wrong. failed at [8, 3, null, 2,...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: #inplace def insertionSortList(self, head: ListNode) -> ListNode: pseudo_head = ListNode() pseudo_head.next = head pointe...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: #use N to mark. queueList = [root] resultList = [] ...
#!/usr/bin/env python3 """ Author: keg program to cheat at dice """ # import specific Classes from 'cheatdice' from cheatdice import Player from cheatdice import Cheat_Swapper from cheatdice import Cheat_Loaded_Dice def main(): """ main program """ # create Cheat_Swapper object cheater1 = Cheat_Swap...
#!/usr/bin/env python3 import os import zipfile iszip = input("What file would you like to check? ") zipfileobj = zipfile.is_zipfile(iszip) if zipfileobj is True: print(f"File {iszip} is a valid .zip file") if zipfile.is_zipfile(iszip) is True: print(f"File {iszip} is also a valid .zip file")
#Isomorphic Strings #Given two strings s and t, determine if they are isomorphic. """ Given "egg", "add", return true. Given "foo", "bar", return false. Given "paper", "title", return true. """ #使用映射解决问题,用数组做映射。 class Solution: def isIsomorphic(self, s, t): if len(s)!=len(t): return False ...
class file_ops(object): """ Static: Takes in the fully-qualified name of a file, opens it and returns a byte array representation :param file_name: :return array: """ @staticmethod def file_to_bytes(file_name): # Open the file for reading and read the contents into a byte array ...
from nltk.book import * from pprint import pprint def lexical_diversity(my_text): # 1_4b """ len(text) - определяет лексемы. :return: """ count_of_lexemes = len(my_text) # количество лексем. Лексемы - не только слова, но и знаки пунктуации count_of_words = len(set(my_text)) # количество эле...
''' even_odd_vending.py Print whether the input is even or odd. If even, print the next 9 even numbers If odd, print the next 9 odd numbers. ''' def even_odd_vending(num): if (num % 2) == 0: print('Even') else: print('Odd') count = 1 print(num) while count <= 9: num += 2 ...
''' mandelbrot.py Draw a Mandelbrot set Using "Escape time algorithm" from: http://en.wikipedia.org/wiki/Mandelbrot_set#Computer_drawings Thanks to http://www.vallis.org/salon/summary-10.html for some important ideas for implementation. ''' import matplotlib.pyplot as plt import matplotlib.cm as cm # Subset of the...
''' Retrieve a day's forecast of New York City and create a graph Using https://github.com/csparpa/pyowm ''' import matplotlib.pyplot as plt from pyowm import OWM import pytz owm = OWM('<token>') def get_forecast(city): # this used to be daily_forecast # https://github.com/csparpa/pyowm/issues/266 fc = ow...
''' linear_correlation_enhanced.py Linear correlation program ''' def find_corr_x_y(x,y): if len(x) != len(y): print('The two sets of numbers are of unequal size') return None n = len(x) # find the sum of the products prod = [xi*yi for xi, yi in zip(x, y)] sum_prod_x_y = sum...
''' graphical_eq_solve.py Graphical equation solver ''' from sympy import Symbol, sympify, solve, SympifyError from sympy.plotting import plot def solve_plot_equations(eq1, eq2, x, y): # Solve solution = solve((eq1, eq2), dict=True) if solution: print('x: {0} y: {1}'.format(solution[0][x], solut...
# -*- coding: utf-8 -*- # 변수와 이름 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print("자동차",cars,"대가 있습니다.") print("운전자는",drivers,"명 뿐입니다.") prin...
from dataclasses import dataclass @dataclass class Vehicle: # Attributes. brand : str model : str buildyear : int licenseplate : str needscleaning : bool milage : float isavailable : bool # Rent vehicle function. def RentVehicle(self): if self.isavailable == True: ...
def qsort(i): if len(i) in (0, 1): return i p = i[-1] l = [x for x in i[:-1] if x <= p] r = [x for x in i[:-1] if x > p] return qsort(l) + [p] + qsort(r) q_list = [1,4,2,5,3]
# RC_5_2 功能: 景氣對策信號。 score=int(input('請輸入景氣對策信號綜合分數 = ')) if score>45 or score<9: print('錯誤') elif score>37: print('紅燈') elif score>31: print('黃紅燈') elif score>22: print('綠燈') elif score>16: print('黃藍燈') else: print('藍燈')
import os.path #匯入os.path #利用isfile()方法先行判斷檔案是否存在 #如果檔案存在則印出檔案內容 if os.path.isfile("resume.txt"): fb=open("resume.txt","r") for word in fb: print(word) #如果檔案不存在則輸出檔案不存在的文字 else: print("所指定開啟的檔案不存在")
# -*- coding: utf-8 -*- lis1=list(range(5,20,1)) lis2=list(range(9,24,1)) lis1.append(sum(lis1)) lis2.append(sum(lis2)) lis1=sorted(lis1,reverse=True) lis2=sorted(lis2,reverse=True) print(lis1.pop()*lis2.pop())
# -*- coding: utf-8 -*- str1="Never say Never! Never say Impossible!" str2="浪花有意千重雪,桃李無言一隊春。\n一壺酒,一竿綸,世上如儂有幾人?" s1=str1.count("Never",15) s2=str1.count("e",0,3) s3=str2.count("一") print("{}\n「Never」出現{}次,「e」出現{}次".format(str1,s1,s2)) print("\n{}\n「一」出現{}次".format(str2,s3))
# H_5_5.py 功能:輸入頭和腳的數量,並判斷出有多少馴鹿及聖誕老人 # 輸入頭及腳的數量 head = int(input('請輸入頭的數量 : ')) foot = int(input('請輸入腳的數量 : ')) # 計算馴鹿和聖誕老人的數量 reindeer = (foot/2) - head Santa = head - reindeer # 將結果顯示出來 print('聖誕老人有 : %d 位' %(Santa)) print('馴鹿有 : %d 隻' %(reindeer))
# -*- coding: utf-8 -*- import sys print("sys.argv:{}".format(sys.argv)) print("文件名稱{}".format(sys.argv[0])) length = len(sys.argv) if len(sys.argv) < 2: try: sys.exit(0) except: tp, val, tb=sys.exc_info() print("exit!..{}:{}".format(tp,val)) for i in range(1,lengt...
# -*- coding: utf-8 -*- """ 樂透開獎與對獎程式 題目要求: 1.讓投注者輸入5個不重複的號碼,每個號碼以逗號(,)隔開 2.隨機產生開獎號碼。 3.計算投注者的5個號碼有幾個號碼開出。 4.輸出需包含開獎號碼的開出順序、大小順序,投注者選的號碼以及符合的號碼; 如果沒有符合則顯示「沒有符合!」。 """ import random def generate_num(): auto_num = [] while len(auto_num)<6: x = random.randint(1, 50) if x not in auto_num: ...
# -*- coding: utf-8 -*- """ 指派運算子練習 """ a = 1 b = 2 c = 3 x = a + b * c print("{}".format(x)) a += c print("a={0}".format(a,b)) #a=1+3=4 a -= b print("a={0}".format(a,b)) #a=4-2=2 a *= b print("a={0}".format(a,b)) #a=2*2=4 a **= b print("a={0}".format(a,b)) #a=4**2=16 a /= b print("a={0}".format(a,b)) ...
# -*- coding: utf-8 -*- """ 輸入兩次段考成績及期末考成績 段考只要其中一次及格並且期末考及格 學期成績才會及格,及格輸出PASS,否則輸出FAIL """ grade1 = int(input("請輸入第一次段考成績:")) grade2 = int(input("請輸入第二次段考成績:")) lastGrade = int(input("請輸入期末考成績:")) if (grade1>=60 or grade2>=60) and lastGrade>=60: print("PASS") else: print("FAIL")
# E_5_15_2 功能: 積分計算面積(1)。 import numpy as np dx=float(input('Please input dx =' )) area=0 y=0 for x in np.arange(2, 5, dx): y=(x**2)+1 area=area+(y*dx) print('area = ', area)
tuple1 = (24, 38, 32, 48, 4) print('tuple 所有的元素如下:') for item in range(len(tuple1)): print ('tuple1[%2d] %3d' %(item, tuple1[item]))
# -*- coding: utf-8 -*- """ 程式名稱:九九乘法表 """ for x in range(1, 10): for y in range(1, 10): print("{0}*{1}={2: ^2}".format(y, x, x * y), end=" ") print()
# -*- coding: utf-8 -*- base_freq = 440 octaves = 3 notes = 12 # TODO Make a list of the notes instead factor = 2 ** (1 / notes) print("factor : ", factor) def freq_from_a4(steps_up): return base_freq * (2 ** (1 / notes)) ** steps_up print("freq + 12 : ", freq_from_a4(12)) cur_note = base_freq...
from datetime import datetime def get_timedelta_string(dt): now = datetime.now() timedelt = now - dt # Printing logic if timedelt.days > 0: num = timedelt.days unit = "day" elif timedelt.seconds > 3600: num = timedelt.seconds / 3600 unit = "hour" elif timedelt....
# Problem Statement # Q4. Check if a number is divisible by three or seven n = int(input("enter a number:")) if (n % 3 == 0) and (n % 7 == 0): print("The number is divisible by both three and seven") else: print("The number is not divisible by three and seven")
# Problem Statement """ Q.36 Display number of tries in Guess the number game. Also refer problem 26(Q.26) """ def guess_the_number(n): guess = int(input("Enter your guess :")) count = 0 while True: if guess > n: count += 1 print("Number of tries : {}\n Guess is Greater tha...
# Problem Statement # Q13. Write a program that prints the next 20 leap years. #A leap year is exactly divisible by 4 except for century years (years ending with 00). # The century year is a leap year only if it is perfectly divisible by 400. For example: # 2017 is not a leap year # 1900 is a not leap year # 2012 is a ...
#!/usr/bin/python3 """ This is the desctription of the module/. """ var = "This is a variable" class Foo: """ Foo class description. """ def __str__(self): """ Foo.__str__() method description. """ return("This is a Foo instance") def function1(): """ function1 description. """ prin...
#!/usr/bin/python3 """ Framework Django D01 - 42 Created on: Author """ """ """ class Vegetables: pass class Fries: pass """ """ class Human: def eat(self, food): """ is food est de type Vegetables, je leve une exception """ if isinstance(food, Vegetables): """ l ...
#given an array, implement bubble sort. #This is a very slow sorting algorithm compared to algorithms like quicksort, with worst-case complexity O(n^2). #However, the tradeoff is that bubble sort is one of the easiest sorting algorithms to implement from scratch. import random test_array = [] for i in range(101): ...
#given two strings check if they are anagrams of eachother. #inthis it doesn't matter if the two strings are words or in the same order, Only that they contain the same letters. anagram_1 = "dirty room" anagram_2 = "dormitory" def test_anagram(word_one,word_two): word_one = word_one.replace(" ","") word_two ...