text
stringlengths
37
1.41M
# Stage 1 class PiggyBank: pass print("Hello") pg1 = PiggyBank() print(pg1) print(id(pg1)) print(hex(id(pg1))) print(type(pg1)) print(pg1.__class__) # Stage 2 -Extensible class PiggyBank: pass pg1 = PiggyBank() print(pg1) print(id(pg1)) print(pg1.__class__) pg1.balance = 10 # It creates a variable ba...
print("Welcome to Object Graph1") l1 = [10,20,True,"cat"] l2 = [90,l1,False,[1,2,3],(4,5,6)] t1 = [l1,l2,9,10] d1 = { "a" : [-1,-2,-3], "b" : ['e','a','r'], "c" : (t1,l1,l2), "d" : {"m":11,"n":22,"o":33,"p":[55.66]} } print(l1[3]) print(d1["b"][2]) print("Thankyou for using python's object graph")
# Abigail Anderson print('Hello world!') print('Choose a language and I will greet you in that language!') print('1. Spanish') print('2. French') print('3. Japanese') choice = int(input()) # user inputs number 1, 2, or 3 if choice == 1: print('Hola!') elif choice == 2: print('Bonjour!') elif choice == 3: prin...
# WRITE YOUR NAME and YOUR COLLABORATORS HERE #------------------------- 10% ------------------------------------- # The operand stack: define the operand stack and its operations opstack = [] #assuming top of the stack is the end of the list # Now define the HELPER FUNCTIONS to push and pop values on the opst...
''' Using memoization to solve fibonacci problem ''' # Time complexity: O(n) # Space complexity: O(n) def fib(n, memo={}): if n in memo: return memo[n] if n < 0: return if n <=2 : return 1 memo[n] = fib(n-1) + fib(n-2) return memo[n] print(fib(5)) print(fib(6)) print(fib(50))
''' Given a target number and a list of number? Return array of number if we can generate the target number from the list. (use additional only) Else return None Can use any number in the list multiple times. ''' def howSum(target, numbers, memo={}): if target in memo: return memo[target] if...
''' Given a target string and list of words. Return number of way that the target string can be generated from the list ''' def countConstruct(target, words): table = [0 for i in range(len(target)+1)] # There is 1 way to construct empty string: table[0] = 1 for i in range(len(target)): ...
from utils.game import Board new_game = Board() new_game.start_game() # COACHES' NOTES: The game works well! Nicely done! # COACHES' NOTES: Your code is close to perfect. # Take these comments as tiny improvements, you have done an excellent job. # - Good type hinting # - Very nice docstring of functions # - Very n...
def test_brackets(string): // limit to only methods push and pop stack = [] for char in string: if ( char == '[' or char == '{' or char == '('): stack.push(string[i]) if (char == ']' or char == ')' or char == '}': bracketPopped = stack.pop() if ((bracketPopped == '[' and char == ']...
from open_program import OpenProgram import json ''' Get string from file ''' json_data = open("tasks.json") data = json.load(json_data) ''' Init OpenProgram class ''' open_program = OpenProgram( data ) ''' Start CLI flow with messages ''' print("list - get all programs available") print("open - select pr...
input = "0 5 10 0 11 14 13 4 11 8 8 7 1 4 12 11" def rebalance(bank): bank = list(bank) length = len(bank) max_value = max(bank) max_value_index = bank.index(max_value) index = max_value_index bank[index] = 0 for _ in range(max_value): index = (index + 1) % length bank[index] += 1 return...
''' 24-game gives the player 4 numbers, and ask for player to use operations +, -, * on these numbers in a way that the result equals to 24 ''' import operator import random import itertools class number_set(): def __init__(self, a, b, c, d): self.numbers = [a, b, c, d] def start_game(self): ...
x = input("Tekrar sayısını giriniz") x = int(x) y = -5 while y < x : if y == 0: y = y + 1 continue print(x / y) y = y + 1 print("İkinci while") y = 0 while y < x: if y % 2 == 0: break print(y) y = y +1 else: print("ikinci while bitti") print("Döngü sona erdi"...
"""Generate Random Number.""" from random import randint dice_roll = input("nds: ") split_array = dice_roll.lower().replace(" ", "").split("d") while len(split_array) != 2: print("Incorrect input, should input number of die, \"d\"," " then side number. i.e. 1d4") dice_roll = input("nds: ") spli...
print("Hello WORLD") for i in range(5): if i==3: continue print(i) for i in range(5): if i==3: break print(i) from datetime import datetime '''print("hello world!") for i in range(10): if i==3: break print("{}".format(i)) #shift+enter for working in inter...
from threading import Thread import time class A(Thread): def run(self): for i in range(1,3): print(i**3) time.sleep(1) class B(Thread): def run(self): for i in range(1,3): print(i**2) time.sleep(1) a=A() b=B() a.start() b.star...
def greater_than(args): return args[0] > args[1] def greater_or_equal_than(args): return args[0] >= args[1] def between(args): return args[1] <= args[0] <= args[2] def even(args): return divisible_by([args[0], 2]) def odd(args): return args[0] % 2 != 0 def equal(args): return args[0] =...
import turtle import math #定义多个坐标 x1,y1=100,100 x2,y2=100,-100 x3,y3=-100,-100 x4,y4=-100,100 #绘制折线 #turtle抬笔 turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.goto(x2,y2) turtle.goto(x3,y3) turtle.goto(x4,y4) #计算起始点与终点的距离 #第一种计算距离的方法,引入了math # distance =math.sqrt((x1-x4)**2+(y1-y4)**2) # turtle.write(distanc...
def main(): #print("Start time: ") #start = input() #print("Duration: ") #duration = input() #print("Day?: ") #day = input() # Temp params start = "11:59 PM" duration = "24:05" day = "null" print(add_time(start, duration, day)) def add_time(start, duration, day="null"): ...
import sqlite3 class DataStoreSqlite(object): """ Database class to create , insert and fetch the data """ def __init__(self): self.conn = sqlite3.connect('search.sqlite') # connecting to database and creating table self.cur = self.conn.cursor() self.table = self.cur.execute('CREATE ...
''' N students take K apples and distribute them among each other evenly. The remaining (the undivisible) part remains in the basket. How many apples will each single student get? How many apples will remain in the basket? The program reads the numbers N and K. It should print the two answers for the questions above. '...
""" Functions for displaying things on the console """ import sys import os import csv import numpy as np import matplotlib.pyplot as plt def printparamsexp(paramdict, errordict=None, decimals=4): """ Prints the keys and values of a dictionary in an exponential form. Required Parameters --------...
print('*'*80) print('.......................Welcome to Sandeep MLOps task o1...........................') import pandas as pd from sklearn.linear_model import LinearRegression print('*'*80) db=pd.read_csv('test_data_set.csv') print('We have a Data Set Now we are used to and now we are show ...') print('#'*80)...
def arrayTest(array): print(array) array.append('j') print(array) array.pop() print(array) array = ['0'] + array print(array) from collections import deque #faster for pop and append (both left and right, so queues and stacks. But slower for inserting at the middle def tryDequeue(): dequeVar = deque('abc') pr...
''' Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: In...
#class Memoize: # def __init__(self, fn): # self.fn = fn # self.memo = {} # def __call__(self, *args): # if args not in self.memo: # self.memo[args] = self.fn(*args) # return self.memo[args] def addTo80(n): print("Looooong time") return 80 + n #@Memoize def memoizedAddTo80(n...
# Define the classes (Student, Exam, University) so that following # Excerpt of code from a Student Management System works as expected. import random class Student: def __init__(self, name, dob): self.name = name self.dob = dob self.exams = {} def takeExam(self, exam): grade ...
# Decorators # • Python has an interesting feature called decorators to add functionality to an existing code. # • This is also called metaprogramming as a part of the program tries to modify another part of the program at compile time # • A decorator in Python is an object that takes a function and returns a function....
'''This is a simple tennis game created with the use of Pygame module. Players hit the ball using rackets which can move vertically. The game lasts until one of the players gets the score of 6 points winning the game.''' import pygame import time class Background(pygame.sprite.Sprite): '''Background class.'''...
#!/usr/bin/env python #-*- coding:utf-8 -*- """ Mercury data This program provides the Mercury data for the simulation Author: Sandro Ricardo De Souza: sandro.fisica@gmail.com """ # Import modules import numpy as np import pandas as pd import oe2pv import math # Name for each Mercury's cadidates varying the semi-a...
# 给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。 # # 你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。 # # # # 示例 1: # # # 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] # 输出:[[7,4,1],[8,5,2],[9,6,3]] # # # 示例 2: # # # 输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # 输出:[[15,13,2,5],[14,3,4,1...
# 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 # # 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 # # 示例1: # # 输入: pattern = "abba", str = "dog cat cat dog" # 输出: true # # 示例 2: # # 输入:pattern = "abba", str = "dog cat cat fish" # 输出: false # # 示例 3: # # 输入: pattern = "aaaa", str = ...
# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 # # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # # # # 示例: # # 给定 1->2->3->4, 你应该返回 2->1->4->3. # # Related Topics 链表 # 👍 620 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. # class ListNode: # def __init__(self, x...
# 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“ # 房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。 # # 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。 # # 示例 1: # # 输入: [3,2,3,null,3,null,1] # # 3 # / \ # 2 3 # \ \ # 3 1 # # 输出: 7 # 解释: 小偷一...
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'andylin' __date__ = '17-12-28 上午11:06' import threading import time import os def run(num): print('runing on number %s ' % (num)) time.sleep(3) print("------all status-------", threading.current_thread()) thread_list = [] start_time = time.t...
# Randamized Quick Sort Algorithm # Time Complexity ==> Best Case O(NlogN), Worst Case O(NlogN) # Space Complexity ==> O(1) import random def partitionSort(array,p,r): pivot = array[p] i = p j = i+1 while j<=r: if pivot<array[j]: j +=1 else: i +=1 t...
for _ in range(int(input("Enter Passes"))): l=[int(i) for i in input().split()] def bubblesort(l): n=len(l) for i in range(n): swapped=False for j in range(n-1-i): if l[j] > l[j+1]: l[j] , l[j+1] = l[j+1],l[j] ...
def greet(): return ("Welcome to the Calculator App- your very limited calc app") print(greet()) input_1 = float(input("What is your first number? ")) input_2 = input("What do you want to do with that number? (ie. +,-,*,/) ") input_3 = float(input("Give me one last number that will affect that first number you ent...
def bubbleSort(list): for i in range (0,len(list) -1): for j in range(0, len(list) - 1 - i): if list[j] > list[j+1]: list[j], list[j+1] = list[j+1], list[j] return list list = [2,55,6,969,13,1000] print(bubbleSort(list))
import json user_input = "" name = input("What is your name?") with open("guest.json",'w') as file_object: json.dump(name,file_object) responses = [] while user_input != "QUIT": user_input = input("Why do you like programming?") responses.append(user_input) with open("guest.json",'a') as file_object: ...
def iterative(it, size): conses = [] for el in it: conses.append([]) for index, cons in enumerate(conses): cons.append(el) # print(el, "--", conses) if len(conses[0]) == size: yield conses.pop(0) def recursive(it, size): it = iter(it) def helper...
# Detect Pangram # Check if string s contains all alphabet characters import string ''' orginal version def is_pangram(s): return len(set(string.ascii_lowercase)) <= len(set(s.lower())) ''' # Better one: def is_pangram(s): return set(string.ascii_lowercase) <= set(s.lower()) # set operation "<=" checks if r...
def tree_from_string(s, tokens=None, add_space=False): if tokens is not None: assert add_space is False return recursive_parse(tokens)[0] if add_space: s = s.replace('(', '( ').replace(')', ' )') return recursive_parse(s.split())[0] def recursive_parse(tokens, pos=0): if tokens...
import cv2 import numpy as np def drawcontours(img): ''' This function is to draw contours on original image ''' image = cv2.imread(img) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (13, 13), 0) edged = cv2.Canny(blurred, 30, 150) contours, _ = cv2.fin...
import math def primality(n): a = 0 if n < 2: return False for i in range(2, math.ceil(math.sqrt(n)) + 1): if n % i == 0: a += 1 if a == 0: return True else: return False # Пример print( primality(61) )
#Using quicksort to sort the list def partition(list, low, high): i = (low-1) pivot = list[high] for x in range(low, high): if list[x] <= pivot: i = i+1 list[i], list[x] = list[x], list[i] list[i+1], list[high] = list[high], list[i+1] return (i+1) def quicksort(list...
#Iteration 3: Loop it to run 1000 times import random import numpy def run_simulation(): counter = 0 day_number = 0 prisoner_chief = 1 lever_position = 'down' prisoners_who_have_operated_lever = [] while counter < 50: prisoner_number = random.randint(1,50) # Select a prisoner if not prisoner_numbe...
# Iteration 4: Monte Carlo simulator to method; parameterize no. of prisoners # and no. of runs; prettify output from numpy import array, mean import random def run_simulation(number_of_prisoners): counter = 0 day_number = 0 prisoner_chief = 1 prisoner_chief_has_not_operated_lever = True lever_position = 'd...
from ClaseProyecto import Proyecto import csv class ManejadorProyecto: __lista=[] def __init__(self): self.__lista=[] def CargarProyectos(self): archivo=open("proyectos.csv") reader=csv.reader(archivo,delimiter=';') for fila in reader: ...
__author__ = 'Djidiouf' # Python built-in modules from datetime import datetime, timedelta # displaying date and time # Third-party modules import pytz # install module: pytz # timezone information # Project modules import modules.connection import modules.time def main(i_string, i_medium, i_alias=None): ""...
from A_star_search_Romania_Map import * import time import random cities=["Craiova","Pitesti","Bucuresti","Oradea","Arad","Eforie","Drobeta","Fagaras","Giurgiu","Zerind","Timisoara", "Sibiu","Lugoj","Mehadia","Ramnicu Valcea","Urziceni","Hirsova","Vaslui","Iasi","Neamt"] with open('graph.txt', 'r') as file: ...
""" Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Note that 1 is typically treated as an ugly number. """ def is_ugly_number(numb...
import cv2 import numpy as np #分离图像 img = cv2.imread('img\\test.jpg') #b = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #g = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #r = np.zeros((img.shape[0], img.shape[1]), dtype = img.dtype) #b[:, :] = img[:, :, 0] #g[:, :] = img[:, :, 1] #r[:, :] ...
user = int(input("How many users do you want to insert? ")) aruser = [] for i in range (user) : aruser.append(input("Insert user " + str(i + 1) + " ")) for i in range (aruser.__len__()): print("The user 1, is: " + aruser[i])
main_str = input("Введите несколько слов через пробел") s = main_str.split(" ") print(s) for ind, el in enumerate(s, 1): if len(el) > 10: string = list(el) i = 10 while i < len(string): string.pop(i) el = ("".join(string)) print(ind, el)
n = float(input()) notas=[100, 50, 20, 10, 5, 2] moedas=[1.00, 0.50, 0.25, 0.10, 0.05, 0.01 ] print("NOTAS:") for i in notas: num = n//i n -= num*i print("{:.0f} nota(s) de R$ {:.2f}".format(num,i)) print("MOEDAS:") for i in moedas: num = n//i n -= num*i print("{:.0f} moeda(s) de R$ {:.2f}"...
def hyp(leg1,leg2): c = ((leg1**2)+(leg2**2))**.5 print(c) def mean(a,b,c): d=(a+b+c)/3.0 print(d) def perimeter(base,height): a = (base*2)+(height*2) print(a) hyp(1,12) mean(1,2,3) perimeter(1,1)
#Problem Nr.3 #http://www.practicepython.org print("Problem 3") a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] print(a) number = int(input("Type in a number..\nthe program will display you all numbers that are less than\nyour typed-in number in the list ")) print(a) for i in a: if i < number: b.appen...
# Расчет на какой день будет достигнута цель a = 5 b= 10 day= 1 while a <= b: print("in ", day, "day runing", a , "km") a = round(a *1.1,2) day +=1
""" Estudiante: Naranjo Sthory Alexanyer Naranjo Cédula de identidad: V - 26.498.600 Asignatura: Cálculo Científico (6105) Tarea 0: Introducción al Cálculo Científico Ejercico 1.6 """ def methodOne(): print('\t*** METHOD #1 ***\n') a = 0 b = 1 n = 100000 h = b/n x = a for i in range(1,n+1): x = x+h print...
n = int(input()) def isPerfect(num): total = 0 for i in range(1, num+1): if num % i == 0: total += i print(total) b = 'True' if num == total/2 else 'False' return b print(isPerfect(n))
def sockMerchant(n, ar): # n = 9, ar = list # sort --> 10 10 10 10 20 20 20 30 50 # inx 0 1 2 3 4 5 6 7 8 # cnt = pair of socks # tmp = list[0] tmp = ar[0] cnt = 0 i = 1 while i<n: try: if tmp == ar[i]: cnt += 1 tmp = ar[i+1] ...
# 73 의 다음 5의 배수 구하기 # 5의 배수 - 73 < 3 # 73 67 38 33 def finalScore(arr): mul_five = [] for i in arr: i += 5 - (i % 5) mul_five.append(i) return mul_five if __name__ == '__main__': n = int(input()) grades = [] for _ in range(n): score = int(input()) grades.app...
def review(s): # h a c k e r odd = [] even = [] for i, c in enumerate(s): if i % 2 == 0: #짝수 odd.append(s[i]) else: even.append(s[i]) return ''.join(odd) + ' '+ ''.join(even) if __name__ == '__main__': n = int(input()) for i in range(n): s =...
# 8 # UDDDUDUU def countingValleys(n, s): depth = 0 cnt = 0 for i in range(n): #index가 필요 if s[i] == 'D': cnt -= 1 else: cnt += 1 if cnt == 0 and s[i] == 'U': depth += 1 return depth if __name__ == '__main__': n = int(input()) s = i...
def compare(a, b): aWin = 0 bWin = 0 for i in range(len(a)): if a[i] > b[i]: aWin += 1 elif a[i] == b[i]: pass elif a[i] < b[i]: bWin += 1 return [aWin, bWin] if __name__ == '__main__': a = list(map(int, input().rstrip().split())) b = ...
#x=10, y=85, d=30 # return 3 import math def solution(X, Y, D): return int(math.ceil((Y-X) / D)) if __name__ == '__main__': res = solution(10, 85, 30) print(res)
def IsPrimeNum(d): if d ==1: return False elif d ==2 : return True import math sq = int(math.sqrt(d)) print(sq) for i in range(2, sq+1): if d % i == 0: return False return True if __name__ == '__main__': T = int(input()) for _ in range(T): ...
def binary_search(arr, target): low = 0 high = len(arr) -1 while low <=high: mid = int((low + high)/2) guess = arr[mid] if guess == target: return mid elif target < guess: high = mid-1 else: low = mid +1 return None if __nam...
from collections import deque graph = {} graph['CAB'] = ['CAR', 'CAT'] graph['CAR'] = ['BAR', 'CAT'] graph['BAR'] = ['BAT'] graph['CAT'] = ['BAT', 'MAT'] graph['MAT'] = ['BAT'] graph['BAT'] = [] def search(start): search_queue = deque() search_queue += graph['CAB'] visited = ['CAB'] while search_queu...
""" Dijkstra is a Shortest Path First (SPF) algorithm that iterates through every node in a graph, storing where its been and the weight for each connection. It retrieves useful information about the shortest path by linking a node to its minimum weight predecessor. So it becomes possible to calculate the shortest pat...
# Elena Voinu def raise_to_power(base_val, exponent_val): if exponent_val == 0: result_val = 1 else: result_val = base_val * raise_to_power(base_val, exponent_val-1) return result_val user_base = 4 user_exponent = 2 print('%d^%d = %d' % (user_base, user_exponent,raise_to_power(user_base, user_...
# Elena Voinu male_names = { 'Oliver', 'Declan', 'Henry' } # Remove 'Oliver' from the set, and add 'Atlas'. ''' Your solution goes here ''' male_names.remove('Oliver') # added print statement just to check that the right names are printed print("Oliver removed from na,es set:", male_names) male_names.add('Atlas') pr...
#Write an expression using Boolean operators that prints "Eligible" #if user_age is greater than 17 and not equal to 25. #Ex: 17 prints "Ineligible", 18 prints "Eligible". user_age = 17 #''' Your solution goes here ''' if (user_age > 17) and (user_age != 25): print('Eligible') else: print('Ineligible')
#Elena Voinu #Create a conditional expression that evaluates to string "negative" if user_val is less than 0, #and "non-negative" otherwise. Example output when user_val is -9 #sample program: -9 is negative user_val = -9 #''' Your solution goes here ''' cond_str = "negative" if user_val < 0 else "non-negative" ...
#Define a function pyramid_volume with parameters base_length, base_width, #and pyramid_height, that returns the volume of a pyramid with a rectangular base. #Relevant geometry equations: #Volume = base area x height x 1/3 #Base area = base length x base width. #''' Your solution goes here ''' def pyramid_volume...
# Elena Voinu '''function number_of_pennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506. ''' ''' Your solution goes here ''' def number_of_pennies(dollar=0,pennies=0): #declare variable total is 0 ...
class Node: def __init__(self, init_data): # the data stored in the node self.data = init_data # the pointer to the next item in the list self.next = None """none is a null value. we assume that they don't point to anything yet (just creating nodes) if it do...
""" Fibonacci Sequence """ import functools import unittest def memoise(function): function.cache = dict() @functools.wraps(function) def _memoise(*args): if args not in function.cache: function.cache[args] = function(*args) return function.cache[args] return _memoise @m...
print("Digite uma sequencia de valores terminada por zero: ") produto = 1 valor = 1 while valor !=0: valor = int(input("Digite um valor a ser multiplicado: ")) produto = produto * valor print("A produto dos valores digitados eh: ", produto)
#!/usr/bin/env python3 # This is a timer. # It accepts args time in hh:mm:ss # and length in integer # and action (bash command) # and it prints time left and nice graphic representation of remainder. # Depending on command line arguments it executes a specified command upon # reaching the end of ...
# string # initialization a = 'hello' print(len(a), type(a)) # element indexing d = a[-6] print(d, type(d)) # slicing : substring from string data h = 'hello world' d = h[-3::1] print(d, type(d)) # type cast with string # number k = int('1010',8) print(k, type(k)) k = float('2.4') print(k, type(k)) # list st = ...
def txt_to_string_arr(file_path): """ txt_to_string_arr :param file_path: 파일 주소 string 임 :return: (1D-array) string 배열 """ f = open(file_path, 'r') ret = [] while True: line = f.readline() if not line: break ret.append(line) f.close() return r...
# 像程式設計師這樣思考 # Chapter 2 問題:Luhn Checksum 第五部分 positive or negative positive = 0 negative = 0 for i in range(1, 11): digit = int(input('ENTER the ' + str(i) + ' numbers:')) if (digit > 0): positive = positive + 1 else: negative = negative + 1 response = input('Do you want the (...
import os from read_input import read_input_as_string def part_one(): abs_file_path = os.path.join(os.path.dirname(__file__), "input") input_data = read_input_as_string(abs_file_path) height_map = [[int(height) for height in line] for line in input_data] low_points = [] for y in range(0, len(he...
def sanitize_ns(string): new_string = '' sanitized = False numbers = [str(num) for num in range(0, 10)] for char in string: if char not in numbers: sanitized = True continue new_string += char return [new_string, sanitized]
""" This TSP Problem implements local search algorihtm to find solution, through using AIMA-Python. Taek Soo Nam(tn32) 23rd Feb 2019 """ from tools.aima.search import Problem, hill_climbing, simulated_annealing, exp_schedule import random class TSP(Problem): def __init__(self, initial, distances, num_citie...
from graphics import * def grid(win, nx, ny, w, h): ox = 10 oy = 10 total_height = oy + h * ny total_width = ox + w * nx for i in range(nx + 1): x = ox + i * w l = Line(Point(x, oy), Point(x, total_height)) l.setOutline('black') l.draw(win) for i in range(ny + 1): y = oy + i * h l = Line(Point(ox, y...
# @Author: Antero Maripuu Github:<machinelearningxl> # @Date : 2019-05-17 13:46 # @Email: antero.maripuu@gmail.com # @Project: Coursera # @Filename : Exercise_1_Housing_Prices.py #In this exercise you'll try to build a neural network that predicts the price of a house according to a simple formula. #So, imagine if ho...
# 异常 exception # 使用try .. except 处理异常 # the statements between the try and excep is executed # if no exception occurs , the except clause is skipped # and execuation of the try statment is finished try: text = input('Enter something-->') # Press ctrl + d except EOFError: print('Why did you do an EOF on me ?') ...
#!/usr/bin/env python3 # Import modules from the standard Python library import re # Import the regex module, this is for something later on # Import user defined modules import utilities # Setup our data and get some translation tables header, sequence, seq50 = utilities.setup() nucleotide_table, protein_dict...
#importing lib's #they are all built in lib's import random import string #asking the user qustions times = input('Enter The Nuber Of Password(s) You Want To Genarate: ') length = input('Enter The Length Of the Password(s): ') wantLower = input('Do you want lower case letters in the password(s) (y/n)') wantUpper = inpu...
#!/usr/bin/python3 import sys def count(text): lst = text.split(' ') print(len(lst) - lst.count ("'\\n',")) def main(): print("insert text here and finish it with endl(control D)") text = str(sys.stdin.readlines()) count(text) if __name__ == "__main__": main()
""" number = int(input("Gimme a number")) while number != 1: print (number) if number == 1: break if number%2 == 0: number = number/2 elif number%2 != 0: number = (number *3)+1 print (number) """ ''' def Graph(t,x): Space = [] for i in range (len(x)): a = x[i] while (True): ...
# FizzBuzz, Accumalative calculator, FizzBuzz Accumalative and Prime. #FIZZBUZZ """ for Number in range (1,10): if Number % 3 == 0 and Number % 5 == 0: print ("FizzBuzz!!!") elif Number % 3 == 0: print ("Fizz!") elif Number % 5 == 0: print ("Buzz!") else: print ("Oof big neck! The number w...
import csv #csv読み込んで〜 f = open('stock.csv', 'r') #ファイル開いて〜 reader = csv.reader(f) header = next(reader) for row in reader: #1行づつ読み込むよ print(row) f.close() #おまけ CsvFile = csv.reader(open('stock.csv'),delimiter=',') #csvファイルを読み込む CsvList = [] #空のcsvファイルを用意してあげて for i in CsvFile: CsvList.append(i) print(Csv...
for i in range(5, 10): print(i) print() for i in range(0, 10, 3): print(i) print() for i in range(-10, -100, -30): print(i) print() a = ['I', 'have', 'a', 'pen'] for i in range(len(a)): print(i, a[i])
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import sys ''' 数据格式转换 ''' def character_tagging(input_file, output_file): input_data = codecs.open(input_file, 'r', 'utf-8') output_data = codecs.open(output_file, 'w', 'utf-8') for line in input_data.readlines(): word_list = line.st...
def get_level(bmi): if bmi <= 18.5: level = '저체중' elif 18.5 <= bmi < 23: level = '정상' elif 23 <= bmi < 25: level = '과체중' elif 25 <= bmi < 30: level = '비만' else: level = '고도비만' # return : level값 호출 return level while True: height = input('Write you...
''' Author: c17hawke Name: Sunny Bhaveen Chandra Date: Nov 15 2019 Time: 1351 hrs IST Problem Statement:- Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. ''' import numpy as np def...