text
stringlengths
37
1.41M
# master_02.py # coding: utf-8 ''' itertools - 标准库之一 1. 创建无限迭代器 itertools.count(1),以1为间隔的等差数列 2. 创建无限迭代器 itertools.cycle('ABC'), 以ABC为循环的数列 3. 创建有限迭代器 itertools.repeat('A',10), 循环A 10次 4. 可以通过takewhile截取 比如 n= itertools.count(1) ns = itertools.takewhile(lambda x: x<10, n) 5. chain()可以将2个迭代器连起来: n1 = itertools....
# tips_08.py # coding: utf-8 ''' time.time() ''' import time start = time.time() for i in range(3000): print i end = time.time() print start,end print end - start
# test_lintcode_easy_02.py # coding: utf-8 ''' 给一个整数 c, 你需要判断是否存在两个整数 a 和 b 使得 a^2 + b^2 = c. 样例 给出 n = 5 返回 true // 1 * 1 + 2 * 2 = 5 给出 n = -5 返回 false ''' def checkTriage(n): for i in range(n): for j in range(n): if i**2 + j**2 == n: return True return False if __name__ == '__main__': n = 5 if c...
# test_lintcode_easy_03.py # coding: utf-8 ''' 给出两个字符串,你需要找到缺少的字符串 样例 给一个字符串 str1 = This is an example, 给出另一个字符串 str2 = is example 返回 ["This", "an"] ''' def findMissString(str1,str2): l1 = str1.split(' ') l2 = str2.split(' ') result_list = [] if len(l1) > len(l2): for item in l1: if item not in l2: r...
# test_4.py # coding: utf-8 ''' 从终端读入一个整数n,随机一个输入一个0 或1 判断连续是0 或1 的最大次数。如: 输入 0 0 0 1 1 1 1 0 1 0 1在连续输入中,出现4次 利用之前分解数组的知识。。。 ''' class Stack: def __init__(self,yourstring): self.items = [] for item in yourstring: self.items.append(item) self.items.reverse() def push(self,data): self.items.append(data) d...
# test_class.py # coding: utf-8 ''' 类,多态,继承 定义一个Point类 - 各种方法,+ ''' class Point: def __init__(self,x,y): self.x, self.y = x, y def set(self,x,y): self.x, self.y = x,y def __f(): pass def __str__(self): return 'I am a Point, x is {0}, y is {1}'.format(self.x, self.y) def __add__(self,other): return Poin...
#!/usr/bin/env python #coding:utf8 import sys def addr2dec(addr): items = [int(x) for x in addr.split('.')] return sum([items[i] << [24, 16, 8, 0][i] for i in range(4)]) def dec2addr(dec): return '.'.join([str(dec >> x & 0xff) for x in [24, 16, 8, 0]]) if __name__ == '__main__': if len(sys.argv) == 3...
print("Welcome to your life decider") print("***********") progress_count = 0 trailer_count = 0 retreiver_count = 0 excluded_count = 0 # creating cells def create_cells(count_type): print(" ", end=" ") if row<(count_type): print("*", end=" ") else: print(" ", end=" ") ...
# Name : Md Ashiqur Rahman # Student Number : 998419242 #Look for <<<...>>> tags in this file. These tags indicate changes in the #file to implement the required routines. Some mods have been made some others #you have to make. Don't miss addressing each <<<...>>> tag in the file! ''' 8-Puzzle STATESPACE ...
a= 3 if a < 5: print("less than 5") elif a == 5 : print("equal to 5") else: print ("greter than 5") def age_foo(age): new_age = age+ 50 return new_age age = int(input("enter you age: ")) if age < 150: print(age_foo(age)) else: print("how is that possible?")
# Dependencies import string import sys import re # Files to load and output input_file = "paragraph_1.txt" output_file = "paragraph_analysis.txt" # Read text file paragraph_text = open(input_file, 'r') paragraph_data = paragraph_text.read() # Find the number of words in the text file character_count = len(parag...
# -*- coding: utf-8 -*- from pila import Pila operadores=['*','+','-','/','='] #Pruebas de validacion de carácteres def esVariable (caracter): if caracter.isupper(): if caracter.isalpha(): return True return False def esNumero (caracter): try: caracter = int(cara...
N=int(input()) for c in range(2,N): if(N%c==0): print("no") break else: print("yes")
a=int(input()) sum=0 for c in range(1,a+1): sum=sum+c print(sum)
age = int(input("What is your age? ")) if age >=18: print("Your age is {:d}". format(age)) print("Adult!") elif age >=6: print("Your age is {:d}". format(age)) print("Teenager!") else: print("Your age is {:d}".format(age)) print("Baby!") ###################### BMI CALCULATOR ###############...
# fin = open('words.txt') # line = fin.readline() # print(line) # print(repr(line)) #prints the /n after the word. fin = open('C:/Users/jboenawan1/Documents/Fall 2017/Problem Solving & Design/Python-Programming-MIS3640/session10-dictionary_exercise/words.txt') for line in fin: word = line.strip() # print (wor...
Python3基础知识9(模块与包简单概念) (1)模块 #简单来讲:一个.py文件就称之为模块(Module)   注意:模块名就是py文件名(不包括.py) 比如test.py 模块化的好处: #1、以库(比如selenium库)形式封装功能,方便给别的代码调用;     库其实就是模块和包     可以使用自己写的库,Python标准库,第三方库 #2、避免变量名冲突(包括函数名)   如果一个代码文件特别的大,变量的名字容易发生重复   需要想出不同的变量名或者函数名   如果采用模块分割代码,每个模块文件代码都不是很多,就可以大大的缓解这个问题   每个模块中的变量名作用域只在本模块中 (2)函数的调用 #不同模块...
#This project trains a model with LSTM and 30-day rolling basis data to forecast future 5 days stock prices. #import packages used in this project import math import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM from pandas_datareader imp...
class Graph: def __init__(self, n = None, e = None): self._nodedict = {} if not n else n self._nodelist = [] self._edgedict = {} if not n else e self._edgelist = [] @property def node(self): return self._nodedict @property def edge(self): ...
def find_short(s): srted = sorted(s.split(' '), cmp=lambda x,y: len(x)-len(y)) return len(srted[0]) import unittest class TestShortestWord(unittest.TestCase): def test_shortest_word(self): self.assertEquals(find_short("bitcoin take over the world maybe who knows perhaps"), 3) self.assertEq...
#cording: utf-8 print('3つの数値を入力してください.') a,b,c=input().split() print(str(a)+','+str(b)+','+str(c)+'が入力されました.') list=[int(a),int(b),int(c)] d=sorted(list) print("元のリスト",list) print("ソート後",d) print('output: '+str(d[0])+" "+str(d[1])+" "+str(d[2]))
for i in range(6): a,op,b=input().split() a=int(a) b=int(b) if(op=='?'): break if(op=='+'): print(a+b) if(op=='-'): print(a-b) if(op=='*'): print(a*b) if(op=='/'): print(a//b)
""" Example of a competing program. Please read the doc and the comments. """ """ playerinterface provides the functions to generate valid return values. You do need this one. Do not delete. """ from playerinterface import spawn_into, move_from_to, fire_at, do_pass from random import randint """ You have to provide...
#!/usr/bin/env python2 # taks8/mapper1.py import sys from collections import defaultdict def map_function(line): """For a given record emits (key, value) pair where key = title id and value = either title rating or title release year Parameters ---------- line : String type A line from the inp...
#!/usr/bin/env python2 # task5/mapper.py import sys from collections import defaultdict earliestYear = sys.maxint latestYear = -sys.maxint -1 def map_function(line): """For a given record emit its release year Parameters ---------- line : String type A line from the input stream Returns ...
#Gabriel Daniels #PSID: 1856516 # Prompt the user for the number of cups of lemon juice, water, and agave nectar needed to make lemonade. # Prompt the user to specify the number of servings the recipe yields. Output the ingredients and serving size lemoncups = float(input('Enter amount of lemon juice (in cups):''\n...
# Gabriel Daniels # PSID 1856516 class ItemToPurchase: # Parameter Constructor def __init__(self, item_name='none', item_price=0, item_quantity=0, item_description='none'): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity self...
### hazf anasor tekrari list ### def hazfetekrari(classlist): new = [] for ozv in classlist: if ozv not in new: new.append(ozv) return new classlist= ["amin", "reza", "meysam", "mahnaz", "reza", "paniz", "farokh", "mobina",\ "reza", "darya", "paniz", "reza", "paniz"] print(classlist) ...
nombres = input("Introduce 3 nombres: ") nombres_separados = nombres.split(" ") for nombre in nombres_separados: print(nombre)
import random import numpy as np import matplotlib.pyplot as plt import histogram from dispersion import dispersion, centralMoment, neprdispersion, varianceTheoria def even (a,b,sum,wx): h =np.sum(sum) / len(sum) wy = [] for i in range (len(wx)): wy.append((1/(b-a))+h) plt.plot (wx,wy,color ...
class Loop: def __init__(self, x=0): self.x = x def forloop(self): i = 0 for i in range(0,10): print(self.x) self.x += 1 i = i+1 if __name__ == "__main__": f = Loop() f.forloop()
print("Программа которая показывает предыдущие и следуещие число введеного") print("Введите число: ") a = int(input()) b = a+1 c = a-1 print("The next number for the number",a,"is",b ) print("The previous number for the number",a,"is",c)
from datetime import date from enum import Enum from math import atan, degrees class Direction(Enum): NORTH = 1 EAST = 2 WEST = 3 SOUTH = 4 UP = 5 DOWN = 6 class GridSquare: def __init__(self): self.x: str = "" self.y: str = "" self.height: int = 0 self.speed: float = 0.0 self.bearing: float = 0.0 ...
class BankAccount: def __init__(self, account_name, interest_rate, balance = 0): self.name = account_name self.int_rate = interest_rate self.bal = balance def deposit(self, amount): self.bal += amount return self def withdraw(self, amount): self.bal -= amoun...
import random def randInt(min= 0 , max= 100 ): if min < max: num = round(random.random() * (max-min) + min) return num else: print("specify a minimum value that is less than the maximum value that you specified (or the default of 100) \n \ or a maximum value that is gre...
# https://projecteuler.net/problem=1 # Multiples of 3 and 5 def sumOf3or5Multiples(max): sum = 0 for number in range(3, max): if number % 3 == 0 or number % 5 == 0: sum += number return sum # print sumOf3or5Multiples(10) # print sumOf3or5Multiples(100) print sumOf3or5Multiples(1000) ...
# https://projecteuler.net/problem=9 # Special Pythagorean triplet # parameter represents the sum of the triplets # using the formula for generating pythagorean triplets: a = m^2 - n^2, b = 2mn, c = m^2 + n^2 def find_pythagorean_triplets(sum): for n in range(sum + 1): for m in range(n, sum + 1): # if inv...
print("""********************************************************** * Blackjack35 Sıcaklık Çevirici * * İşlemler; * * 1-Celcius to Fahrenheit * * 2-Celcius to Kelvin * * 3-...
# 98 Validate Binary Search Tree # I-DFS class Solution(object): def ValidateBST(self, root): """ : type root : TreeNode : rtype : bool """ pre = [None] return self.dfs(root, pre) def dfs(self, root, pre): if not root: return True i...
import os from nick import create_nick def user_exist(nickname): # should raise error if user exist # testa try: with open('usernicks.csv') as usernicksfile: for row in usernicksfile.readlines(): # split line on "," user = row.strip().split(',') ...
'''Following Links in Python In this assignment you will write a Python program that expands on http://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position relative to ...
lista_elementos_1 = ["Douglas", "Anderson", "Libório", "Maicon", "Prefeito Géri"] lista_elementos_2 = ["Douglas", "Maicon", "Libório"] lista_diferenca = [item for item in lista_elementos_1 if item not in lista_elementos_2] print(lista_diferenca)
from flask import Flask, render_template, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import datetime """ __name__ is set to the name of the current class, function, method, descriptor, or generator instance. Python assigns the name "__main__" to the script when the script is execut...
import math def quickSort(array, p, r): if p<r: q=partition(array,p,r) quickSort(array,p,q-1) quickSort(array,q+1,r) def partition(array,p,r): x=array[r] i=p-1 for j in range(p,r): if array[j]>=x: i=i+1 temp=array[i] ...
from linked_list import MyList, ListNode class MyQueue: def __init__(self): self.items = MyList() def length(self): return self.items.__len__() def isEmpty(self): if self.length() == 0: return True return False def enqueue(self, item): i = ListNode...
import pygame class DrawableButton(): color = None hovering = False pressed = False def __init__(self, color, game, rect=None): self.color = color self.rect = rect self.game = game def draw(self, screen): if (self.hovering and not self.pressed): color ...
# forme générale if (une condition ici): # ... # des instructions ici # ... else: # ... # des instructions ici # ... # affichage si un test est vrai temperature = 28 if temperature>25: print('il fait chaud !') # affichages distincts selon un test temperature = 28 if temper...
fname = input('File name: ') try: fhand = open(fname) except: print('There is an exception.') exit() count = 0 for line in fhand: if not line.startswith('From'): continue count = count + 1 words = line.split() print(words[1]) print('There is ', count, ' From lines.')
import re hand = open('mbox1.txt') for line in hand: line = line.rstrip() #start with a single lowercase letter, uppercase letter, or number [a-zA-Z0-9] #follow by zero or non blank characters \S* #follow by an uppercase or lowercase letter x = re.findall('[a-zA-Z0-9]\S+@\S+[a-zA-Z]', line) if ...
fname = input('Enter a file name: ') try: fhand = open(fname) except: print('Fail to open ', fname) exit() eaddr = dict() for line in fhand: if not line.startswith('From'): continue words = line.split() if words[1] not in eaddr: eaddr[words[1]] = 1 else: eaddr[words[1]] += 1...
# program to find Fibonacci number series number = raw_input("Enter quantity of number:") p = 0 q = 1 # print p # print q for s in range(int(number)): r = p + q print r p = q q = r
'#class calculator' def add(a, b): "this function adds two numbers" return a + b def subtract(a, b): "this function subtracts two numbers" return a - b def multiply(a, b): "this function multiplies two numbers" return a * b def divide(a, b): "this function divides two numbers" return a / b print ("sel...
#%% # the process of classifying words into their parts of speech - part-of-speech tagging, POS-tagging # using a tagger import nltk from nltk import word_tokenize # POS tagger attaches a part of speech tag to each word text = word_tokenize('And now for something completely different') nltk.pos_tag(text) # CC - coordin...
from sklearn import datasets import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split digits = datasets.load_digits() print(digits.keys()) print(digits.DESCR) print(digits.images.shape) print(digits.data.shape) plt.imshow(digits.images...
import numpy as np from scipy.linalg import toeplitz def simu_data(n, p, rho=0.25, snr=2.0, sparsity=0.06, effect=1.0, seed=None): """Function to simulate data follow an autoregressive structure with Toeplitz covariance matrix Parameters ---------- n : int number of observations p : i...
def encryption(word,mpass): key = mpass[0] + mpass[-1] + mpass[3] + mpass[2] word_array = [] key_array = [] for c in word: word_array.append(ord(c)) for c in key: key_array.append(ord(c)) j = 0 for i in range(len(word_array)): if i%2 == 1: word_array[i] += key_array[j] if word...
class swingline(object): # Class definition def __init__(self, finalAngle,pix,pct=0.8,startAngle=-90,strokeColor=200): # Object constructor self.finalAngle = finalAngle self.pix = pix self.currentAngle = float(startAngle) self.easing = 0.02 self.pctDraw = pct self.s...
#Bill late payment #For 5 months (12% extra bill on current bill) starting bill is 6565 current_bill = 6565 extra_charges = 0 for i in range(1,6): extra_charges = (12/100) * current_bill current_bill += extra_charges print("Your current bill is {} with extra charges {} for late bill payment".format(round(current_...
#2 string metodu, 2 liste metodu ve 1 döngü #işlemin sonucu return #çok mantıklı bir fonksiyon olmasada ödev kurallarına uygun return eden bir fonksiyon def fonksiyon(): liste = ["ibrahim","ali","veli","ayşe","mehmet"] notlar = [100,75,50,60,0] liste_copy = liste.copy() #list method for i in range(0,l...
# Dependencies import csv import os # dir() : will return all the functions available in the csv module. #print(dir(csv)) # 1. Open the data file. ## Assign a variable for the file to load and the path. file_to_load_path = os.path.join("Resources", "election_results.csv") # print(f""" # file_to_load_path: # {file_to...
#! /usr/bin/env python # from fenics import * def poisson(): #*****************************************************************************80 # ## poisson solves the Poisson problem on the unit square. # # Discussion: # # Del^2 U = - 6 in Omega # U(dOmega) = Uexact(...
#! /usr/bin/env python # from fenics import * def poisson_nonlinear(): #*****************************************************************************80 # ## poisson_nonlinear solves the nonlinear Poisson problem on the unit square. # # Discussion: # # - div( ( 1 + u^2 ) grad(u) ) = x ...
# https://www.codewars.com/kata/help-mrs-jefferson/train/python def shortest_arrang(n): student_range = reversed(range(n)) return student_range print shortest_arrang(10)#,[4, 3, 2, 1]) print shortest_arrang(14)#,[5, 4, 3, 2]) print shortest_arrang(16)#,[-1]) print shortest_arrang(22)#,[7, 6, 5, 4]) print sho...
# https://www.codewars.com/kata/find-the-middle-element/train/python def gimme(input_array): return input_array.index(sorted(input_array)[1]) print gimme([2, 3, 1])
# https://www.codewars.com/kata/square-n-sum/train/python def square_sum(numbers): sum = 0 for i in numbers: sum += i*i return sum print square_sum([1,2]) print square_sum([0, 3, 4, 5])
# https://www.codewars.com/kata/opposite-number/train/python def opposite(number): if number < 0: return abs(number) else: return number - number - number print opposite(1) #,-1)
import sys import os def sort_quick(nums): if len(nums) == 1: return nums if nums == sorted(nums): return nums pivot = nums[len(nums)-1] leftpart,rightpart = partition(nums,pivot) return sort_quick(leftpart) + [pivot] + sort_quick(rightpart) def partition(arr,pivot): left_part = [] right_part = [] for i ...
#!/usr/bin/env python """ Coder: max.zhang Date: 2015-01-29 Desc: classes of hierarchical nodes """ class BaseNode(object): """ Desc: Base class of Node Data: _id|int: id _name|str: name """ def __init__(self, node_idx, node_str): self._id = node_idx self._name...
#นายพงศภัค ฟุ้งทวีวงศ์ 6310301020 #นายชวัลวิทย์ วงศ์สงวน 6310301024 #นายพัชรพงษ์ สุทธิยุทธ์ 6310301026 #Github : https://github.com/pongsapak-ton/movieticketsystem import tkinter as tk from tkinter import * import tkinter.font from tkinter.ttk import * from select import * from login import * from movie...
#!/usr/bin/python3 import simplytaxi import premiumtaxi import reg from taxilist import taxiList print("\nWelcome to the new system of Tax Hippokampoi") print("Terminal: Buenavista #2 Shopping Mall\n\n") while True: if len(taxiList) <= 10: print("Please request more Taxis to this location\n") print("Pl...
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 09:59:27 2020 """ def fizzbuzzNumber(number): """ Prüft für eine Zahl, ob Sie durch 3 und oder 5 teilbar ist. Parameters ---------- number : int Die zu prüfende Zahl Returns ------- 'Fizz', wenn number durch 3 teilbar 'Buz...
#!/usr/bin/env python3 import BlackJack_Main as main import print_functions as pf def Game(): #_StartValues endgame=False Deck=[2,3,4,5,6,7,8,9,10,'J','Q','K','A']*4 dealer_hand=[] player_hand=[] print(f'You have {Credits["bank"]}$') #_place bet while True: bet_input=input('place bet: ') if not bet_i...
class Room(): """ The Room class represents one room and is initialized by passing a room name. Stores all created rooms in a list 'Room.rooms'. """ rooms = [] def __init__(self, room_name): """ Creates a Room object which connect other classes in the game. Args: ...
hello_str = 'hello world' # 1. 判断是否以指定字符串开始 print(hello_str.startswith('Hello')) # 2. 判断是否以指定字符串结束 print(hello_str.endswith('world')) # 3. 查找指定字符串 # index 同样可以查找指定的字符串在大字符串中的索引 # index 如果指定的字符串不存在,会报错 # find 如果指定的字符串不存在,会返回-1 print(hello_str.find('llo')) print(hello_str.find('abc')) # 返回 -1 # 4. 替换字符串 # replace 方法...
i = 0 while i < 10: # continue 某一条件满足时,不执行后续重复的代码,跳转到循环开始的条件判断 # i == 3 if i == 3: # 注意:在循环中,如果使用 continue 关键字 # 在使用关键字之前,需要确认循环的计数是否修改 # 否则可能会导致死循环 i += 1 continue print(i) i += 1
def binary_search1(li, item): """递归版本:二分查找""" n = len(li) if n > 0: mid = n // 2 if li[mid] == item: return True elif item < li[mid]: return binary_search1(li[:mid], item) else: return binary_search1(li[mid + 1:], item) else: re...
# 多值参数又叫可变长参数 def demo(num, *nums, **person): print(num) print(nums) print(person) # demo(1) # demo(1, 2, 3, 4) demo(1, 2, 3, 4, 5, name='小明', age=18)
# print triples of lines import sys import json class Triple: def __init__(self): self.triple = [] def push(self, line): if len(self.triple) == 3: self.pop() self.triple.append(line) def pop(self): if len(self.triple) > 0: json.dump(self.triple, sy...
import numpy as np import math import matplotlib as mpl import matplotlib.pyplot as plt t = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] y = [6.80, 3.00, 1.50, 0.75, 0.48, 0.25, 0.20, 0.15] x1 = t y1 = y # (a) # Assume some initial values for x1 & x2 and then apply gradient descent xA = [0, 0] def computeJ(x1, x2, t, y...
# 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 mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: result = TreeNode() if r...
class Solution: def thirdMax(self, nums: List[int]) -> int: nums.sort(reverse = True) unique = [] while len(nums) > 0: var = nums.pop(0) if var not in unique: unique.append(var) if len(unique) == 3: return unique[2] ...
# Peter wants to generate some prime numbers for his cryptosystem. # Help him! Your task is to generate all prime numbers between # two given numbers! #Input #The input begins with the number t of test cases in a single line (t<=10). # In each of the next t lines there are two numbers m and n # (1 <= m <= n <= 10000...
#Hemisphere Network is the largest television network in Tumbolia, # a small country located east of South America (or south of East America). # The most popular sport in Tumbolia, unsurprisingly, is soccer; # many games are broadcast every week in Tumbolia. #Hemisphere Network receives many requests to replay dubi...
#7) Определить количество разрядов числа #Написать функцию, которая определяет количество разрядов введенного целого #числа """def digits(n): i = 0 while n > 0: n = n//10 i += 1 return i num = abs(int(input('Введите число: '))) print('Количество разрядов:', digits(num))""" def func(): ...
# 5.11 break문없이 재작성 sum = 0 number = 0 while sum <= 100: number += 1 sum += number print("마지막 숫자는", number,"입니다.") print("합계는", sum,"입니다.") # 5.12 continue문 없이 재작성 sum = 0 number = 0 while number < 20: number += 1 if number == 10 or number == 11: sum = sum else: su...
def max(num1, num2): result = num1 if (num1 > num2) else num2 return result def main(): i = 5 j = 2 k = max(i, j) print(i,"와/과", j, "중에서 큰 수는", k, "입니다.") main()
score = eval(input("Input your score: ")) pay = eval(input("Input your pay: ")) if score > 90: afterPay = pay * (1 + 0.03) else: afterPay = pay * (1 + 0.01) print("afterPay: ",afterPay)
""" To classify the input skin into one of the 6 skin tones """ import pandas as pd from sklearn.neighbors import KNeighborsClassifier def skin_tone_knn(mean_values): # df = pd.read_csv("public\pre-processing\skin_tone_dataset_RGB.csv") df = pd.read_csv("public\skin_tone_dataset.csv") X = df.iloc[:, [1, ...
# -*- coding: utf-8 -*- """ Created on Tue Sep 11 18:52:15 2018 @author: admin Problem Statement: In this assignment students will build the random forest model after normalizing the variable to house pricing from boston data set. """ import numpy as np import pandas as pd import matplotlib.pyplot as pl...
import re def is_pangram(given: str) -> bool: temp = re.sub(r'[^a-zA-Z]', '', given).lower() return len(set(temp)) == 26
import functools from typing import List def is_prime(knowns: List[int], num: int) -> bool: return 0 == len([k for k in knowns if k <= num and num%k == 0]) def memoize(func): cache = func.cache = {} @functools.wraps(func) def memoized_func(*args, **kwargs): key = str(args) + str(kwargs) ...
import re from itertools import groupby def decode(given: str) -> str: numbers = (int(n) if n else 1 for n in re.split('\D', given)) letters = ''.join(n for n in re.split('\d', given) if n) return ''.join(number*letter for number,letter in zip(numbers,letters)) def encode(given: str) -> str: code = '...
def flatten(nested_list): ## type hinting here can be interesting def helper(): for item in nested_list: if isinstance(item, (list, tuple)): for subitem in flatten(item): yield subitem elif item is not None: yield item return li...
import numpy as np #reversing an array normally using reverse method arr = [1,2,3,4,5] arr.reverse() print(arr) #reversing an array using reversed method arr1=[1,2,3,4,5,6,7,8,9,10] print(list(reversed(arr1))) #reversing using flip method in numpy arr2=np.array(['p','r','a','b','h','a','s','a','l','e','t','i']...
def binary_search(my_list,target): left=0 right=len(my_list)-1 while left<=right: middle=(left+right)//2 if target==my_list[middle]: return middle elif target>=my_list[middle]: left=middle+1 else: right=middle-1 return -1 ...
# -*- coding: utf-8 -*- ''' Задание 6.1b Сделать копию скрипта задания 6.1a. Дополнить скрипт: Если адрес был введен неправильно, запросить адрес снова. Ограничение: Все задания надо выполнять используя только пройденные темы. ''' #Solution address_correct = False while not address_correct: IP_address = input("E...
map = {"miles": 1, "meters": 1609.34, "yards": 1760 } def convert(fromUnit, toUnit, value): if fromUnit == "miles" and toUnit == "yards": result = value * 1760 return result elif fromUnit == "miles" and toUnit == "meters": result = value * 1609.344 return ...
''' n개의 자연수 입력 각 자연수를 뒤집은 후 그 뒤집은 수가 소수이면 그 뒤집은 수를 출력 뒤집는 함수 reverse(x) 소수인지 확인하는 함수 isPrime(x) ''' import sys # sys.stdin = open("input.txt", "rt") def reverse(x): result = 0 while x > 0: n = x%10 x = x//10 result = result*10 + n return result def isPrime(x): if ...
def sum_weight(beep_weight,bop_weight): total_weight=beep_weight+bop_weight return total_weight def calc_avg_weight(beep_weight,bop_weight): avg_weight=(beep_weight+bop_weight)/2 return avg_weight def run(): beep_weight=int(input("What is the weight of Beep?")) bop_weight=int(input("What i...
answer=input("What happens when the last petal falls?\n") print("My dear Bella when the last petal falls "+ answer)