text
stringlengths
5
121k
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ """ Revursive version """ class Solution: """ @param root: The root of the binary search tree. @param node: insert this node into the binary search tree. @return...
""" 932ms version insert node in the same list """ class Solution: """ @param head: The first node of linked list. @return: The head of linked list. """ def insertionSortList(self, head): cur = head index = head tempmax = head.val while index.next: ...
class Solution: def rotateRight(self, head, k): if not head or not head.next: return head cur = head count = 0 while cur: count += 1 cur = cur.next k = k % count if not k: return head ...
def isLineValid(line_X1,line_X2): answer = True if(line_X1 == line_X2): answer = False print("Points coordinates must be different from each other to form a line") return answer def verifyLineCoordinates(line): line_X1 = line[0] line_X2 = line[1] if(line_X...
import pygame from pygame.math import Vector2 class Ship(object): def __init__(self, game): self.game = game size = self.game.screen.get_size() self.speed = 1.5 self.opor = 0.85 self.gravity = 0.5 self.pos = Vector2(size[0]/2,(size[1]/2)-(size[1]/4)) self.v...
""" __mtime__ = '2018/6/7' """ array=[[col for col in range(4)] for row in range(4)] for row in array: print(row) print('-----开始旋转矩阵----') for i, row in enumerate(array): for index in range(i, len(row)): tmp = array[index][i] array[index][i] = array[i][index] array[i][index] = t...
link = input('Enter your link :') link = link.replace('https://', "") link=link.replace('www.', '') value_of_start = link.rfind('/') print(link[:value_of_start])
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 X = [-300, 300] Y_AXES_LIST = [[120, 220], [20, 120], [-120, -20], [-220, -120]] class CarManager: def __init__(self): self.all_cars = [] self.ca...
from fractions import Fraction from sympy import * f_dict = {} def f(m, n, a, b): """ m个白球,n个黑球,想要摸到a个白球,b个黑球 用递推式的方式计算准确结果,结果使用分数表示 """ assert a >= 0 and b >= 0 and m >= 0 and n >= 0 assert a <= m and b <= n param = (m, n, a, b) if param in f_dict: return f_dict[param] if...
import sys def test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__=='__main__': test()
""" This file contains an example search engine that will search the inverted index that we build as part of our assignments in units 3 and 5. """ import sys,os,re import math import sqlite3 import time docs = {} resultslist = {} term = {} chars = re.compile(r'\W+') pattid= re.compile(r'(\d{3})/(\d{3})/...
import csv import sys from read_csv import read_and_transform_csv from function_to_apply import foo from decimal import Decimal, ROUND_HALF_UP input_filepath = sys.argv[1] output_filepath = sys.argv[2] result = read_and_transform_csv(filepath = input_filepath, foo = foo, result = {}) with open(output_fi...
abc = "ABCcdedDD" print(abc.lower()) print(abc.swapcase()) print(abc.title()) print(abc.upper())
import cv2 import matplotlib.pyplot as plt import numpy as np def seg_kmeans_color(img, k=2): h, w, d = img.shape b, g, r = cv2.split(img) img = cv2.merge([r, g, b]) img_flat = img.reshape((img.shape[0] * img.shape[1], 3)) img_flat = np.float32(img_flat) criteria =...
import math total_part_1 = 0 total_part_2 = 0 filename = 'input.txt' with open(filename,) as file_object: for line in file_object: x_part_1 = int(line,10) res_part_1 = x_part_1 / 3 total_part_1 += math.floor(res_part_1) - 2 x_part_2 = int(line,10) while m...
import sys import threading """ Compute height of a given tree Height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a leaf to the root. """ class TreeHeight: def __init__(self, nodes): self.num = len(nodes) self.parent = nodes self.depths = [0] * self....
import csv import sys from datetime import datetime from datetime import timedelta from datetime import timezone USAGE = f"usage: python {sys.argv[0]} file_name.csv datetime" class CommandLine: def __init__(self, argv): if len(argv) > 3: print("error: at most two command line argument...
""" 75. 寻找峰值 中文English 你给出一个整数数组(size为n),其具有以下特点: 相邻位置的数字是不同的 A[0] < A[1] 并且 A[n - 2] > A[n - 1] 假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置。 样例 样例 1: 输入: [1, 2, 1, 3, 4, 5, 7, 6] 输出: 1 or 6 解释: 返回峰顶元素的下标 样例 2: 输入: [1,2,3,4,1] 输出: 3 挑战 Time complexity O(logN) 注意事项 数组保证至少存在一个峰 如果数组存在多个峰,返回其中...
""" 433. 岛屿的个数 中文English 给一个 01 矩阵,求不同的岛屿的个数。 0 代表海,1 代表岛,如果两个 1 相邻,那么这两个 1 属于同一个岛。我们只考虑上下左右为相邻。 样例 样例 1: 输入: [ [1,1,0,0,0], [0,1,0,0,1], [0,0,0,1,1], [0,0,0,0,0], [0,0,0,0,1] ] 输出: 3 样例 2: 输入: [ [1,1] ] 输出: 1 """ import collections class Solution: """ @param grid: a boolean 2D matrix @re...
""" 453. 将二叉树拆成链表 中文English 将一棵二叉树按照前序遍历拆解成为一个 假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。 样例 样例 1: 输入:{1,2,5,3,4,#,6} 输出:{1,#,2,#,3,#,4,#,5,#,6} 解释: 1 / \ 2 5 / \ \ 3 4 6 1 \ 2 \ 3 \ 4 \ 5 \ 6 样例 2: 输入:{1} 输出:{1} 解释: """ """ Definition of Tree...
""" Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤...
""" 618. 搜索图中节点 中文English 给定一张 无向图,一个 节点 以及一个 目标值,返回距离这个节点最近 且 值为目标值的节点,如果不能找到则返回 NULL。 在给出的参数中, 我们用 map 来存节点的值 样例 例1: 输入: {1,2,3,4#2,1,3#3,1,2#4,1,5#5,4} [3,4,5,50,50] 1 50 输出: 4 解释: 2------3 5 \ | | \ | | \ | | \ | | 1 --4 Give a node 1, target is 50 there a hash named values which ...
""" 900. 二叉搜索树中最接近的值 中文English 给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值 样例 样例1 输入: root = {5,4,9,2,#,8,10} and target = 6.124780 输出: 5 解释: 二叉树 {5,4,9,2,#,8,10},表示如下的树结构: 5 / \ 4 9 / / \ 2 8 10 样例2 输入: root = {3,2,4,1} and target = 4.142857 输出: 4 解释: 二叉树 {3,2,4,1},表示如下的树结构: 3...
from functools import reduce from collections import Counter import itertools import operator def most_common(L): SL = sorted((x, i) for i, x in enumerate(L)) groups = itertools.groupby(SL, key=operator.itemgetter(0)) def _auxfun(g): item, iterable = g count = 0 min_index = len(L) for ...
from flask import Flask from flask import request application = Flask(__name__) @application.route("/") def home(): return WORDHTML WORDHTML = """ <html><body> <h2>Word and Number Game</h2> <form action="/game"> Enter a word: <input type='text' name='wrd'><br> ...
import pickle class Book: def read_data(self): self.title = input('Enter Book tile: ') if not self.title: return self.author = input('Enter Author name: ') self.page_count = input('Enter page count: ') self.borrow_history = [] def add_borrow_history(self, u...
class Automate(object): """Une class automate qui permet de lire des solutions on peut y ajouter une regle on peut aussi resoudre avec la fonction solve et un mot de passe """ END = -1 NOT_FOUND = 0 START = "" def __init__(self, name): self.name = name self.regles...
class BSTIterator: def __init__(self, root: TreeNode): def inOrderTraversal(output,node): if node.left is not None: output.extend(inOrderTraversal([],node.left)) output.append(node.val) if node.right is not None: output.extend(inO...
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: n=len(mat) sum=0 for i in range(n): sum=sum+mat[i][i] for i in range(n): sum=sum+mat[i][n-i-1] if n%2!=0: sum=sum-mat[n//2][n//2] return sum
class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i in range(len(A)): for j in range((len(A[0])-1)//2+1): temp = 1- A[i][j] A[i][j] = 1- A[i][len(A[0])-j-1] A[i][len(A[0])-j-1] = temp return A
class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: def graphTraversal(node,record): record[node.val-1] += 1 temp = 0 if node.left is not None: temp += graphTraversal(node.left,record) if node.right is not Non...
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ length=len(s) for i in range(length//2): temp=s[i] s[i]=s[length-i-1] s[length-i-1]=temp
class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: store = [] temp = head while temp is not None: store.append(temp) temp = temp.next leng = len(store) k=min(k,leng-k+1) if leng%2==1 and k==...
def main(): g = open('textfile.txt','r') if g.mode == 'r': contents = g.read() print(contents) if __name__ == "__main__": main()
items=[6, 20, 8, 19, 56, 23, 87, 41, 49, 53] def quickSort(dataset, first, last): if first < last: pivotrIdx = partition(dataset, first, last) quickSort(dataset, first, pivotrIdx-1) quickSort(dataset, pivotrIdx+1, last) def partition(dataset, first, last): pivotValue = dataset[first] lower = first...
class Car: pass class Truck(Car): pass c = Car() t = Truck() print(type(c)) print(type(t)) print(isinstance(c,Car)) print(isinstance(t,Car))
number = int(input('Enter any number: ')) if(number%2 == 0): print('The Number is even.') else: print('The Number is odd.')
for i in range(1,21): if i == 4 or i == 13: s = str(i) + " is unlucky !!!!" print(s) elif i % 2 == 0: t = str(i) + " is even !!" print(t) else: u = str(i) + " is odd !!" print(u)
import matplotlib.pyplot as plt from digits.hand_writing import HandWriting if __name__ == '__main__': def print_menu(): test = ['asdfsadf', 'asdgsad', 'asdf'] print(test) t = [2 == 2] print(t) print('0, EXIT') print('1, 손글씨 인식') print('2, 고양이 모자이크') ...
import time from random import randint, choice import copy def you_are_dead(player, text=''): if text: print(text) print('YOU', end='', flush=True) time.sleep(0.5) print('\tARE', end='', flush=True) time.sleep(0.5) print('\tDEAD.', end='', flush=True) print('So passes {} the {} into the endless night.'.fo...
from random import randint from random import choice import time def user_input(): msg = '> ' choice = input(msg) return choice def press_enter(): msg = '...' input(msg) def run_attempt(): escape_num = 10 print('Press enter to roll your Run attempt') press_enter() roll = randint(1,20) if roll > es...
class Pizza: def __init__(self): self.size = 0 self.style = "" self.new_topping = [] def add_topping(self, topping): self.new_topping.append(topping) def print_order(self): space = " and " new_string = f"I would like a {self.size}-inch, {self.style} pizza" ...
def sum(a, b, c): return a + b + c print(sum(3,2,1)) print(sum(1000,300,111)) foodArray = ['pizza', 'burger', 'sushi', 'curry'] def findFoodInTheApp(arrayOfFood, desiredFood): for food in arrayOfFood: if food == desiredFood: return f'Here is your {food}' print(findFoodInTheApp(food...
'''Imlementing stack based on linked list''' class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head ...
pi = 3.14 radius = 5 area = pi * radius ** 2 print("Area: ", area)
movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ")
name = input("Enter your name: ") age = input("Enter your age: ") print(name, age)
print("Hello, World!".lower()) print("Hello, World!".upper()) print("Hello, World!".capitalize()) print("Hello, World!".title()) print(" Hello, World! ".strip())
movies = [ ("The Room", "Tommy Wiseau", "2003", "$6,000,000") ] title = input("Title: ") director = input("Director: ") year = input("Year of release: ") budget = input("Budget: ") new_movie = title, director, year, budget print(f"{new_movie[0]} ({new_movie[2]})") movies.append(new_movie) print(movies[0]) print(...
def pour(jug1, jug2): print(jug1,'\t', jug2) if jug2 is 2: return elif jug2 is 4: pour(0, jug1) elif jug1 != 0 and jug2 is 0: pour(0, jug1) elif jug1 is 2: pour(jug1, 0) elif jug1 < 3: pour(3, jug2) elif jug1 < (4 - jug2): pour(0, ...
def solution(clothes): answer = 1 c_dict = {} for c, type in clothes: if type in c_dict: c_dict[type] += 1 else: c_dict[type] = 1 for cnt in c_dict.values(): answer *= cnt + 1 return answer - 1
import random import string from flask import jsonify def random_chars(n=12, uppercase=False, symbol=False, digit=False): """ The function generates a random password using user-defined parameters and evaluates its difficulty :param n: str :param uppercase: bool :param symbol: bool :param...
import pandas as pd import numpy as np import matplotlib.pyplot as plt table = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/penduduk_gender_head.csv") table.head() x_label = table['NAMA KELURAHAN'] plt.bar(x=np.arange(len(x_label)), height=table['LAKI-LAKI WNI']) plt.xticks(np.arange(len(x_label)), table...
def userx(): user = input("Masukan Username : ") if user == 'admin': print("Lanjut Gan, Masukin Passwordnya") pw = input("Masukan Password : ") if pw == 'admin': print("Login Sukses !") else: print("Password salah!") else: print("Salah Coy User...
a = 8 def kuadrat (a): total = a**2 print("Kuadrat dari",a,"adalah",total) return total a = kuadrat(a) print (a) print (50*'-') def tambah (a,b): total = a+b print(a, "+" , b , '=', total) return total def kali (a,b): total = a*b print(a, "x" , b , "=", total) return total a = tamb...
suku = int(input('Masukan Suku Ke Berapa : ')) a = 0 b = 1 c = 3 print(a) print(b) while c <= suku: c = a+b a = b b = c print(c) c+=1
import unittest from main import Problem1 class TestProblem1(unittest.TestCase): def test_sum_of_natural_numbers_below_10_that_are_multiples_of_3_or_5(self): p1 = Problem1.Problem1() self.assertEqual(23,p1.solve(10)) def test_sum_of_natural_numbers_below_1000_that_are_multiples_of_3_or_5(self): p1 = Problem1...
import itertools class Problem5(object): def solve(self,number): uniqueProducts = self.products(number) for x in itertools.count(1): valid = True for i in uniqueProducts: if not x % i == 0: valid = False if valid: return x def products(self,number): result = [] for i in range(number,...
""" Source: https://www.youtube.com/watch?v=87MNuBgeg34 We can have observable that can notify one group of subscribers for one kind of situation. Notify a different group of subscribers for different kind of situation. We can have the same subscribers in both groups. We call these situations events (different kinds o...
for x in range(1,101): print(x) print(x*x) print("Done!") names = ["Sarah", 'jack', 'Beth', 'Jort'] for x in range(0, len(names)): print(names[x]) for name in names: print(name)
class User: bank_name = "First National Dojo" def __init__(self, name, email_address, account_balance): self.name = name self.email = email_address self.account_balance = account_balance def make_deposit(self, amount): self.account_balance += amount re...
for num in range(151): print(num) for num in range(5,1001,5): print(num) for num in range(1,100,1): if num % 5 == 0: print("Coding") if num % 10 == 0: print("Coding Dojo") else: print(num) sum = 0 for num in range(0,500000,1): if num % 2 == 0: continue el...
""" Решить несколько задач из projecteuler.net Решения должны быть максимально лаконичными, и использовать list comprehensions. problem6 - list comprehension : one line problem9 - list comprehension : one line problem40 - list comprehension problem48 - list comprehension : one line Sum square difference Problem 6...
import csv import platform import sys import os from linkedlist import LinkedList from data_type import User users = LinkedList(User) def clear_terminal(): system = platform.system() if system == 'Windows': os.system('cls') elif system == 'Darwin' or system == 'Linux': os.system('clear'...
import random as r from matplotlib import pyplot as plt print(plt.style.available) plt.style.use('fivethirtyeight') list_x = [0] list_y = [0] for x in range(100): list_x.append(r.randint(1, 100) - r.randint(1, 50)) list_y.append(1+list_y[x]) plt.plot(list_y, list_x, color = 'b', linestyle='--',la...
""" Created on Tue Dec 12 22:55:27 2017 @author: lenovo """ from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense classifier = Sequential() classifier.add(Convolution2D(32, 3, 3, inp...
from setup import BLUE, WHITE, SQUARE_SIZE, GRAY, ROBOTS import pygame class Robot: PADDING = 10 OUTLINE = 2 def __init__(self, row, col, color): self.row = row self.col = col self.color = color self.robot1 = False self.robot2 = False self.robot3 = True ...
from decimal import Decimal if __name__ == '__main__': n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores querry_name = input() querry_scores = student_marks[querry_name] total_sc...
the_count=[1,2,3,4,5] fruits=['apples','oranges','pears','apricots'] change=[1,'pennies',2,'dimes',3,'quarters'] for number in the_count: print(f"this is count {number}") for fruit in fruits: print(f"A fruit of type :{fruit}") for i in change: print(f"I go {i}") elements=[] for i in range(...
import datetime time = datetime.datetime.now() month = str(time.month) day = str(time.day) hour = str(time.hour) minute = str(time.minute) foods = ["Meat", "Cheese"] print("Welcome to the Grocery List App.") print("Current Date and Time: " + month + "/" + day + "\t" + hour + ":" + minute) print("You currently have "...
print("Welcome to the multiplication/exponentiation table app.") print("What number would you like to work with?") name = input("\nHello, what is your name: ").title().strip() num = float(input("What number would you like to work with: ")) message = name + ", Math is really cool!!!" print("\nMultiplication Table ...
from array import * array_num = array('i', [1,3,5,7,9]) for i in array_num: print("Loop through the array.",i) print("Access first three items individually") print(array_num[0]) print(array_num[1]) print(array_num[2])
print("Welcome to the Favorite Teachers Program") fav_teachers = [] fav_teachers.append(input("Who is your first favorite teacher: ").title()) fav_teachers.append(input("Who is your second favorite teacher: ").title()) fav_teachers.append(input("Who is your third favorite teacher: ").title()) fav_teachers.append(inp...
from array import * array_num = array('i',[1,3,5,7,9]) print("Original array: " +str(array_num)) array_num.extend(array_num) print("Extended array: "+str(array_num))
def division(a,b): if a<b: return 0 else: return 1+division(a-b,b) print(division(15,3))
import sys import operator args = sys.argv if len(args) != 3: exit("Not enough arguments please pass 2 arguments") storyFileName = args[1] skipWordsFileName = args[2] with open(storyFileName, 'r') as storyFile: storyString = storyFile.read() print('Story filename: ' + storyFileName) with open(skipWo...
''' class node: def __init__(data): self.data = data self.next = None ''' def findMid(head): temp = head i=1 while temp: temp = temp.next i+=1 mid = (i/2)+1 tpoint = head j=1 while j<mid: element = tpoint.data tpoint = tpoint.next ...
def reverseParentheses(ary): ary=list(ary) while '(' in ary: for i in range(len(ary)): if ary[i]=='(': head=i elif ary[i]==')': tail= i break ary[head:tail+1]= ary[tail-1:head:-1] return ''.join (i for i in ary)
def alphabeticShift(inputString): return ''.join([chr(ord(i)+1) if i!='z' else 'a' for i in inputString])
def checkPalindrome(inputString): return True if inputString==inputString[::-1] else False
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newList = ['Hello' for x in fruits if x != "apple"] print(newList)
lado = int(input("Digite a medida de um dos lados do quadrado: ")) area = lado**lado print("Area do quadrado: " + str(area))
import random import sys from os import system from IPython.display import clear_output def checkifboardisfull(boardstate): counter = 0 for i in boardstate: if i == 'X' or i=='O': counter+=1 if counter==9: print("The game has ended in a draw!") sys.exit(0) return True else: return False ...
import random def random_function(): return 4 * random.random() + 3 for i in range(10): print(random_function())
is_male = True is_tall = True if is_male and is_tall: print("You are a tall male.") elif is_male and not(is_tall): print("You are a short male.") elif not(is_male) and is_tall: print("You are not a male, but you are tall.") else: print("You are not a male.")
movies = ["Star Wars", "Gandhi", "Casablanca", "Shawshank Redemption", "Toy Story", "Gone with the Wind", "Citizen Kane", "It's a Wonderful Life", "The Wizard of Oz", "Gattaca", "Rear Window", "Ghostbusters", "To Kill A Mockingbird", "Good Will Hunting", "2001: A Space Odyssey", "R...
class User: pass user1 = User() user1.first_name = "Dave" user1.last_name = "Bowman" print(user1.first_name) print(user1.last_name) print(80 * "-") first_name = "Arthur" last_name = "Clarke" print(first_name, last_name) print(80 * "-") print(user1.first_name, user1.last_name) print(80 * "-") user2 =...
""" Created on @author: """ from student import student def main(): Surname = input("Enter student's surname: ") Firstname = input("Enter student's first name: ") StuNo = input("Enter student number: ") Course = input("Enter student's course: ") stuObj = student(Surname...
""" Created on @author: """ shoppinglist = [] setFlag = 1 item = "" while(setFlag != 0): item = input("Enter the item in shopping list : ") if item == "": setFlag = 0 break; else: shoppinglist.append(item) print(shoppinglist)
''' Count the number of prime numbers less than a non-negative number, n. Example: Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. ''' class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ ...
''' Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 ''' class Solution(...
''' Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: "Hello World" Output: 5 ''' cla...
''' Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... Example 1: Input: 1 Output: "A" Example 2: Input: 28 Output: "AB" Example 3: Input: 701 Output: "ZY" ''' class Soluti...
''' Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' class Solution(object): def reverseList(self, head): """ :type head: ListNode ...
friend =["Jan","Cream","Phoo","Bam","Aom","Pee","Bas","Kong","Da","Jame"] friend[9]="May" friend[3]="boat" friend.append("Dome") friend.append("Poondang") friend.insert(1,"Csa") friend.insert(8,"Ped") friend.remove("Aom") friend.pop(3) del friend[7] friend.clear() del friend print(friend)
def cyclicForm(pattern): length = len(pattern) form = [pattern] def cyclicFormed(pattern , k ): old = pattern new = [0] * len(pattern) for i in range(k): new[0] = old[-1] new[1:] = old[:-1] old = new.copy() return ''.join(new) for i i...
import sys def hamming(str1, str2): HammingDistance = 0 for i in range(len(str2)): if str1[i] != str2[i]: HammingDistance += 1 return HammingDistance def find_kmer(text, k): kmer_collection = [] for i in range(len(text) - k): kmer_collection.append(text[i:i + k]) ...
def main(): address_books = [ {'name': '東京タワー', 'location': '東京都港区芝公園4丁目2−8', 'zipcode': '1050011'}, {'name': 'スカイツリー', 'location': '東京都墨田区押上1丁目1−2', 'zipcode': '1310045'}, {'name': '通天閣タワー', 'location': '大阪府大阪市浪速区恵美須東1丁目18−6', 'zipcode':...
def perfact(a): i=1 sum=0 while i<=1000: if a%i==0: sum=sum+i if a==sum: print("Perfact",i) else: print("not perfact",i) i=i+1 num1=int(input("enter the number")) perfact(num1)
def addtion(a,b): c=a+b print("Addtion",c) x=int(input("enter the first no:")) y=int(input("enter the second no:")) addtion(y,x)