text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-07 16:21:14 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def findTheLongestSubstring(self, s): length = len(s) vowel = {'a':0,'e':0,'i':0,'o':0,'u':0} ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-14 18:04:48 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def letterCasePermutation(self, S): """ :type S: str :rtype: List[str] """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-07 06:28:39 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import re class Solution: def isValid(self, s: str) -> bool: if len(s) & 1 == 1: return False # 判断是否存在非法的输入 pa1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-13 09:27:23 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-13 15:09:08 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def smallestK(self, arr, k): """ :type arr: List[int] :type k: int :rtype: Lis...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-11 06:51:38 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(): def search(self, nums, target): if not nums: return -1 left = 0 right = len(nums) - 1...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-12-21 08:07:01 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution: def findMin(self, nums): if not nums: return None left = 0 right = len(nums) - 1 if nums[left] < nums[right]: r...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-02-20 06:30:19 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return any...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-05 20:42:24 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def findContinuousSequence(self, target): # 使用滑动窗口进行求解 # 在任意时间段,滑动窗口的左右边界都只能向右移动 if target ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-11 17:51:43 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: None Do n...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-24 19:53:42 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def surfaceArea(self, grid): if not grid: return 0 surface = 0 def neig...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-11-16 08:11:19 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution: def insert(self, intervals, newInterval): if not intervals: return [newInterval] cur = 0 length = len(intervals) an...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-13 09:09:19 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ class Twitter: class Node: def __init__(self): self.twit = [] self.followee = set() def __init__(self): ...
# 1. CSV files are just plain text files! # Open logger.csv using our standard with syntax, saving the file object in the temporary variable log_csv_file. # 2.Print out the contents of logger.csv by calling .read() on the file. Notice that it is parsed as a string. with open("logger.csv") as log_csv_file: print(l...
# 1. We’re doing a little bit of online shopping and find a pair of new sneakers. Right before we check out, we spot a nice sweater and some fun books we also want to purchase! # Use the += operator to update the total_price to include the prices of nice_sweater and fun_books. # The prices (also included in the works...
# 1. Our school is expanding! We are welcoming a new set of students today from all over the world. # Using the provided table, create a two-dimensional list called incoming_class to represent the data. Each sublist in incoming_class should contain the name, nationality, and grade for a single student. # Name Na...
# 1.You’re a programmer working for an organization that is trying to digitize and store poetry called Preserve the Verse. # You’ve been given two strings, the title of a poem and it’s author, and have been asked to reformat them slightly to fit the conventions of the organization’s database. # Make poem_title have tit...
# 1. Determine if the following statements are boolean expressions or not. If they are, set the matching variable to the right to "Yes" and if not set the variable to "No". Here’s an example of what to do: # Example statement: # My dog is the cutest dog in the world. # This is an opinion and not a boolean expression,...
# 1.In the code editor is a string of the first line of the poem Spring Storm by William Carlos Williams. # Use .split() to create a list called line_one_words that contains each word in this line of poetry. line_one = "The sky has given over" line_one_words = line_one.split() # 1.Your boss at the Poetry organizati...
# 1.Define a class Student this will be our data model at Jan van Eyck High School and Conservatory. # 2.Add a constructor for Student. Have the constructor take in two parameters: a name and a year. Save those two as attributes .name and .year. # 3.Create three instances of the Student class: # Roger van der Weyden,...
# 1. Set the variables statement_one and statement_two equal to the results of the following boolean expressions: # Statement one: not (4 + 5 <= 9) # Statement two: not (8 * 2) != 20 - 4 # 2. The registrar’s office at Calvin Coolidge’s Cool College has been so impressed with your work so far that they have another ta...
# 1. Set the variables statement_one and statement_two equal to the results of the following boolean expressions: # Statement one: (2 + 2 + 2 >= 6) and (-1 * -1 < 0) # Statement two: (4 * 2 <= 8) and (7 - 1 == 6) # 2. Let’s return to Calvin Coolidge’s Cool College. 120 credits aren’t the only graduation requirement, ...
# 1. Use square brackets ([ and ]) to select the 4th employee from the list employees. Save it to the variable employee_four. # 2. Paste the following code into script.py: # print(employees[8]) # What happens? Why? # 3. Selecting an element that does not exist produces an IndexError. # In the line of code that yo...
# 1. Jiho works for a gardening store called Petal Power. Jiho keeps a record of orders in a list called orders. # Use print to inspect the orders he has received today. # 2. Jiho just received a new order for "tulips". Use append to add this string to orders. # 3. Another order has come in! Use append to add "rose...
# 1.A new addition to our painting application that we are building for Jiho will be a function that calculates the amount of paint needed to cover a surface. # Typically, a gallon of paint can cover about 400 square feet. Using that knowledge, we can accept a width and height of a surface to determine how much paint i...
# 1.You have a list of dog breeds you can adopt, dog_breeds_available_for_adoption. # Using a for loop, iterate through the dog_breeds_available_for_adoption list and print() out each dog breed. # Use the <temporary variable> name of dog_breed in your loop decleration. # 2.Inside your for loop, after you print each do...
# 1.In your workspace we’ve put dictionary called data_payload. We want to save this to a file called data.json. # Let’s start by importing the json library. # 2.Open a new file object in the variable data_json. The filename should be 'data.json' and the file should be opened in write-mode. # 3.Call json.dump() with ...
# 1.Use a for loop to iterate through the items of pct_women_in_occupation. For each key : value pair, print out a string that looks like: # Women make up [value] percent of [key]s. pct_women_in_occupation = {"CEO": 28, "Engineering Manager": 9, "Pharmacist": 58, "Physician": 40, "Lawyer": 3...
# Say we stored our course grades in a list, but some of the grades were on a four-point scale and others were on a 100-point scale. To get all the grades on the same scale, try using a lambda function with the map() function to multiply just the grades on the four-point scale by 25 to get all of the grades on the same...
# 1.Use a try block to try to print the caffeine level of "matcha". If there is a KeyError, print "Unknown Caffeine Level". # 2.Above the try block, add "matcha" to the dictionary with a value of 30. caffeine_level = {"espresso": 64, "chai": 40, "decaf": 0, "drip": 120, "matcha": 30} try: print...
seconds = int(input("Enter seconds: ")) minutes = int(input("Enter minutes: ")) conversion = seconds * minutes print("conversion of minutes to seconds: ",conversion)
add_number = lambda a, b: a + b multiply_numbers = lambda a, b: a * b divide_numbers = lambda a, b: a / b print_my_name = lambda name: name.upper() name_list = ["Vári Róbert", "Kiss Elemér", "Nagy Adrienn", "Tóth Barna"] print(sorted(name_list)) print(sorted(name_list, key=lambda name: name.split()[-1]))
from Student import Student class Classroom(object): def __init__(self, name, class_day, roster): self.name = name self.class_day = class_day self.roster = roster self.assignments = {} def add_student(self, student_name): if student_name in self.roster: p...
import random import sys class RandomGenerator(object): """Wrapper class for a random generator.""" def __init__(self, range, generator_factory): """ range: desired range of random integers, i.e., [0, range) generator_factory: when passed 'range', return a generator that emits a st...
""" 以下图为例: A / ^ \ 6 / | \ 1 / | \ start 3 end \ | / 2 \ | / 5 \ | / B 说明:start(起点) 指向 A 和 B,A 和 B 指向 end(终点),B 指向 A """ # 构建图 gra...
class Tree(object): def __init__(self, data1=None, data2=None, data3=None, parent=None): self.left = None self.right = None self.data1 = data1 self.data2 = data2 self.data3 = data3 self.data = [data1, data2, data3] self.parent = parent def data_len(self):...
n=int(input("Enter number of Transactions")) #n is the number of transactions total=0 while n!=0: str =input("Type of Transaction:") t = str.split(" ") # type is to determine whether it's a deposit or withdrawal type = t[0] # amt is the amount of money deposited or withdrawn amt = int(t[1]) ...
''' f(i) = f(i-1) + f(i-2) k = 2 Nao se esquercer dos termos ausentes f(i) = f(i-2) + f(i-4) f(i) = 0f(i-1) + f(i-2) + 0f(i-3) + f(i-4) k = 4 ''' # fn(n) 2fn(n-1) - fn(n-2) def fn(n): if n == 0: return 0 elif n == 1: return 3 else: return 2 * fn(n - 1) - fn(n - 2) def multiplic...
''' https://www.hackerrank.com/challenges/eulers-criterion/problem https://en.wikipedia.org/wiki/Euler%27s_criterion ''' def v1(b, e): copy_b = 1 while e > 1: if (e & 1) == 0: b *= b e >>= 1 else: copy_b *= b b *= b e = (e - 1) >> 1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ## Title: ## Description: ## Author:uillaume Gay<elagachado AT gmail DOT com> ## Commentary: def fwhm(wave): ''' Returns full width at half maximum ''' m = wave.max() x = wave.argmax() right = left = nan wave /= m for i in ran...
from default.hangman import Hangman def main(): # Create Hangman game game = Hangman("words.txt") # Welcome Message for user print """Welcome, user, to the exciting game that is Hangman! We have randomly selected a word from a text file for you to try and guess. Good luck and have fun!""" # Begin ...
if __name__ == '__main__': s = raw_input() u=0 l=0 d=0 an=0 a=0 for i in s: if i.isupper()==True: u+=1 if i.islower()==True: l+=1 if i.isdigit()==True: d+=1 if i.isalpha()==True: a+=1 if i...
def show(card): for string in card: print(" ".join(string)) def count_ways(card, x, y): ans = 0 if card[x][y + 1] == 0: ans += 1 if card[x][y - 1] == 0: ans += 1 if card[x + 1][y] == 0: ans += 1 if card[x - 1][y] == 0: ans += 1 return ans def maze2...
import time class MeasureTime(object): """Decorator object.""" def __init__(self, *args): self.args = args def __call__(self, fn): def wrapped_fn(*fn_args): start = time.time() res = fn(*fn_args) elapsed = time.time() - start print fn._...
names1 = ["Steven", "Dennis", "Adrian", "Jerico", "Steven"] ages1 = [5, 2, 3, 10, 5] names2 = ["Juan", "Carlos", "Ramiro", "Camila", "Carla"] ages2 = [1, 3,5,2,4] names_with_ages = zip(ages1, ages2) for student in names_with_ages: mult = student[0]*student[1] print(mult)
''' Testing parser: simple arithmatic parser ''' from lex import * class ParseError(Exception):pass class Parser: def __init__(self, lexer): self.lexer = lexer self.lookahead = self.lexer.token() self.value_stack = [] def match(self, name): if self.lookahead.name == name: ...
import math """ Girilen sayının asal olup/olmadığını bulan,eğer asal değilse çarpanlarını ekrana basan fonksiyon.""" def prime_numbers(x): list=[] list_asal=[1,x] count=False for i in range(2,int(x/2)): if(x%i == 0): list.append(i) count = True if(count == True): ...
""" Alınan text dosyasının kelimlerinin frekansının bulunması.""" class myclass(): def __init__(self): f = open("dosya.txt", "r") mycontent = f.read() mysentences = mycontent.split(".") self.mywords = [] for sentence in mysentences: words_in_the_sentence = senten...
def main(): n = eval(input( "Please give me a number: ")) product = 1 for i in range (1,n+1): product = product * i print("The product of the first", n, "positive integers is", product) main()
import os from sys import exit import roomdesc clear = lambda: os.system('cls' if os.name=='nt' else 'clear') player_inv = [] def starter(): clear() print(roomdesc.startroom) print("\n[check] what's happening. Do [nothing]\n") choice = input("> ") if "check" in choice: ...
""" Write a function that takes in an array of unique integers and returns its powerset. Complexity: Space: O(n*2^n) | Time: O(n*2^n) """ def powerset(array): res = [[]] for num in array: #Add subsets before the actual number for i in range(len(res)): currentSubset = res[i] ...
class robot_xy(object): """description of class""" def __init__(self,x_pos,y_pos,angle): self.x_pos = x_pos self.y_pos = y_pos self.angle = angle def position(self): return '{}|{}|{}'.format(self.x_pos, self.y_pos, self.angle) def set_x(self, x_pos): self.x_po...
# # ################################ # # # DAY21 # # ################################ # # numpy is a package specialised in multi dimensional array # # # # import numpy as np # # from numpy import * # # # # arr01 = {i, [2,3,4,5]} # # arr02 = array([2, 3, 4, 5], int) # # print(arr02) # # import numpy as np # print(np.__...
import random number = random.randint(1, 9) chanceCount = 0 while (chanceCount < 5): introString = int(input("Enter a number between 1 and 9: ")) if (introString > number): print("Your guess was too large") elif (introString == number): print("Congratulation! You guessed it correct."...
def var_dump(var, startspace : int=0): """Dumps information about a variable This function displays structured information about a variable that includes its type and value. Lists and dictionaries are explored recursively with values indented to show structure. Parameters ---------- var : any The variable to...
num = int(input("enter the number of starts:")) for i in range(num): print("*", end=' ')
# 90~100은 A, 80~89점은 B, 70~79점은 C, 60~69점은 D, 나머지 점수는 F score = int(input()) if score >= 90 and score <= 100: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F") # if 90<=score<=100: # print("A") # elif 80<=score<=89: # print("B...
from api import api from Sudoku import Sudoku ############################################## class Interfaz(): def ingresar_tamaño_tablero(self):#se ingresa el tamaño del tablero self.tamaño = 0 while self.tamaño != "9" and self.tamaño != "4": self.tamaño = input("Ingrese el tamaño ...
class Person(object): def __init__(self, first_name, last_name, father): self.first_name = first_name self.last_name = last_name self.father = father person_a = Person("User", "1", None) person_b = Person("User", "2", person_a) a = { "key1": 1, "key2": { "key3": 1, "key4": {"key5": 4,"user": person_b}}} def pr...
# i= 1 # while i<=10: # print("ejecucion " + str(i)) # i=i+1 # print("termino la ejecucion") # edad= int(input("intruduce tu edad: ")) # while edad<5 or edad>100: # print("has introducido na edad incorrcta. vuelve a intearlo") # edad=int(input("introduce tu edad: ")) # print("gr...
#ejercicio 1 # n1=int(input("introduce un numero: ")) # n2=int(input("introduce un numero mayor que " + str(n1)+ ": ")) # while n2>n1: # n1=n2 # n2=int(input("este numero es mayor que " + str(n1)+ ": ")) # print() # print(n2, "no es mayor que",str(n1)) #ejercicio 2 numero=int(input("ingresa...
demon_list = [1, "HELLO", 2, True,[1, 2,3]] colors = ["red","green","blue"] #numbers_list= list((1,2,3)) #print(type(numbers_list)) #r = list(range(1,100)) #print(r) #print(colors[0]) #print("green" in colors) #print(colors) #colors[1]= "yellow" #print(dir(colors)) #colors.extend(["violet","yellow"])...
class TikTacToeOpponent(object): """a silly tiktactoe opponent""" def __init__(self): self.spotpreflist = [(0,0),(0,2),(2,2), (2,0),(1,1),(1,2), (1,0),(2,1),(0,1)]; self.mark = -1 def takeTurn(self,game): '''selects it's favorite available spot and returns that position''' #print game.empty #check for p...
import math while True: num = int(input("Enter the number to check number is prime is not :\n")) if num >= 2: for i in range(2, num//2): if (num % 2) == 0: print(f"Given number is not a prime number :{num}") break else: print(f"Give...
import sqlite3 from datetime import datetime import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mtick pd.set_option('display.max_rows', None) DATABASE = "stocks.db" def get_data(table="stocks"): """ Retrieve the data from the database """ conn = sqlite3.connect(DATABASE) ...
#!/usr/bin/python print "<html><head>" print "</head><body>" # import module for getting day import datetime # import module for connecting to mysql import mysql.connector cnx = mysql.connector.connect(user='root', database='delta') cursor = cnx.cursor() # Gives the number of messages able to send for the day # Nece...
# Assignment Number... : 6 # Student Name........ : 허현 # File Name........... : hw6_허현 # Program Description..: 함수를 활용하는 과제 # 1 ## a def area_triangle(h, w): # 각 인자를 h와 w로 설정 ## b return 0.5*h*w # 삼각형을 구하는 공식 적용 ## c my_tri = area_triangle(10, 15) # 함수 활용 print(my_tri) # 2 ## a def distance(a, b): square_sum...
# Assignment Number... : 1 # Student Name........ : 허 # File Name........... : hw1_허현 # Program Description..: 자료형 활용하는 과제 # 1 season = input("What is your favorite season?") # season을 출력하기 위해 할당했다 print(season) # 2 date1 = input("Which date were you born?") # date변수는 위험할 수 있어서 date1으로 지정했다 print(date1) # 3 print(...
def func(a,b=5,c=10): print('a is ',a , 'and b is ',b , 'and c is ',c) func(3,7) func(25, c=24) func(c=50, a = 100) # print_out # a is 3 and b is 7 and c is 10 # a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 def maximum(x,y): if x>y: return x elif x==y: return 'Th...
# -*- coding: utf-8 -*- s1 = 72 s2 = 85 r = s1/s2 name = 'xiaoming' print('%s\'s score improves %.2f %%'%(name,r)) print('%2d-%2d' % (3, 1)) print('%.2f' % 3.1415926) # %.2f 意思是两个小数点,有一个period classmates = ['Michael', 'Bob', 'Tracy'] classmates.append('Adem') #后面加element print(classmates) classmates.insert(1,'Jac...
import datetime class Person(object): def __init__(self,name): """ Create a person called name """ self.name= name self.birthday= None self.lastname= name.split(' ')[-1] def getLastname(self): """ return the last name of person """ ...
import math def polysum(n,s): """ input: Two arguments 'n' and 's'. 'n' stands for number of sides and 's' stands for each side length (regular polygon have same length for all sides) output: sum of the area and square of the perimeter of the regular polygon. Function returns the sum, rounded t...
""" input: input a positive integer prints the closest cube root of that number """ x=int(input("Enter value\n")) eps = 0.01 num_guess = 0 low = 1 high = x guess = (low + high)/2.0 while abs(guess**3 - x) >= eps: if guess**3 < x: low = guess else: high = guess guess = (low + high)/2.0 num_guess += 1...
N1=[] N2=[] N3=[] M1 = [1,-2,3,-6,4,2,1,3,-7,-9] M2 = [1.2,-2.2,3,-6.89,4.24,2.0,1,0.3,-7.0,-9.5] for i in map(abs, M1): N1.append(i) print("List") print(M1) print("Is now changed after \"abs\" function into:") print(N1) print("\n\n\n") for i in map(int,M2): N2.append(i) print("List") print(M2) print("Is now chang...
import string exclude = set(string.punctuation) def remove_punctuation(x): x = ''.join(ch for ch in x if ch not in exclude) return x # # 原df # Out[26]: # a b # 0 c,d edc.rc # 1 3 3 # 2 d ef 4 # # # 过滤a列标点 # In [27]: df.a = df.a.apply(remove_punctuation) # In [28]: df # Out[28]: ...
def string_se_arithmo(): keimeno = input("Δώστε string: ") string = str(keimeno) noumeroASCII = ''.join(str(ord(c)) for c in string) noumeroASCII2=int(noumeroASCII) plhthos = 0 for i in range(1,noumeroASCII2 + 1): if (noumeroASCII2 % i == 0): plhthos = plhthos + 1 if(plhthos == ...
''' Write a script that takes a string of words and a letter from the user. Find the index of first occurrence of the letter in the string. For example: String input: hello world Letter input: o Result: 4 ''' string = input("Please enter your message: ") letter = input("Please enter your letter: ") result = string...
''' Read in 10 numbers from the user. Place all 10 numbers into an list in the order they were received. Print out the second number received, followed by the 4th, then the 6th, then the 8th, then the 10th. Then print out the 9th, 7th, 5th, 3rd, and 1st. Example input: 1,2,3,4,5,6,7,8,9,10 Example output: 2,4,6,8,10,9...
''' Write a script that sorts a dictionary into a list of tuples based on values. For example: input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [("item3", 1), ("item1", 5), ("item2", 6)] ''' input_dict = {"item1": 5, "item2": 6, "item3": 1} result_list = [] a = input_dict.items() print(a) sorted_li...
''' Write a script that takes a string of words and a symbol from the user. Replace all occurrences of the first letter with the symbol. For example: String input: more python programming please Symbol input: # Result: #ore python progra##ing please ''' string = input("Please enter your message: ") symbol = input("...
import Utils # The function’s input is a variable called points # The function will try to read the current score in the scores file, if it fails it will create a # new one and will use it to save the current score. # The function will print the user current score. def add_score(point): file = open(Utils.SCORES_FI...
__author__ = 'Oranitha' import re master_read = open('in.txt').read().split(",") master_write = open('out.csv',"w") master_write.write("General Data,Total Enemies Fought,Egg,Apparel,Vista,Ambush,Eliminate,Crate,") plain_read = master_read[::3] for row in plain_read: rowlist = row.split("(") name = re.findall('...
#Program to read data from data file in read mode and #append the words starting with letter ‘T’ #in a given file in python f=open("test.txt",'r') read=f.readlines() f.close() id=[] for ln in read: if ln.startswith("T"): id.append(ln) print(id)
#!/usr/bin/python # title :Filter.py # description :python moving average and median filter # author :Sean Tidd # date :2020-02-11 # version :0.1 # notes : # python_version :3.5 # ============================================================================== import c...
i=0 a=0 b=1 show=0 n=int(input("Type a limit:")) if(n>=2): print(a) print(b) while(i<n-2): show=a+b print(show) a=b b=show i=i+1 elif n==1: print(a) else: print("no value")
# 1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел # и строк и сохраните в переменные, выведите на экран. # name = 'Алексей' print(name) print(type(name)) time = 456 print(time) print(type(time)) v_int = input('Введите число:\n') print(v_int, type(v_in...
def purple_shell(racers): """Given a list of racers, set the first place racer (at the front of the list) to last place and vice versa. >>> r = ["Mario", "Bowser", "Luigi"] >>> purple_shell(r) >>> r ["Luigi", "Bowser", "Mario"] """ first = racers.pop(0) last = racers.pop(-1) ...
import numpy as np """ function D=l2distance(X,Z) Computes the Euclidean distance matrix. Syntax: D=l2distance(X,Z) Input: X: dxn data matrix with n vectors (columns) of dimensionality d Z: dxm data matrix with m vectors (columns) of dimensionality d Output: Matrix D of size nxm D(i,j) is the Euclidean distance o...
import numpy as np def ridge(w,xTr,yTr,lambdaa): # # INPUT: # w weight vector (default w=0) # xTr:dxn matrix (each column is an input vector) # yTr:1xn matrix (each entry is a label) # lambdaa: regression constant # # OUTPUTS: # loss = the total loss obtained with w on xTr and yTr # gradient = the gradient at w # # ...
# Author: Ali Kolenovic # This program accesses data from a twitter user site # To run in a terminal window: python3 twitter_data.py import tweepy ### PUT AUTHENTICATION KEYS HERE ### CONSUMER_KEY = "" CONSUMER_KEY_SECRET = "" ACCESS_TOKEN = "" ACCESS_TOKEN_SECRET = "" # Authentication authenticate = twee...
# Write a function is_even that will return true if the passed-in number is even. # YOUR CODE HERE # Read a number from the keyboard # num = input("Enter a number: ") # num = int(num) def is_even(number): # int(number) while True: try: if int(number) == 0: return'Is zero e...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'compareTriplets' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # def compareTriplets(a, b): puntuación_Lucia=0...
def sal(): try: time = float(input('Enter working time ')) salary = float(input('Enter salary in dollars ')) premium = float(input('Enter the premium to the salary in dollars ')) result = time * salary + premium return result # print(f'salary for an empl...
import re phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') #Groups are denoted by parentheses. You can escape parentheses if you need to find them using \ mo = phoneNumRegex.search('My phone number is 456-213-9543') print(mo.group(1)) #Gets the first group and prints it. phoneNumRegex = re.compile(r'\(\d...
print('Hello'.isalpha()) #Checks if all characters are alphabetical. print('Hello123'.isalnum()) #Checks if characters are both numeric and alphabetical. print('123'.isdecimal()) #Checks if all caharacters are numbers. print(' '.isspace()) #Checks for whitespaces. print('Hello'.istitle()) #Checks for titlecase. ...
""" Author CodePain Team Date 14/01/2021 Version 1.0.0 Saver tool """ class Saver: def __init__(self): """ This is a constructor """ self.requestLog = [] def verify(self, userId): """ This method verifies if the user exist in the list Args: ...
import matplotlib.pyplot as plt import numpy as np def blue_red_plot(x, y, ylabel: str, save: bool = False, imgname: str = None): plt.figure(figsize=(6, 4)) plt.plot(x, label='Training', c='b') plt.plot(y, label='Validation', c='r') plt.ylabel(ylabel) plt.xlabel('Iteration') plt.grid(c='k', ls...
# Dah el 2asl, calculations to predict score based on most common answer import pandas as pd import numpy as np import math data = pd.read_csv("sample.csv") #User targetted vars current_user = 0 problems_of_first_user = [] mean_of_first_user = 0 common_rating_first_user = 0 changed = False threshold1 = 0.3 threshold2...
#!/usr/bin/env python3 import json from collections import OrderedDict # Retrieving information print("Server name: ", end='', flush=True) server = input() print("IP address: ", end='') ip = input() print("User informations:\nUsername: ", end='') username = input() print("Shell: ", end='') sh = input() print("ssh_k...
def range(a, b=None, c=None): ''' This function should behave exactly like the built-in range function. For example: >>> list(range(5)) [0, 1, 2, 3, 4] >>> list(range(1, 5)) [1, 2, 3, 4] >>> list(range(1, 5, 2)) [1, 3] ''' start = 0 if b is None else a stop = a if b is ...