text
stringlengths
37
1.41M
first_name = "jhon" last_name = "smith" message = f'{first_name} {last_name} is a coder ' print(message) print(len(message)) course = "python basic course" print(course.upper()) print(course.lower()) print(course.find("c")) print(course.replace("p", "C")) print("python" in course) print("cython" in course) print(course...
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv import time with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area c...
def findmaxnum(a): max_num = a[0] for i in range(len(a) - 1): if max_num < a[i + 1]: # found a new max swap max_num = a[i + 1] return max_num a = [7, 3, 10, 5, 0] print("max num in list=", findmaxnum(a))
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members. # Often decode JSON into dictionaries # Simple dict person = { 'first_name': 'Adam', 'last_name': 'Parsons', 'age': 32 } # Simple dict using a constructor # person = dict(first_name='Adam', last_name='Parsons'...
import math import time import matplotlib.pyplot as plt # function derivative as a method of the function "f" itself def f_dashx(a,b,f,x): f_dash = a*((f*f*f*f) -b) return(f_dash) #calculation of fucntion value using euler method/ RK-1 # ivc stands for initial value condition def rk1(f_dash,ivc,ste...
import time import math #globals g = 9.81 Q = 20 def fun(g_,Q_,y): a = g_*pow(y,3) b = pow ((6+y),3) c = (3+y)*Q_*Q_ fun_val = ((a*b)/8)-c return(fun_val) def bisect_root(guess,g,Q): a= guess[0] b= guess[1] itr = 0 while(1): f_a = fun(g,Q,a) ...
#!/usr/bin/env python # read latitude and longitutde from csv file # then calculate the distance and write into new csv file # # updated to calculate the bike distance by using MapQuest api # # Last update: 2/4/2020 # Author: Injung Kim import math import csv from collections import defaultdict from pprint import ppr...
def verifica(entrada,t,v): string = "" tamanho = 0 for todos in range(t): if tamanho == (t-v): break i = str(todos+1) if i not in entrada: string+=i string+=" " tamanho+=1 return string while True: try: t,v = [int(x) fo...
N = int(input("")) fat = 1 i = 1 while i <= N: fat = fat *i i += 1 print (fat)
n = int(input()) lista = [] aux = 1 for x in range(n+1)[1::]: lista.append([x,x**2,x**3]) for x in range(n): for y in range(3): if y == 2: print(lista[x][y]) else: print(lista[x][y], end=' ')
valores = input() partes = valores.split() A = float(partes[0]) B = float(partes[1]) C = float(partes[2]) if (((abs(B-C)) < A) and (A < (B+C))) or (((abs(A-C)) < B) and (B < (A+C))) or (((abs(A-B)) < C) and (C < (A+B))): perimetro = A+B+C print("Perimetro = %0.1f" % perimetro) else: area = (A+B)*C/2 pr...
# Incorporate the random library import random # Print Title print("Let's Play Rock Paper Scissors!") # Specify the three options by defining a list options = ["r", "p", "s"] # Computer Selection computer_choice = random.choice(options) # User Selection user_choice = input("Make your Choice: (r)ock, (p)aper, (s)cissors...
''' Euler50.py ' 0.05 on a powerful machine, July 2017 ' (c) Riwaz Poudyal ''' primes = [] def isPrime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False i = 5 while(i*i <= n): if n % i == 0: return False i...
amount = int(input()) p1 = ' _~_ ' p2 = ' (o o) ' p3 = ' / V \\ ' p4 = ' /( _ )\\ ' p5 = ' ^^ ^^ ' print(p1*amount) print(p2*amount) print(p3*amount) print(p4*amount) print(p5*amount)
#is_int #An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). #For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. #This means that, for this lesson, you can't just test the input...
# TODO: redefine magic numbers as constants import pygame import random # Class for the main player class Enemy(pygame.sprite.Sprite): ''' This class is the enemy class which inherits from pygame.sprite.Sprite class ''' # Class initialization def __init__(self, enemy_img, size, game_window_x, ga...
moves = ["move1","move2",["move11","move21"]] # 导入模块 import neast neast.print_lol(moves) # def创建函数 def print_lol(the_list): for the_list_item in the_list: if isinstance(the_list_item, list): print_lol(the_list_item) else: print(the_list_item) # 函数调用 print_lol(moves) print(...
#Day 1 Report Repair #--- Day 1: Report Repair --- # After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. # Surely, Christmas will go on without you. # # The tropical island has its own currency and is entirely cash-only. The gold coins used there have a l...
print("\t\t Jurusan Sistem Informasi terdapat pada fakultas...") while True: for i in range(5): tebakan= input("Masukkan tebakan mu: ") if tebakan == "FRI": print("Jawaban Benar") break else: print("Jawaban salah") if tebakan == "FRI": ...
#lista zawierajaca liczby całkowite od 0 do 20 liczby = [] for x in range(21): liczby.append(x) print(liczby) #list comprehension #jesli chcemy uworzyc listez elementami w srodku (range, kwadraty liczb itp) #to uzywamy ponizszej składni: numerki = [x for x in range(21)] print(numerki)
file_path = "dane.txt" #try: # with open(file_path, 'r') as file: # print(file.read()) #except FileNotFoundError as e: # print("Podany plik nie istnieje!", e) #except Exception as e: # print("Uuuups, nastąpił jakiś błąd.", e) #finally: # print("Ta funkcja zawsze się wykona") try: print("To jes...
pos = {num:-num for num in range(10)} print(pos) ### A partir de una lista creo un diccionario. fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] dicFellowship = {elemento:len(elemento) for elemento in fellowship} print(dicFellowship)
# coding=utf-8 x = True print(x) print(type(x)) print(int(x)) listOfList = [["a", "b", "c"], ["d", "f"], ["g", "h", "i", "j"]] print("lengh of the list is: ", len(listOfList)) print("lengh of the second list of the list", len(listOfList[1])) x = [8.3, 3.1, 7, 5, 1] y = [2.2, 4.6, 9.1] print("Max element", max(x)) ...
# Un while basico offset = -6 while offset != 0 : print('entro') if offset > 0 : offset = offset - 1 else : offset = offset + 1 # Un for basico sobre lista areas = [11.25, 18.0, 20.0, 10.75, 9.50] for elemento in areas: print(elemento) # Un for sobre un Objeto Enumerate. for index, ele...
from unittest import TestCase from timeConversion import timeConversion class TestTimeConversion(TestCase): def test_input_is_midnight(self): self.assertEqual(timeConversion("12:00:00AM"), "00:00:00") self.assertEqual(timeConversion("12:05:15AM"), "00:05:15") def test_input_is_the_morning(sel...
# https://www.hackerrank.com/challenges/diagonal-difference/problem import math def diagonalDifference(arr): n = len(arr) - 1 d1 = 0 d2 = 0 for i in range(n + 1): d1 += arr[i][i] d2 += arr[i][n - i] return abs(d1 - d2) if __name__ == '__main__': n = int(input()) arr = []...
# https://www.hackerrank.com/challenges/birthday-cake-candles/problem def birthdayCakeCandles(ar): maxar = ar[0] count = {} for i in ar: count.setdefault(i, 0) count[i] += 1 if i > maxar: maxar = i return count[maxar] if __name__ == '__main__': ar_count = int(...
# https://www.hackerrank.com/challenges/time-conversion/problem import re def timeConversion(s): if re.match("^12(.)+AM$", s): res = '00' + s[2:8] return res if re.match("^(.)+AM$|^12(.)+PM$", s): return s[:8] res = int(s[:2]) + 12 return str(res) + s[2:8]
# autor: Hugo de Jesus Valenzuela Chaparro # curso desarrollo experimental 2 # Universidad de Sonora, agosto 2019 # este programa sirve para evaluar funciones, preguntando al usuario # el valor de x a evaluar, las funciones son # -------------------------------------------------------- # a) 4 - x^2 # b) x^(1/2) # c) l...
''' 13. Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7 ''' alt= float(input('Qual sua altura em mts: ')) sexo='' while sexo != 'M' or 'F': sexo = str(input('Qual seu...
''' 04. Faça um Programa que verifique se uma letra digitada é vogal ou consoante ''' letra = str(input('digite uma letra: ')).upper() if letra in 'AEIOU': print('A letra digitada é uma VOGAL!') else: print('A letra digitada é uma CONSOANTE!')
''' 11. Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo. ''' n1int= int(input('Digite um numero inteiro: ')) n2int= int(input('Digite outro numero inteiro: '))...
''' 15. Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: salário bruto. quanto pagou ao ...
# To be filled by students import matplotlib.pyplot as plt from dataclasses import dataclass import pandas as pd @dataclass class NumericColumn: col_name: str # series: pd.Series df: pd.DataFrame # def get_name(self): # """ # Return name of selected column # """ # name = self.name # return...
# Python内置的sorted()函数就可以对list进行排序: # print(sorted([1,4,-1,8,-3])) #1 # list=[1,4,-1,8,-3] # list2=sorted(list) # print(list2) #2 # sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: #print(sorted([1,4,-1,8,-3],key=abs)) #[1, -1, -3, 4, 8] key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序 #字符串排序 #1.正常: #p...
# map map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素, # 并把结果作为新的Iterator返回。 # 有一个函数f(x)=x2,要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map()实现如下: # def f(x): # return x*x # # # r=map(f,[2,4,6,8]) # 由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 # print(list(r)) # 把list所有数字转为字符串: # p...
def insertion_sort(a_list): for index in range(1,len(a_list)): current_value = a_list[index] current_position = index while current_position > 0 and a_list[current_position-1] > current_value: a_list[current_position] = a_list[current_position - 1] current_position = ...
graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['E','A'] graph['C'] = ['A', 'B', 'E','F'] graph['E'] = ['B', 'C'] graph['F'] = ['C'] #The length of the keys is used to provide the dimensions of the matrix which are stored in #cols and rows. matrix_elements = sorted(graph.keys()) cols = rows = len(matrix_elements)...
# def basic_small_change(denom, total_amount): # sorted_denom = sorted(denom , reverse= True) # print(sorted_denom) # returned_change = [] # for cash in sorted_denom: # div = total_amount // cash # if div > 0: # total_amount = total_amount % cash # return...
def inverting_a_string(str1): last_index = len(str1)-1 if len(str1) == 1: return str1[0] else: return str1[last_index] + inverting_a_string(str1[:last_index]) print(inverting_a_string("jackson"))
import random position = 0 walk = [position] steps = 100 for step in range(steps): dist = 1 if random.randint(0,1) else -1 position = position + dist walk.append(position) print(walk)
def quick_sort(a_list): #O(n) is O(nlogn) but may degrade to O(nlogn) if the pivot point is completely skewed to either the left or the right quick_sort_helper(a_list,0, len(a_list)-1) def quick_sort_helper(a_list , first, last): #begins with the same base case as the merge sort. If the length of the #...
from study_address import Address class Person: def __init__(self, name, age, birth, email): self.name = name self.age = age self.birth = birth self.email = email self.place = [] def add_address(self, street, number, state, country): endereco = Address(street, n...
"""Simple Dungeons and Dragons 5th Edition Character Generator.""" __author__ = "Nicholas Harrison" # COP 1500 project guidelines commented as "per guidelines." # Below imports math and random for use later. import math import random def continue_key_press(): """Allows user to progress program and add ...
import tkinter as tk # ColorScale class that creates a slider scale with a color gradient class ColorScale(tk.Canvas): def __init__(self, parent, val=0, height=13, width=80, variable=None, from_=0, to=1, command=None, gradient='hue', **kwargs): tk.Canvas.__init__(self, parent, width=width,...
#str1 = "hasan" str1 = input() a = str1.islower() if a==True: print("Lowercse") else: print("uppercase")
def check(number): if number%2==0: c= "EVEN" return c else: c ="ODD" return c number = int(input()) print(check(number))
class Car: def __init__(self): self.mil = 10 self.com ="mbw" c1 = Car() c2 = Car() #Car.com = "pjero" print(c1.mil , c1.com) print(c2.mil , c2.com)
def my_function(x): return x[::-1] mytxt=input("Input A string\n") print(my_function(mytxt))
from code_challenges.quick_sort.quick_sort import quick_sort, partition,swap def test_assert_quick_sort(): assert quick_sort def test_quick_sort(): list = [8,4,23,42,16,15] actual = quick_sort(list, 0, len(list)-1) expected = [4,8,15,16,23,42] assert actual == expected def test_quick_sort_with_ne...
import string str1 = string.ascii_lowercase dictionary1 = {char:char for char in str1} dictionary2 = {char:(char+char if i%2 ==0 else char) for i,char in enumerate(str1)} dictionary3 = {'a': 'a', 'e': 'e', 'i': 'i', 'm': 'mm', 'q': 'qq', 'u': 'uu', 'y': 'yy'} def left_join(dictionary1, dictionary2): k2dict = {key:...
import random mylist = ["rock","paper","scissor"] randnum = random.choice(mylist) def game(user,randnum): if randnum == "rock": if user == "r": print("oops! Match tied computer chose: ",randnum) return 0 elif user == "s": print("oops! you lost computer chose: ",ra...
# Define a list list1 = [1,2,3,4,5,6,7,8,9,10] print(list1) # Define an empty Dictionary for output dict1 = {} # Generating dictionary using for loop # Even numbers (keys) and their respective square (values) for x in list1: if x%2 == 0: dict1[x] = x**2 # Driver Code print(dict1) # Generating dictionary...
""" Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see example. """ # Define Two separate lists lang = ["English", "Hindi", "Marathi", "Arabic"] langtype = ["Business Language", "Native Lan...
#!/usr/bin/python3 # Regex search in file "*.txt" for regular expression import os, re, glob targetDir = "/tmp/python" targetRegex = re.compile(r'thuan') fileType = "*.txt" #suppose search only in current directory os.chdir(targetDir) for file in glob.glob(fileType, recursive=False): with open(file, "r") as fr: ...
import random as r #flowers, badgers, lions, buffer flowers, buffer badgers, buffer lions, cell version,last flowers, last badgers, last lions def matrix(x,y): out = [] #print(x,y) for i in range(x): out.append([(0,0,0,0,0,0,0,0,0,None)]*y) return(out) def matrix2(x,y): out = [] #print(x,y) for ...
import numpy as np a = np.array([1,2,3,4,5]) print(a) print(np.__version__) arr = np.array([1,2,3,4,5]) print(arr) print(arr.ndim) #ndim checks dimensions of array. arr1 = np.array([[[1,2,3],[1,2,3],[1,2,3]]]) print(arr1) print(arr1.ndim)
print("FILTERING ARRAYS: ") #filterng an array using a boolean index list. import numpy as np a = np.array([12,44,56,45,78,66]) x = [True,True,True,False,True,False] print(a[x]) print("CREATING FILTER ARRAYS: ") ar = np.array([12,34,56,13,23,78,90,10]) #print the numbers those are greatr than 13: ar_filter = [] for e...
#!/usr/bin/env python # # import unittest class BowlingScoreTests(unittest.TestCase): def test_can_parse_all_strike_score_sheet(self): """Can parse score sheet with all strikes""" roll_count = len(Game('X X X X X X X X X X X X').rolls) self.assertEqual(roll_count, 12) def test_can_par...
#1. Fix the 5 syntax errors in the code below so that it runs. It should print the length of myFirstList and print the result of myFirstList * 3. #Then it should set mySecondList to the concatenation of myFirstList and a list containing 321.4. #Then it should print the value of mySecondList. myFirstList = [12,"ape",1...
#Q-1: The following segment should print the statement, "So happy 4 you!". emotion = "So happy " print(emotion + str(4) + " you!") #Q-2: The following program segment should print the phrase, "My new book cost $12". item = "new book" price = "12" print("My " + item + " cost $" + price) #Q-3: The following program seg...
import tkinter, tkinter.messagebox # Tkクラス生成 tki = tkinter.Tk() # 画面サイズ tki.geometry('300x200') # 画面タイトル tki.title('ラジオボタン') # ラジオボタンのラベルをリスト化する rdo_txt = ['Python','Java','C#'] # ラジオボタンの状態 rdo_var = tkinter.IntVar() # ラジオボタンを動的に作成して配置 for i in range(len(rdo_txt)): rdo = tkinter.Radiobutton(tki, ...
# !/usr/bin/python # -*- coding: UTF-8 -*- """ Author: YH.Chen Purpose: Use multiprocessing package to create multiprocessing. Created: 24/6/2020 """ import multiprocessing as mul from multiprocessing import Process import os # 进程信息输出函数 def info(title): print(title) # 输出进程名称 print('module nam...
##!/usr/bin/python3 """ Author: ZhengPeng.Han Purpose: Get infomation of the operating system by a built-in function of python,which named platform. Created: 26/6/2020 """ import platform def TestPlatform(): print("----------Operation System Info--------------------------") print('The version of Python i...
#采用Python语言创建多进程;提示:采用Python内置工具包multiprocessing from multiprocessing import Process import os, time # 线程启动后实际执行的代码块 def pr1(process_name): for i in range(5): print (process_name, os.getpid()) # 打印出当前进程的id time.sleep(1) def pr2(process_name): for i in range(5): print (process_name, os.g...
##!/usr/bin/python3 # -*- coding: UTF-8 -*- """ Author: ZhengPeng.Han Purpose: Gets the names of all files and folders in the given file directory by a built-in function of python,which named os.path. Created: 26/6/2020 """ import os path = 'D:\VIPworks' # 回调函数 def find_file(arg, dirname, files): for file in...
""" Author:Chenjiaying Purpose:采用Python语言创建多进程 Created:1/7/2020 """ from multiprocessing import Process import time def f(name): time.sleep(1) print('hello', name, time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = Process(target=f, args=('reid',)) ...
import os def print_list_dir(root_path): dir_files = os.listdir(root_path) for f in dir_files: file_path = os.path.join(root_path, f) if os.path.isfile(file_path): print(file_path) if os.path.isdir(file_path): print_list_dir(file_path) if __name__ == '__m...
""" Author: jianxi.li Purpose: homework2:采用python语言实现windows命令行调用;提示:采用Python内置工具包os.system Created: 26/6/2020 """ import os #os.system("calc")#启动计算器 #os.system("appwiz.cpl")#程序和功能 #os.system("certmgr.msc")#证书管理实用程序 #os.system("charmap")#启动字符映射表 #os.system("chkdsk.exe")#Chkdsk磁盘检查(管理员身份运行命令提示符) order = input('im...
import multiprocessing import time # 定义一个空列表 m_list = [] # 定义一个向列表添加元素的函数 def add_list(): # 查看进程id编号 print("add:", id(m_list)) # 循环0,1,2,3,4 for i in range(5): # 把循环的元素添加到列表 m_list.append(i) # 打印列表 print(m_list) # 休息1秒 time.sleep(1) ...
# coding=utf-8 ''' Author: By.Zhang Purpose: create multiprocess by python. Created: 28/6/2020 ''' from multiprocessing import Process from multiprocessing import Pool import time import os import random # --------创建函数并将其作为单个进程。-------- # 通过Multiprocessing模块中的Process类,创建Process对象 # 通过对象参数target="需要...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
print("hello wendy :)") # recursion! # call function within a function! # with every recursion problem # what's the base case! # how do we pass along our issuez # factorialz! def factorial(n): """ calls n factorial - 1 base case? n == 0??? return 1 2! = 2 because 2 * 1 = 2 3! = 6 bec...
# Initializing Variables in Python # Creating Variables # A variable is created the moment you first assign a value to it. x = 5 y = "John" print(x) print(y) # Variables do not need to be declared with any particular type and can even change type after they have been set. z = 4 # z is of type int z = "Sally" # z...
""" The View class for The Ark. """ import pygame pygame.init() class ArkView(): """ A class that represents the game view of the game, The Ark. """ def __init__(self, ark_game): """ Creates a new ArkController instance. """ self._game = ark_game self._font ...
# !usr/bin/env python3 ### Author: Marius Ingebrigtsen ### from sys import path def cmpint(a, b): """ Comparison function for numbers. """ return a - b class EntryIterator: """ Iterator class for map entry. """ def __init__(self, entry = MapEntry): """ Assign entry values. """ self.head ...
# !usr/bin/env python3.8 from sys import path path.insert(1, "../bst/") from bst import BinarySearchTree, Node class Node(Node): """ Node for rbt-structure. """ def __init__(self, key = None, item = None, nextnode = None): """ Create and assign value to node. """ self.key = key self.item = item...
from ..util import slice_ def daxpy(N, DA, DX, INCX, DY, INCY): """Adds a vector x times a constant alpha to a vector y Parameters ---------- N : int Number of elements in input vector DA : numpy.double Specifies the scalar alpha DX : numpy.ndarray A double precision r...
from ..util import slice_ def zdotu(N, ZX, INCX, ZY, INCY): """Computes the dot-product of a vector x and a vector y. Parameters ---------- N : int Number of elements in input vectors ZX : numpy.ndarray A double precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`)) IN...
from ..util import slice_ def sswap(N, SX, INCX, SY, INCY): """Swaps the contents of a vector x with a vector y Parameters ---------- N : int Number of elements in input vector SX : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int ...
from ..util import slice_ def scopy(N, SX, INCX, SY, INCY): """Copies a vector, x, to a vector, y. Parameters ---------- N : int Number of elements in input vectors SX : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Stora...
#元祖和列表很类似 ()包裹的,区别在于列表是可变的,元祖是不可变得 arr = ['hello', '','xiaofeng','lulu',''] nums = (2,3,4,5,6,6,8,7,7,7,7,7,7) print(nums.index(4)) #查询数据第一次出现的位置 print(nums.count(7)) #查询某个元素出现的次数 print(type(nums)) #特殊情况表示元祖中只有一个数据 需要加一个逗号 a =(18,) print(type(a)) print(tuple('hello')) #('h', 'e', 'l', 'l', 'o') #列表转换成为元祖 相互转换...
person = {'name':'xiaofeng','age':18,'sex':'男','name':'lulu'} person['name'] = '我爱lulu' # 如果key 不存在的话 则会新增一个 person['xf'] = '小哥哥' print(person.pop('name')) #返回被删除的value print(person)
a =['辛德拉','发条','安妮','卡萨丁','阿狸','拉克丝'] for i in a: print(i) j = 0; while j< len(a) : print(a[j]) j += 1
print(ord('a')) # 使⽤ord⽅法,可以获取⼀个字符对应的编码 print(chr(100)) # 使⽤chr⽅法,可以获取⼀个编码对应的字符
#!/usr/bin/env python3 from typing import List class Solution(object): # Inverview 01.08. Zero Matrix LCCI def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ ind = [] for i in range(len(matrix)): ...
#!/usr/bin/env python3 from sys import path path.append('.') from utils.linked_list_utils import LinkedList, ListNode class Solution(object): # 19. Remove Nth Node From End of List def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: cur = head length = 0 while cur: ...
#!/usr/bin/env python3 from typing import List class Solution(object): # 53. Maximum Subarray # Dynamic programming def maxSubArray(self, nums: List[int]) -> int: # OVERTIME maxsum = nums[0] for i in range(len(nums)): sums = nums[i] curr_maxsum = sums ...
#!/usr/bin/env python3 from typing import List class Solution(object): # 561. Array Partition I def arrayPairSum(self, nums: List[int]) -> int: nums = sorted(nums) sums = 0 for i in range(0, len(nums), 2): sums += min(nums[i], nums[i + 1]) return sums if __name__...
#!/usr/bin/env python3 from typing import List, Optional from sys import path path.append('.') from utils.binary_tree_utils import TreeNode class Solution(object): # 112. Path Sum def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: # Recurse return self.traverse(root=root,...
#!/usr/bin/env python3 from typing import List class Solution(object): # 198. House Robber def rob(self, nums: List[int]) -> int: if len(nums) <= 2: return max(nums) dp = [nums[0], nums[1]] if len(nums) >= 3: dp.append(dp[0] + nums[2]) for i in range...
counties = ["Arapahoe", "Denver", "Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties") else: print("El Paso is not in the list counties") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapa...
def printboard(board): print('\t\t' + '|' + '\t\t' + '|' + ' ') print(' ' + board[1] + ' ' + '|' + ' ' + board[2] + ' ' + '|' + ' ' + board[3] + ' ') print('\t\t' + '|' + '\t\t' + '|' + '\t\t') print('--------' + '|' + '-------' + '|' + '--------') print('\t\t' + '|' + '\t\t' +...
# Hopcroft-Karp bipartite max-cardinality matching and max independent set # David Eppstein, UC Irvine, 27 Apr 2002 def bipartiteMatch(graph): """ Find maximum cardinality matching of a bipartite graph (U,V,E). The input format is a dictionary mapping members of U to a list of their neighbors in V. ...
import errno import os import sys def split_list_in_chunks(lst, chunk_amount): """ Splits list lst in lists of chunk_amount elements and returns them (as a list of lists) """ chunk_amount = max(1, chunk_amount) return [lst[i:i + chunk_amount] for i in range(0, len(lst), chunk_amount)] def gener...
#Функция должна проверить совпадение значений с помощью оператора assert # и, в случае несовпадения, предоставить исчерпывающее сообщение об ошибке. def test_input_text(expected_result, actual_result): assert expected_result == actual_result, "expected {}, got {}".format(expected_result, actual_result)
import threading import time print('Start of program.') def takeANap(m, n): time.sleep(n) print('Wake up!') for i in range(1, 6): threadObj = threading.Thread(target=takeANap, args= (0,i)) threadObj.start() print('End of program.')
from collections import defaultdict food_counter = defaultdict(int) for food in ['spam', 'egg', 'spam', 'spam']: food_counter[food] += 1 for food, counter in food_counter.items(): print(food, counter)
from matplotlib import pyplot as plt import numpy as np from qiskit import * from qiskit.visualization import plot_bloch_vector plt.figure() ax = plt.gca() ax.quiver([3], [5], angles='xy', scale_units='xy', scale=1) ax.set_xlim([-1, 10]) ax.set_ylim([-1, 10]) #plt.draw() #plt.show() plot_bloch_vector([1, 0, 0]) """ ...
# Program to determine the frequency of each letter when the input text is split into x piles. # # To run: # $python3 freqAnalysis.py text x # where text is the plaintext or ciphertext and x is a possible length of the key, so also the number of piles to split # the text into. # # Output: # $Frequencies: # $Pile 1 Pil...