text
stringlengths
37
1.41M
if __name__ == '__main__': while True: print("开始?0/1") c=input() if c==0: break else: s = input("请输入字符串,我帮你看看哪个重复了:") d = set() for i in s: d.add(i) for i in d: num = s.count(i) ...
#随机生成两个分别包含10和15个整数的列表,并计算输出两个列表的并集 import random # 并集就是把两个列表相加去重 def suiji(): nlist = [random.randint(1, 21) for i in range(0, 15)] mlist = [random.randint(1, 31) for i in range(0, 10)] slist = mlist + nlist ulist = {i for i in slist} print("第一个随机列表为:{0}".format(nlist)) print("第二个随机列表为:{0}".f...
#!/usr/bin/env python2.7 # encoding: utf-8 """ @brief: @author: icejoywoo @date: 15/12/6 """ import re import perf s = ("Note that there is a significant advantage in Python to adding a number " "to itself instead of multiplying it by two or shifting it left by one bit. " "In C on all modern ...
x=int(input()) if x%2==0: print("it is Even") else: print("it is Odd")
#primenumber......ajith x=int(input("enter a value")) if x<=1000: if(x>1): for i in range(2,x): if(x%i==0): print("it is not a prime number") break else: print("it is a prime number") else: print("not a prime number") else: prin...
from os import path def print_paths_parts(file, number): """ This method outputs print b amount of parts of input path to file in correct order. Amount of parts also an input argument Works on with all common type of path : Unix and Win :parameters: path : st...
# PB1 ABHISHEK WAHANE # Unification Algorithm class Variable: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value class Constant: def __init__(self, value): self.value = value def __eq__(self, other): return self.v...
""" lambda는 함수명이 존재하지 않으며 재활용성을 고려한 함수보다는 1회성으로 잠깐 사용하는 속성 함수라고 볼 수 있음 """ answer = lambda x: x**3 print(answer(5)) power = list(map(lambda x: x**2, (range(1,6)))) print(power)
foods = ["bacon", "beef", "spam", "tomato", "tuna"] # for food in foods[3:]: # print(food) # print(len(food)) # for number in range(5): # print(number) # for number in range(1,10,2): # print(number) # for number in range(10): # print(str(number) + " Hello World") times = 5 while times < 10: ...
str="HI! my name is vaishnav!. what is yours?" print(str) print('Split string =') print('HI!\n My name is vaishnavi\n What is yours?\n')
a=input("enter the words in string to be reversed") a=a.split() b=a[-1::-1] revstr=' '.join(b) print(b)
#learned a little bit about csv files and the csv library while making this program. Also have a pretty cool way to search for popular drake songs! import csv from string import * # convert_num: converts things like "1M" or "2.4K" to 1000000 and 2400 # converts input string to a list of chars, manipulates tha...
import numpy as np import matplotlib.pyplot as plt import pickle import random ##opening of the file f = open('data2_new.pkl','rb') data = pickle.load(f) f.close() da = np.asarray(data) X = da[:,0] Y = da[:,1] #initialisation of variables cnt = 0 best_fit = 0 slope = 0 intercept = 0 iterations = 1 variance = 0 ...
from collections import deque element="hello" print(element[0]) print(element[-1]) print(element[4]) print(element[-5]) # [2:4] the element at 4 is excluded print(element[2:4]) print(element[2:9]) print(element[77:99]) #List Implementation print("\n\nLIST IMPLEMENTATION") sampleList=[0,1,2,3,4,5,6,7] print("This is t...
element=["1","2","3"] print(element) element[1]="7" print(element)print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")...
import sys def driver_testcases(): no_of_cases = int(input()) for i in range(1, no_of_cases+1): length = int(input()) arr = [int(x) for x in input().split()] print(f"Case #{i}: {Reversort(arr)}") def main(): Reversort(L) def Reversort(L): cost = 0 l = len(L) for i...
from electronicDie import ElectronicDie from sense_hat import SenseHat import time import csv import os.path from os import path from datetime import datetime #Creating an object pointing to the SenseHat class sense = SenseHat() #Creating an object pointing to the ElectronicDie class electronicDieObj = ElectronicDie(...
import curses class ViewController(object): """ A ViewController is essentially the entry point to the UI. It is responsible for initializing the screen, moving between main views, and waiting in the main event loop. """ def __init__(self, views=None): """ Create a new ViewController. ...
from abc import ABC,abstractmethod class shape(ABC): def __init__(self,hight,base): self.hight=hight self.base=base @abstractmethod def area(self): pass class Triangle(shape): def area(self): area=.5* self.base * self.hight print("area of triangle:",...
#!/usr/bin/python3 """Module to display the first 10 hot posts""" import requests def top_ten(subreddit): """ Function that will take the first 10 hot posts from a subreddit """ response = requests.get('https://www.reddit.com/r/{}/hot.json' .format(subreddit), ...
""" Various functions useful for saving and loading arrays of results """ import os, json, logging import numpy as np def save_json(folder_name, base_name, output_data): """ Serialize a structure of output data to JSON file in specified location :param folder_name: :param base_name: ...
""" Provide geometric transformations and other utilities. """ from math import sin, cos, sqrt import numpy as np from lxml import etree def rotation_about_vector(vec, t, mat=None): """ Return a transform matrix to rotate ``t`` radians around unit vector ``vec``. """ l = vec[0] m = vec[...
from sympy.combinatorics.permutations import Permutation from sympy.utilities.iterables import variations, rotate_left from sympy.core.symbol import symbols from sympy.matrices import Matrix def symmetric(n): """ Generates the symmetric group of order n, Sn. Examples ======== >>> from sympy.combi...
import sys import os import webbrowser def webview(outfile): """pop up a web browser for the given file""" if sys.platform == 'darwin': os.system('open %s' % outfile) else: webbrowser.get().open(outfile) def webview_argv(): """This is tied to a console script called webview. It just p...
quantidade_de_valores = True conta_par = 0 cont = 0 print("Digite um numero diferente de -1: ") while quantidade_de_valores: num = int(input("Digite um numero: ")) if(num < 0): break cont = cont + 1 if num % 2 == 0: conta_par = conta_par + 1 print(conta_par, "numeros pares")
# ---- Global variables ------------------------------------------------------- N = int(input("\nEnter square size N: ")) # N - lenght of side LIST = [] NUMBER_LENGTH = len(str(N*N)) # Check how many digits the largest number has # ---- Class for colours ------------------------------------------------------ class bc...
# задание№1 # Поработайте с переменными, создайте несколько, выведите на # экран. Запросите у пользователя некоторые числа и строки и # сохраните в переменные, затем выведите на экран. name = input('Введите Ваше имя: ') surname = input('Введите Вашу фамилию: ') age = int(input('Введите Ваш возраст: ')) year_birth = 20...
# Declaring aa class class Time: second = 0 hour = 0 minute = 0 # Providing Inputs to variables of class time = Time() time.hour = 1 # 1 hour = 3600 seconds time.minute = 10 # 10 minutes = 600 seconds time.second = 20 # Function to convert Time in H:M:S format in to Seconds def time_to_int(time): ...
import sys def cumulative_sum(num): empty_list = [] length = len(num) temp = 0 print("length of the list:", length) for i in range(0, length): temp = temp + num[i] empty_list.append(temp) # print(i) return(empty_list) # Program2 num = [10, 2, 3] new_list = cumulative_...
import requests import sys import os import re def get_vendor_info(): """Making request to Linux usb information database to retrieve devices information : Input: None : Output: List of devices and their ids""" # Making request to linux usb database try: print("[+] Retrieving...
def solution(n): answer = 0 if n == 2: answer = 1 else : answer = 1 for i in range(3, n + 1) : is_prime_num = True for j in range(2, i) : if i%j == 0 : is_prime_num = False break ...
A = int(input()) for i in range(A): print(" "*i, end = "") print("*"*(2*A - 1 - 2*i)) for i in range(A - 1, 0, -1): print(" "* (i-1), end = "") print("*"*(2*A - 1 - 2*(i - 1)))
def palindrome(s): l = len(s) dp = [[0 for i in range(l)] for j in range(l)] for i in range(len(s)-1,-1,-1): for j in range(i,len(s)): if i==j: dp[i][j] = 1 elif j-1==i and s[i]==s[j]: dp[i][j] = 1 elif dp[i+1][j-1]==1 and s[i]==s[j]: dp[i][j] = 1 index = 0 ...
# 최대 구간 합 문제 (maximum subarray problem) def read_data(): array = [int(v) for v in input().split()] return array def max_sum(array): l = len(array) m = int(l/2) if l == 1: return sum(array) array_l = array[:m] array_r = array[m:] answer = 1e-100 # 이곳에 문제 3에 대...
def numDivisor(n): ''' n의 약수의 개수를 반환하는 함수를 작성하세요. ''' sum_divisor = 0 for i in range(1, n+1): if 0 == n % i: sum_divisor += 1 return sum_divisor def main(): ''' Do not change this code ''' number = int(input()) print(numDivisor(number)) ...
import math def get_data(): N = int(input()) data_list = [] for _ in range(N): num = int(input()) data_list.append(num) return data_list def sorting_number(numbers): s = 0 # 여기에 문제 1에 대한 코드를 작성하세요. while len(numbers) != 1: sorted_numbers = sorted(num...
def push(heap, x) : heap.append(x) index = len(heap)-1 while index != 1 : if heap[index//2] > heap[index] : tmp = heap[index//2] heap[index//2] = heap[index] heap[index] = tmp index = index // 2 else : return def pop(heap) : ...
def get_parent_child_rel(): p_c_rel = dict() all_childs = set() no_rels = int(input()) for _ in range(no_rels): tmp = [int(v) for v in input().split()] p_c_rel[tmp[0]] = {'left' : tmp[1], 'right' : tmp[2]} for child in tmp[1:]: if child != -1: all_chi...
import math def get_data(): N = int(input()) data_list = [] for _ in range(N): num = int(input()) data_list.append(num) return data_list def construct_heap(numbers): heap = [] while len(numbers) != 0: number_ = numbers.pop() heap.append(number_) ...
input_file=raw_input("input file name?") def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count,f): print line_count,f.readline(), input_file=open(input_file,'r') print"let us first print the whole file\n" print_all(input_file) print "let's now rewind kind of a tape" ...
people = 20 cats = 40 dogs = 5 if people < cats: print "too many cats world is doomed" if people > cats: print "not many cats world is saved" if people < dogs: print"the world is drooled on" if people > dogs: print"the world is dry" dogs += 5 if people >= dogs: print"people are greater than or...
import math; class BasicObject: animationIdCount = 0 def __init__(self, points, color): self.points = points self.color = color self.old_animation_positions = {} # this is used during the animation rendering procces inorder to keep track of the last position and lerp from there for examp...
#coding=gbk ''' Created on 2014319 @author: bling ''' # dic = {'tom':11,'sam':56,'jun':20,'jun':19} print dic,type(dic) print dic['jun'] dic['jun']=30 print dic dic={} print dic dic['yangml']=10 print dic #ʵԪصѭ dic = {'tom':11,'sam':56,'jun':20,'jun':19} for key in dic: print dic[key],type(dic[k...
import math import string import random # Writ a function which generates a six digit random_user_id. # print(random()) # print(randint(3,9)) def random_user_id(stringLength = 6): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength)) print(random_user_id()) multi...
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} A = {19, 22, 24, 20, 25, 26} B = {19, 22, 20, 25, 26, 24, 28, 27} age = [22, 19, 24, 25, 26, 24, 25, 24] # Find the length of the set, it_companies print(len(it_companies)) # Add 'Twitter' to it companies it_companies.add('Twitter')...
# Concatenate the string 'Thirty', 'Days', 'Of', 'Python' to a single string, 'Thirty Days Of Python' concatunate = ['Thirty', 'Days', 'Of', 'Python'] full_sentence = ' '.join(concatunate) print(full_sentence) # Concatenate the string 'Coding', 'For' , 'All' to a single string, 'Coding For All' string = ['Coding', 'Fo...
# -*- coding:utf-8 -*- data={"name":"walker","age":33} try: data["weight"] except (KeyError,IndexError) as e: #这样一次只能捕获一个错误;如果对两种错误的处理方式一样,可以用这种方式进行处理 print("字典不存在",e) print("----------") list1=["sadfasd","sadfsadf",333] # list1[5] try: list1[5] except IndexError as e: print(e) print("------------") m=6...
#! -*- coding:utf-8 -*- # https://www.cnblogs.com/zpzcy/p/7668765.html """ 需求: 启动程序后,让用户输入工资,然后打印商品列表 允许用户根据商品编号购买商品 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 可随时退出,退出时,打印已购买商品和余额 """ product_list = [ ('Iphone', 5800), ('Mac Pro', 9800), ('Bike', 800), ('Watch', 10600), ('Coffee', 31), ('Alex Python', 120), ...
#! -*- coding:utf-8 -*- """ len() ,len(list)方法返回列表元素个数,list -- 要计算元素个数的列表,返回值,返回列表元素个数 元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。 list( seq ) 方法用于将元组或字符串转换为列表,返回值,返回列表 #可以直接del list[2] 删除列表中的元素 #列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表 列表可以嵌套列表 序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推 """ list = ["name", "ag...
import io n = int(input()) # all subsets of {1,2,3, ... , n} def printSubstring(arr): f = io.StringIO() f.write('{') # Flag to check if an extra comma is present at the end extraComma = False for elem in a: f.write('{},'.format(elem)) extraComma = True if extraComma: # ...
animals = ['cat', 'dog', 'monkey', 'lion', 'zebra', 'giraffe'] #animals = ['cat', 'monkey', 'dog'] COUNT = 2 # all combinations of animals of size 2. n = len(animals) a = [[],[]] def backtrack(a,k): # check if the current configuration is a solution and process it. if k == n: print(a) else: # E...
import random import matplotlib.pyplot as plt import collections seed = random.randint(1, 10000000) random.seed(seed) size_list = [18] * 60 size_list_hubs = [50] * 60 min_distance = 110 connection_distance = min_distance + 80 class Hub: def __init__(self, name, x, y): self.name = name self.x = x ...
import re from datetime import datetime def map_str_to_datetime(date_string): regex_year = '^\d{4}$' regex_month = regex_year[:-1] + '-\d{2}$' regex_day = regex_month[:-1] + '-\d{2}$' regey_daytime = regex_day[:-1] + ' \d{2}:\d{2}:\d{2}$' if re.match(regex_year, date_string): return dat...
import string class Solution: # def isPalindrome(self, s: str) -> bool: def isPalindrome(self, s): # s = s.lower() ptr_pos = 0 ptr_neg = len(s) - 1 while ptr_pos<=ptr_neg: if s[ptr_pos].lower() == s[ptr_neg].lower(): ptr_pos += 1 ptr...
import time from collections import deque from Queue import Queue number = 100000 start = time.time() a = list() for i in range(number): a.append((i)) for _ in range(number): a.pop() print('time for built-in list is {}'.format(time.time()-start)) start = time.time() a = deque() for i in range(number): a.append((i...
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ mid = len(nums) // 2 if nums[mid] == target: return mid if nums[mid] < nums[-1]: # head on the left if nums[mid] < tar...
# linked list # need a head that points to the next item in list, last item in list will point to None # adding is easiest to head, because will have the head pointer class Node: def __init__(self, data): self.data = data self.next = none def getData(self): return self.data def g...
# all recursive algorithms must obey three important laws: # A recursive algorithm must have a base case. # A recursive algorithm must change its state and move toward the base case. # A recursive algorithm must call itself, recursively. def sum_list_recursively(num_list): """Sum numbers in a list using recursio...
"""Reverse a string using recursion. For example:: >>> rev_string("") '' >>> rev_string("a") 'a' >>> rev_string("porcupine") 'enipucrop' """ def rev_string(s): """Return reverse of string using recursion. You may NOT use the reversed() function! """ # can put new_string a...
def string_validator(s): """Return t/f for if s contains lowers, uppers, digits, etc""" t = type(s) for method in [t.isalnum, t.isalpha, t.isdigit, t.islower, t.isupper]: print any(method(char) for char in s)
# anagram puzzle # doesn't quite work this way because of examples like 'baab' # def is_anagram_of_palindrome(word): # """ # >>> is_anagram_of_palindrome("a") # True # >>> is_anagram_of_palindrome("ab") # False # >>> is_anagram_of_palindrome("aab") # True # >>> is_anagram_of_palindro...
def calculateScore(text, prefixString, suffixString): """ >>> calculateScore('nothing', 'bruno', 'ingenious') """ pass def calculate_prefix_score(string1, string2): """ >>> calculate_prefix_score('nothing', 'bruno') 2 """ prefix = '' prefix_start = string1[0] start_pre_ma...
# def array_sum(lst): # for i in xrange(len(lst)): # if sum(lst[:i]) == sum(lst[i+1:]): # return "YES" # else: # # print sum(lst[:i]), sum(lst[i+1:]) # continue # return "NO" # above solution times out on HR # better solution: def equal_sums_on_sides_of_in...
class Digraph: class RandomizedQueue(): def __init__(self): self.RandomizedQueue = [] self.size = 0 def isEmpty(self): return self.RandomizedQueue == [] def enqueue(self, item): self.RandomizedQueue.append(item) self.size += 1 ...
class Shell(): @staticmethod def sort(a): N = len(a) h = 1 while h <= N/3: h = 3*h + 1 while h >= 1: i = h while i < N: j = i while j >= h and Shell.less(a[j], a[j-h]): Shell....
import random class Shuffle(): @staticmethod def shuffle(a): N = len(a) i = 0 while i < len(a): r = random.randint(0,i) Shuffle.exch(a, i, r) i += 1 @staticmethod def exch(a, i, j): swap = a[i] a[i] = a[j] a[j] = swa...
from sklearn.datasets import load_digits from sklearn.svm import SVC from sklearn.model_selection import validation_curve,train_test_split from sklearn.model_selection import learning_curve from sklearn.neighbors import KNeighborsClassifier from sklearn.externals import joblib import matplotlib.pyplot as plt import num...
ficha = [] temp = [] while True: nome = str(input(' Nome : ')).strip().capitalize() n = int(input('Quantas notas deseja cadastrar :')) nota = media = s =0 for i in range(0,n): nota = float(input(f' Digite a {i+1}ª nota : ')) s += nota temp.append(nota) media = s/n ficha.a...
#contador de vogais em tupla palavras = ('PANDEMIA', 'CORONA', 'VIRUS', 'BRASIL', 'PRESIDENTE', 'DESGOVERNO', 'MORTES', 'CRISE', 'ECONOMIA') for p in palavras: print(f'Na palavra {p} temos as vogais . . . . . ',end=' ') for letra in p: if letra in 'AEIOU': print(f'{...
from pip._vendor.distlib.compat import raw_input from random import randint escola = [[],[],[]] aluno = {} notas = {} def cadastro_aluno(): print('-'*30) aluno['matrícula'] = randint(1, 1000) aluno['nome'] = raw_input("Nome : ") aluno['idade'] = int(input("Idade : ")) aluno['ano'] = int(input('ano: ')) ...
""" 'button.py' module. Used in the creation of all the buttons in the program. """ from .constants import pg, FONT_SMALL_PLUS, WHITE, HOVER_SOUND class Button: """Button instance class implementation.""" def __init__(self, rect_size, color, text): """ Button instance constructor. :pa...
""" 'missile.py' module. Used in creating the cannon missile body and shape. """ from math import pi, pow, degrees import pymunk as pm from pymunk.vec2d import Vec2d from .constants import MISSILE_DRAG_CONSTANT from .sprite_class import Sprite class Missile(Sprite): """Missile Sprite subclass implementation.""" ...
import matplotlib.pyplot as plt class Pie: def __init__(self, labels, data, title): self.labels = labels self.data = data self.title = title def make_pie(self, out_path, name): fig1, ax1 = plt.subplots() ax1.pie(self.data, labels=self.labels, autopct='%1.1f%%', ...
class Matrix(object): def __init__(self,num_rows = 2,num_cols = 2): ''' initilaizes rows, columns, and array ''' self.num_rows = num_rows self.num_cols = num_cols try: if type(num_rows) == int and type(num_cols) == int:#check if rows and colu...
class Privileges: """A simple attempt to model a privileges for an admin.""" def __init__(self, privileges=['can add post', 'can delete post', 'can ban user']): """Initialize the battery's attributes.""" self.privileges = privileges def show_privileges(self): """Show all privil...
def print_models(unprinted_desing, completed_models): """ Simulate printing each design, until none are left. Move each design to completed_models after printing. """ while unprinted_desing: current_design = unprinted_desing.pop() print(f"Printing model: {current_design}") c...
# A named tuple type has a few attributes in addition to those inherited from tuple . # Example 2-10 shows the most useful: the _fields class attribute, the class method # _make(iterable) and the _asdict() instance method. from collections import namedtuple City = namedtuple('City', 'name country population coordinat...
symbols = '$¢£¥€¤' # using list comprehension beyond_ascii = [ord(code) for code in symbols if ord(code) > 127] print(beyond_ascii) # using filter and map beyond_ascii = list(filter(lambda x: x > 127, map(ord, symbols))) print(beyond_ascii)
items = ['laptop', 'mobile', 'computer', 'hony', 'rabbi', 'piash', 'borna'] print('The first three item in the list are:') for item in items[:3]: print(item) print('The items from the middle of the list are:') for item in items[2:]: print(item) print('The last three items in the list are:') for item in items[...
alien_0 = {'color': 'green', 'point': 5} print(alien_0['color']) print(alien_0['point']) print(alien_0) # alien_0 = {'color': 'red'} # print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) print(f"The alien is {alien_0['color']}") alien_0['color'] = 'yellow' print(f"The alien is now {...
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('canoli') friend_foods.append('ice cream') print('My favorite foods are:') print(my_foods) print('\nMy frieds favorite foods are:') print(friend_foods) s_foods = my_foods s_foods.append('jalkd') print(my_foods) print(s_foods)
def show_messages(messages): """Show all messages is in list""" for message in messages: print(message) def send_messages(messages, sent_messages): """Display all send message and add every message in new list""" while messages: current_message = messages.pop() print(f"Send suc...
def cipher(direction , shift, message): if direction == "encode": shift_text ="" for char in message: value = alphabets.index(char) shift_num = value+shift shift_text = shift_text + alphabets[shift_num] print(shift_text) elif direction =="decod...
class A: def __init__(self,a): self.a=a # print a def __str__(self): return str(self.a) def s(self): return self.a**2 def __del__(self): pass b=A(10) print b print b.s() del b #print b
import json class Matrix: def __init__(self,array): self.array=array def __add__(self,other): if len(self.array)==len(other.array): new_matrix=[] for i in range(2): row=[] for j in range(2): row.append(self.array[i][j] + other.array[i][j]) new_matrix.append(row) return Matrix(new_matrix)...
var=raw_input("enter the month") my_dict={'jan':[31,23],'feb':28,'mar':31,'apr':30,'may':31,'jun':30,'jul':31,'aug':31,'sep':30,'oct':31,'nov':30,'dec':31} print my_dict[var]
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * #As we know, a Cube has 8 vertices and 12 edges """All we have to do, is define the basic structure of an object and feed it to OpenGL, which will create the appropriate 3D Model for it """ #8 Vertices. Each vertex is a tupl...
def make_album(artist_name, album_title, num_tracks = ''): album = {'name' : artist_name, 'title' : album_title} if num_tracks: album['tracks'] = num_tracks return album while (True): artist_name = input("\nInput the artist name ('q' to quit): ") if (artist_name == 'q'): break; ...
class Restaurant(): """A simply attempt to model a restaurant.""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): print("The name of the restaura...
friends = ["Yanbai", "Wanggang", "Chenhongyun"] message1 = "How are you, " +friends[0] + "?" print(message1) message2 = "在四川过好吗, " +friends[1] + "?" print(message2) message3 = "How is the house price in Shanghai, " +friends[-1] + "?" print(message3)
def make_sandwich(size, *fillings): """Summarize the sandwich we are about to make.""" print("\nMaking a " + size + "-size sandwich with the following fillings:") for filling in fillings: print("- " + filling) make_sandwich('large', 'Beef') make_sandwich('small', 'Pork', 'Onion', 'Pota...
transportation = ["Car", "Helicopter", "Ship"] message1 = "I like traveling by " +transportation[0] + "." print(message1) message2 = "However,my wife like traverling by " +transportation[-1] + "." print(message2) message3 = "We dream that some day we could by our own " + transportation[-2] + "." print(message3)
""" This is The Internship Program Developer Exam 2019 """ import xmltodict, json, os def main(): """ This is MAin Function """ print("Please input name of file XML: ", end="") name = input() for filename in os.listdir(): #loop to find file.XML in path directoy if filename.endswith(name+".xml")...
''' Arithmetic Addition + Substraction - Multiplication * Devision / Floor devision // Modulus % Exponential ** #trying on int data1 = 100 data2 = 2 print(data1 + data2) print(data1 - data2) print(data1 * data2) print(data1 / data2) print(data1 // data2) print(data1 % data2) pr...
value = 100 denominator = 10 d = {} try: div = value/ denominator print(div) try: raise IOError except: print("nested except") print(d[1]) except ZeroDivisionError as e: denominator = denominator + 1 div = value/ denominator print("Congrats !! your code have a Zero...
var1 = 'Hello World!' #reverse a string #string[::-1] #string[start:stop:step] print("var1[0]: ", var1[0]) print("var1[1:5]: ", var1[1:5]) #capitalize - first alphabet to upper print(var1.capitalize()) #length of string print(len(var1)) #check end of string suffix = "d!"; print(var1.endswith(suffix)) #find strin...
''' Iterables When you create a list, you can read its items one by one. Reading its items one by one is called iteration: Generators are iterators but you can only iterate over them once. Its because they do not store all the values in memory, they generate the values on the fly Yield is a keyword that is use...
data = [1, 2, True,"Nirmal Vatsyayan", 2.4, ["ok"]] print(type(data)) for value in data: print(value," type is ",type(value)) data = [] #append a value in list data.append(1) print(data) #extending a list by adding all value from another list new_data = [1000,111,1] data.extend(new_data) print(data) #insert in...
'''operator overloading error example, file doc''' class Student(object): '''this is an awesome student class''' def __init__(self, name, roll_number): self.name = name self.roll_number = roll_number def message(self): '''this is comment for message function''' print(self.n...
import numpy as np a = np.array([1, 2]) b = np.array([2, 1]) print(a*b) print(np.sum(a*b)) print((a*b).sum()) print(np.dot(a, b)) #dot function is also instance method print(a.dot(b)) print(b.dot(a))