text
stringlengths
37
1.41M
# PROGRAM TO READ AND WRITE DATA FROM A FILE in_data = open("sample1.txt", "w") in_data.write("Welcome to the world of Python") print("---After writing to file DATA : ", in_data) in_data.close() out_data = open("filename.txt", "r") out_data = out_data.read() print("---Reading from file : ", out_data) # out_data.clo...
import json import os ''' convert python dict to json ''' dict1 ={'Students':[ {'id': 128302, 'name': 'Ram', 'salary': 123947, 'designation': 'Python Developer'}, {'id': 128300, 'name': 'Ram Kumar', ...
class Counter(object): def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.cur...
""" import pickle d={'Name':'Ram','Course':'Python','fee':25000} """ def is_palindrome(word, in_pos): try: if len(word) >= in_pos: print("Position with", in_pos, " value is :", word[in_pos - 1]) else: raise ValueError("Value does not exist") for each in range(0, len...
def math_sum(l): sum_ = 0 for i in l: sum_ += i return sum_ s = [1, 2, 3, 4, 5] print('Sum of list is', math_sum(s)) print(__name__)
s = input('Enter a test string:') print('Length of a string:', len(s)) print('-------------Indexing of string---------------') i = input('Enter a character to know index:') print('Index of a string:', s.index(i)) print('Index of a string (from Right side):', s.rindex(i)) print('-------------Slice Operator of string----...
# 1 num = [2, 3, 7, 4, 5, 6, 10, 11, 120] # 2 largest_num = num[0] second_largest_num = num[0] third_largest_num = num[0] # 3 for i in num: # 4 if i > largest_num: third_largest_num = second_largest_num second_largest_num = largest_num largest_num = i # 5 elif i > second_larges...
# Palindrome with different logic string = input('Enter a text string:') length = len(string) rev_string = '' for i in range(-1, (-length - 1), -1): substring = string[i] rev_string += substring if rev_string == string: print('Entered string is a Palindrome!') else: print('Entered string is not a Palind...
# https://www.programiz.com/python-programming/generator """ What are generators in Python? => There is a lot of overhead in building an iterator in Python We have to implement a class with __iter__() and __next__() method, keep track of internal states, raise StopIteration when there was no values to be r...
s = 'Hello world' n = "Hi! Madam, how are you doing?" k = '''Hi! Divyasri, How are you? I'm waiting here Come to my home.''' print(s) print('\n', n) print('\n', k) print('-----------Concadinating all string-------------') print('\n', s, '\t' + n, '\t' + k) print('---------Replications of all string--------------') ...
def check_str(s): char_count = {} for char in s: if char not in char_count and char != ' ': char_count[char] = s.count(char) print(char_count) def check_U_L(s): str_1 = list(s) upper_l = 0 lower_l = 0 ul = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') # ll = list('abcdefghijkl...
import random import time import copy size1 = 100 size2 = 10000 size3 = 1000000 span = 1000000 threshold = 20 # --------------------------------------- # Insertion Sort # --------------------------------------- # not optimized, equiv to while version below, but uses for loop def insertion_sort1(A): for i in rang...
""" Tuples: ======= A Tuple is a immutable data structure and a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable. Python has two built-in methods that you can use on tupl...
def outer(func_name): a = 10 def inner(x, y): result = func_name() return result return inner @outer def add_nums(a, b): a, b = 10, 5 return a + b a = add_nums(50, 70) print(a)
nan = float('nan') inf = float('inf') # Function to add two numbers def add(num1 = nan, num2 = nan): try: num1 = float(num1) num2 = float(num2) except ValueError: return 0 addition = num1 + num2 return addition # Function to subtract two numbers def subtract(num1 = nan, num2 = nan): try: num1 = float(n...
# Filename: q3_miles_to_kilometre.py # Name: Ng Cheryl # Created: 20130121 # Modified: 20130127 # Description: Program to read a distance in miles # and converts it to kilometres # main while True: # prompt to get distance in miles distance = float(input("\nPlease enter distance in miles:")) # store value of...
# Filename: q07_miles_to_kilometres.py # Name: Ng Cheryl # Created: 20130203 # Modified: 20130203 # Description: Program that displays two tables side by side # converting miles to kilometres and kilometres to miles # main # display heading print ("Miles Kilometres Kilometres Miles") # loop 10 times for i in range(1...
# Filename: q7_find_largest.py # Name: Ng Cheryl # Created: 20130227 # Modified: 20130227 # Description: recursive function find_largest(alist) # that returns the largest integer in an array alist. # initialise variable to store largest integer largest = 0 # define method def find_largest(alist): """ function to ...
# Filename: q4_print_reverse.py # Name: Ng Cheryl # Created: 20130225 # Modified: 20130228 # Description: recursive function reverse_int(n) that reverses the digits of an integer n # define function def reverse_int(n): """ Function to reverse digits of an integer""" # terminating case if n<10: ...
# Filename: q02_triangle.py # Name: Ng Cheryl # Created: 20130203 # Modified: 20130203 # Description: Program that reads three edges for a triangle # and determines whether the input is valid # and prints perimeter when valid and invalid if invalid # main while True: # declare an empty list triside = [] # in...
from enum import Enum, auto class TokenType(Enum): # Single-character tokens. LEFT_PAREN=auto() RIGHT_PAREN=auto() LEFT_BRACE=auto() RIGHT_BRACE=auto() COMMA=auto() DOT=auto() MINUS=auto() PLUS=auto() SEMICOLON=auto() SLASH=auto() STAR=auto() # One or two character ...
# 3rd party library from math import pi def deg_to_rad(deg): '''Convert degrees to radians''' return deg * pi / 180.0 def clamp(x, min, max): '''Restrict a value between a minimum and a maximum value''' if x < min: return min if x > max: return max return x
# get the weather URL # give the City as input # output should print Weather, Temperature, Humidity, Wind Speed info import requests import json API_KEY = "6c7b5cdc8b366b3d4ef06f90ca952766" city_name = input("Enter City Name > ") URL = f"api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units...
# Given an array with N-non negative integers and lower and upper limits # R1 and R2 resp. Find the numbers R1<= NUM <=R2 from typing import Counter def give_ele(req): Count = 0 for i in range(len(x)): if i >= R1 and i <= R2: Count += 1 print(Count) # num = int(input("> ")) x...
# number = int(input("Enter Number: ")) # factorial = 1 # if number < 0 : # print("Factorial does not exits for negative numbers") # elif number == 0 : # print("Factorial of 0 is 1") # else: # for i in range(1, number+1): # factorial = factorial * i # print(str(factorial)) def fact(n): ...
letter='''Dear 'Name' You are selected. All the best Date: 'Date' ''' name=input("Enter your name:\n") date=input("Enter Date:\n") letter=letter.replace("'Name'",name) letter=letter.replace("'Date'",date) print(letter)
#!/usr/bin/python """ turtle-example-suite: tdemo_fractalCurves.py This program draws two fractal-curve-designs: (1) A hilbert curve (in a box) (2) A combination of Koch-curves. The CurvesTurtle class and the fractal-curve- methods are taken from the PythonCard example scripts for turtle-graphics. """ f...
#!/usr/bin/python """ turtle-example-suite: tdemo_paint.py A simple eventdriven paint program - use left mouse button to move turtle - middle mouse button to change color - right mouse button do turn filling on/off ------------------------------------------- Play around by clicking into the canv...
''' 本程式檔名: moduleTranslate.py= autoTurtle.py IO: turtle.py ----> turtle_tc.py 吃進: turtle_tc_alias.py turtle_docstringdict_tc.py 2016/07/03 ''' ''' 改為輸出turtle_tc檔 本身不再被當作漢化導入執行 2015/12/5 直接執行程式會輸出turtle_c檔 當為import時才不會輸出 2015/11/18 已加上中文說明 2015/11/17 增加輸出一個turtle_c檔 可直接取代turtle_tc運行 裡面仍需導入turtle模組...
#!/usr/bin/python """ turtle-example-suite: tdemo_sierpinski1.py This program draws a coloured sierpinski triangle. Each vertex of the triangle is associated with a color - in the case of this example red, green and blue. The colors of the triangular cells of the Sierpinski triangle are computed by i...
#!/usr/bin/python # 預設編碼為 utf-8 """ turtle-example-suite: tdemo_clock.py Enhanced clock-program, showing date and time ------------------------------------ Press STOP to exit the program! ------------------------------------ """ from turtle_tc import * from datetime import datetime 模式(角度從北開...
""" A command line interface (CLI) to perform tasks for people running the client locally. Functionality: 1. Dump data to a CSV file. """ import pandas as pd from datetime import datetime, date from pandas.errors import EmptyDataError from psycopg2.errors import UndefinedTable from config import summary_js...
#Mostrar por la pantalla la suma de los multiplos de 3 y 5 entre 10 #entre 100 y entre 1000. print('--------RETO 1-------'); sumMul = 0; print('Multiplos de 3 y 5 del 1 al 10'); for x in range(1,10): if x % 3 == 0 or x % 5 == 0: sumMul = sumMul + x; print x; #Los imprime dando saltos...
""" 6: Udvid programmet fra opgave 5, så det kan gemme dictionary’en i en tekstfil. Den skal gemme hvert key, value på sin egen linje. Vælg selv navnet på denne tekstfil. """ from exercise2 import Chokolade_cheesecake_med_marengslaeg as kage # Denne er mere kompleks, end hvad der behøves def print_dict(d, level=0, fi...
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 2020 Vi skal lave et program som gør følgende: Lav en dictionary med fornavn, efternavn, alder og by for en person (vælg selv hvilken). Print derefter de enkelte elementer i denne dictionary. Tilføj et key-value par til denne dictionary, f.eks. uddannelsessted Slet...
""" 5: Ændr loopet som du lavede i opgave 4, så ingredienserne bliver printet i alfabetisk rækkefølge. """ from exercise2 import Chokolade_cheesecake_med_marengslaeg as kage # Denne er mere kompleks, end hvad der behøves def print_dict(d, level=0): for key in sorted(d): if type(d[key]) == dict: print(f"{key}:")...
def find_missing(list1, list2): if len(list1) == 0 or len(list2) == 0: return 0 elif list1 == list2: return 0 else: if len(list1) > len(list2): first_list = list1 second_list = list2 else: first_list = list2 second_list = list1 ...
print("enter a number:") prime = True n = int(input()) if n == 1 or n == 2: prime = True else: for i in range(2,int(n/2)+1): if n%i == 0: prime = False break if not prime: print(n,"is not a prime number") else: print(n, "is a prime number")
import random l = ['rock','paper','scissor'] print("Enter your name: ") name = input() print("Hi",name,",let's play rock,paper and scissor.") c='y' while c == 'y': print("What you choose?") ch1 = input() i=random.randint(0,2) print("i=",i) ch2=l[i] print("ch1=",ch1) print("ch2=",ch2) if ...
from array import * def hoare_quick_sort(arr, low ,high): pivot = arr[low] i = low -1 j = high +1 while True: j = j-1 while arr[j] > pivot: j = j-1 i = i+1 while arr[i]< pivot: i= i+1 if i < j: arr[i],arr[j] = arr[j],arr[i]...
def exibir_menu(): print('''Escolha uma opção: 1. Cadastrar Paciente 2. Mostrar pacientes cadastrados 3. Buscar paciente ''') def cadastrar(pessoas): identificador = input('Defina um id para este paciente: ') nome = input('Nome: ') idade = int(input('Idade do paciente: ')...
""" This program prints a series of random numbers in the range from MIN_RANDOM to MAX_RANDOM. """ import random NUM_RANDOM = 10 MIN_RANDOM = 0 MAX_RANDOM = 100 def main(): for i in range(NUM_RANDOM): result = random.randint(MIN_RANDOM, MAX_RANDOM) print(result) # This provided line is required ...
# Copyright 2020 Joseph Kularski # Workspace for Advent of Code 2020 # Request permission before using or duplicating this code for any purpose def main(): f = open("input.txt", "r+") file_lines = f.readlines() pw_correct = 0 pt2_correct = 0 for x in file_lines: # split string ...
numbers = input("How many numbers you want to calculate? ") grade_list = [] def evaluate(): for i in range (numbers): grades = float(input("Please enter a number between 1-1000: ")) while grades < 0 or grades > 1000: print ("The number " + str(grades) + " is out of range") g...
class Node: def __init__(self, data=None): self.data = data self.left = None self.right = None class BST: def __init__(self): self.root = None #self.message = "found:" def insert(self, data): if self.root is None: self.root = Node(...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: if len(inorder) == 0: ...
''' Check for 4 repeating numbers in an NxN matrix row-wise, column-wise or diagonally Return true if found, else false ''' def checkio(matrix): vector = [] cols = list(zip(*matrix)) rows = matrix for m in matrix: vector += m uniques = set(vector) diagonalsnw, diagonalsne = ...
''' You are given an expression with numbers, brackets and operators. For this task only the brackets matter. Brackets come in three flavors: "{}" "()" or "[]". Brackets are used to determine scope or to restrict some expression. If a bracket is open, then it must be closed with a closing bracket of the same type. The ...
import string def to_encrypt(text, delta): #replace this for solution num_to_text = dict(enumerate(string.ascii_lowercase,start=0)) num_to_text[100] = ' ' len_alphabet = len(string.ascii_lowercase) ascii_to_num = {string.ascii_lowercase[i-1]:((i+delta-1) % len_alphabet) \ for i ...
import re def checkio(data: str) -> bool: upper = re.search("[A-Z]+",data) lower = re.search("[a-z]+",data) digits = re.search("[0-9]+",data) if upper is None: return False if lower is None: return False if digits is None: return False if (len(data)<10): retu...
''' Mission is to calculate the probability of X dice with N sides to have the total sum of S ''' from math import factorial from functools import reduce from itertools import combinations_with_replacement def probability(dice_number, sides, target): dice_throw = range(1,sides+1) unique_throws = combinatio...
def checkio(str_number: str, radix: int) -> int: list_numbers = [] return_sum = 0 for char in str_number: if ord(char)> 64: list_numbers.append(ord(char)-55) else: list_numbers.append(int(char)) list_numbers = list_numbers[::-1] for i in range(len(list_numbers...
#My details print("Name : "+"Somil"+" Swapnil"+" Chandra"); print("College : "+"DIT"+" University"+" Dehradun") #Initialization maths=90; eng=88; hindi=90; chem=97; comp=95; #Calculating total total=maths+hindi+eng+chem+comp; #Calculating percentage p=total/5*100; #Displaying result print("Total Marks : ",tota...
import os import datetime import glob path = input("enter_path_here: ") today = datetime.datetime.today()#gets current time os.chdir(path) #changing path to current path(same as cd command) #we are taking current folder, directory and files #separetly using os.walk function for root,directories,files in o...
for i in range(10): print("hello world") """ i 浪費了,沒用到 """ print("-" * 50 + "\n") # ----------------------- for _ in range(10): print("hello world") print(_) # 臨時變數 print("-" * 50 + "\n") # ----------------------- x, y, *_ = [1, 2, 3, 4, 5] print(x, y, _) print("-" * 50 + "\n")
dict1 = { "zhao": 68, "qian": 80, "sun": 72, "li": 90, "zhou": 83, "wu": 79, "zheng": 95, "wang": 82 } print(dict1) print("-" * 50 + "\n") # sort dict # dict1.items().sort(key= lambda item : item[0]) # error dict1_sorted_by_key = sorted(dict1.items(), key= lambda item: item[0], reverse...
# 使用 ** 建立可變參數函式 def formMolecules(**kwargs): if len(kwargs) == 2 and kwargs["hydrogen"] == 2 and kwargs["oxygen"] == 1: return "water" elif len(kwargs) == 1 and kwargs["unobtanium"] == 12: return "aether" print(formMolecules(hydrogen=2, oxygen=1)) print(formMolecules(unobtanium=12)) print(form...
class Animal: def __init__(self, name, age=1): self.name = name self.age = age def sing(self): print(self.name + " " + str(self.age) + "歲,很會唱歌!") def grow(self, year=1): self.age += year bird1 = Animal("bird1") bird1.grow() bird1.sing() bird2 = Animal("bird2", 2) bird2.grow(...
s = 'konnnitiha mike' print(s) is_start = s.startswith('k') print(is_start) print(s.find('mike')) print(s.rfind('iti')) print(s.capitalize()) print(s.title()) print(s.upper()) print(s.replace('mike', 'jon')) print(s) r = [1,2,3,4,5,1,2,3] x = r.index(3,0) print(x) if 51 in r: print('exist') r.sort() print(r) ...
""" This problem was asked by Slack. You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the bottom right corner? You can only move right and down. 0 represents an empty space while 1 represents a wall you cannot walk through. For example, given the follow...
""" This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our i...
class Stack: def __init__(self): self.data = [] def push(self, record): self.data.append(record) def peek(self): if self.data: return self.data[-1] else: return None def size(self): return len(self.data) def pop(self): if s...
def multiplicarRecusivo(num, factor): if isinstance(num, int): if (factor == 0): return 0 elif (factor == 1): return num elif (factor < 0): return - multiplicarRecusivo(num, -factor) else: return num + multiplicarRecusivo(num, ...
# Copyright 2015 Lawrence Kesteloot # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
def write_grayscale(filename, pixels): """creates a grayscale BMP file""" height = len(pixels) width = len(pixels[0]) with open(filename, 'wb') as bmp: #BMP Header bmp.write(b'BM') size_bookmark = bmp.tell() bmp.write(b'\x00\x00\x00\x00') bmp.write(b'\x00\x00') bmp.write(b'\x00\x00') ...
import requests from bs4 import BeautifulSoup url = "https://temple.campuslabs.com/engage/organizations" #download the URL and extract the content to the variable html response = requests.get(url, cookies={'__test': '2501c0bc9fd535a3dc831e57dc8b1eb0'}) html = response.content print(html) #pass the HTML to Beautifulso...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 79.py # @Author: guolei # @Time : 02/07/2019 3:24 PM # @Desc : # @Ans :回溯法,深度优先搜索 class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ mark = ...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 34.py # @Author: guolei # @Time : 01/05/2019 11:11 AM # @Desc :在排序数组中找目标元素的起始及结束位置。思路,先二分查找到一个该数的位置,然后对该数左边,找等于target且位置最小,右边等于target且位置最大的target,最后进行位置组合。 class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] ...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 206.py # @Author: guolei # @Time : 20/07/2019 2:59 PM # @Desc :反转链表 # @Ans :迭代法,创建一个节点存储下一个位置 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): ...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 86.py # @Author: guolei # @Time : 16/07/2019 6:07 PM # @Desc : # @Ans :创建两个链表,分别是小于x链表和大于x链表,遍历完把小于x的链表的尾指针指向大于x链表的头指针,核心点 创建哑指针 # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = No...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 77.py # @Author: guolei # @Time : 26/06/2019 9:07 PM # @Desc : # @Ans :回溯法 class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ res = [] def f(start,...
#!/usr/bin/python # -*- coding: utf-8 -*- # @File : 70.py # @Author: guolei # @Time : 02/05/2019 7:10 PM # @Desc :爬楼梯 # @Ans :DFS,深度优先搜索,超时了竟然……,用动态规划,res[i] = res[i-1] + res[i-2],表示最后一次是在前一个台阶跳一步(1台阶) ,或者 前两个台阶跳一步(2台阶) import collections class Solution(object): def climbStairs(self,n): res = collectio...
import turtle window = turtle.Screen() def make_window(color, title): """ Set up the window with the given background color and title. Returns the new window. """ window = turtle.Screen() window.bgcolor(color) window.title(title) return window def make_turtle(color, size): """ ...
import turtle screen = turtle.Screen() fer = turtle.Turtle() def draw_star(t, size): t.left(36) for _ in range(5): t.forward(size) t.left(144) draw_star(fer, 100) fer.hideturtle() screen.exitonclick()
def find(strng, ch, start=0): index = start while index < len(strng): if strng[index] == ch: return index index += 1 return -1 def count_letters(word, letter): a = find(word, letter, 0) count = 0 while a != -1: a = find(word, letter, a+1) ...
#追加の座標(x0,y0) #線分の端点の座標1(x1,y1) #線分の端点の座標2(x2,y2) import math x0 = int(input()); y0 = int(input()); x1 = int(input()); y1 = int(input()); x2 = int(input()); y2 = int(input()); def distance(x0,y0,x1,y1,x2,y2): a = x2 - x1; b = y2 - y1; a2 = a * a; b2 = b * b; r2 = a2 + b2; tt = -(a*(x1-x0)+...
def rotateLeft(d, arr): # return arr[d:] + arr[:d] temp = [] n = len(arr) d = d%n for i in range(d): temp.append(arr[i]) print(temp) for i in range(n-d): arr[i] = arr[i+d] count = 0 for i in range(n-d, n): arr[i] = temp[count] count+=1 return a...
''' Program for quick sort ''' def piviot(a, start, end): piviot = end-1 e = piviot-1 i = start while i <= e: if a[i] > a[piviot]: a[i], a[e] = a[e], a[i] e -= 1 else: i += 1 a[piviot], a[i] = a[i], a[piviot] return i def quickSort(a, start, ...
''' Given a string, compute recursively a new string where all appearances of "pi" have been replaced by "3.14". Sample Input 1 : xpix Sample Output : x3.14x ''' def replacePi(s): if len(s) <= 1: return s if s[0:2] == "pi": return "3.14" + replacePi(s[2:]) else: return s[0] + replace...
def printMatrix(sol): for eachLine in sol: print(eachLine) print("-----------------") def hasPathHelper(maze, sol, x, y, n): if x == n-1 and y == n-1: sol[x][y] = 1 printMatrix(sol) return True if (x < 0 or y < 0 or x>=n or y >= n or maze[x][y]==0 or sol[x][y]==1): ...
""" def print_val(**kwargs): print type(kwargs) print kwargs print_val(a=10,b=20) def print_val(a,b=20): print a,b print_val(10,20) """ def print_vals(*args ): print("a:", a, "b:",b, "args:", args,"kwargs:", kwargs) print_vals(10, 20,30,40 )
from urllib import urlopen import sys def fetch_data(url): """This documentation will give url pattern of data""" try: w = urlopen(url) except: print("Bad URL") sys.exit(100) data = w.read() data_s = str(data) return data_s def fetch_word_count(url): """This documentation will give url pattern of data""" ...
def greet(name): '''this funvtion returns the name of a variable''' print 'hello'+' '+ name +' '+ 'good' greet('Nitesh') print greet.__doc__
f1 = open('file1.txt', 'r') val1 = f1.readlines() f2 = open('file2.txt', 'r') val2 = f2.readlines() for line1 in val1: if line1 not in val2: print line1 f1.close() f2.close()
""" List lesson """ s = "show how to index into sequences".split() for i in range(1, len(s) + 1): print(s[len(s) - i]) # is the same as print(s[-i]) ## Slicing an array ### seq[start:stop] -> start inclusive, stop exclusive y = s[1:4] print(y) ## Slicing with negative indices ### Takes everything except ...
print("what" "ever") multi = """ <html> <body> </body> </html> """ print(multi) # raw strings (no escaping) print(r'C:\Windows\System32\win.exe') #strings are arrays s = 'string' for i in range(len(s)): print(s[i]) c = 'oslo' print(c.upper()) ## All strings are unicode (UTF-8) based #byte literal b = b...
print "List implementation" #Lista declarada, vacia listX = [] #Lista declarada, con valores de diferentes tipos listY = ['y', 'n', 1, 0, True, False, '1'] #Esta lista contiene las dos anteriores listZ = listX + listY listY.append(1) listX.append('azul') listX.append('verde') listX.append('rojo') print listX.index('r...
#!/bin/bash/env python shu1 = input("台阶的倍数:") shu2 = int(shu1) while True: if (shu2*7)%2 == 1 and (shu2*7)%3 == 2 and (shu2*7)%5 == 4 and (shu2*7)%6 == 5: print("该台阶有%d阶" % (shu2*7)) break else: print("错误,请重新输入!") shu2 = shu2 + 1
#!/usr/bin/env python class Fridge: """This class implements a fridge where ingredients can be added and removed individually, or in groups. The fridge will retain a count of every ingredient added or removed, and will raise an error if a sufficient quantity of an ingredient isn't present. Methods:...
#!/usr/bin/env python def in_fridge (some_fridge,desired_item): """This is a function to see if the fredge has a food. fridge has to be a dictionary defined outside of the function. the food to be searched for is in the string wanted_food""" try: count = some_fridge[desi...
# # @lc app=leetcode.cn id=189 lang=python3 # # [189] 旋转数组 # from typing import List # @lc code=start class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) for _ in range(n - k % n): ...
from lc_types import ListNode, construct_linked_list, print_linked_list,\ TreeNode, print_tree from typing import List class Solution: def deleteDuplicatesii(self, head: ListNode) -> ListNode: if not head or not head.next: return head dummy = ListNode("", next=head) prepre,...
# 给你一个二进制矩阵 matrix ,它的大小为 m x n ,你可以将 matrix 中的 列 按任意顺序重新排列。 # # 请你返回最优方案下将 matrix 重新排列后,全是 1 的子矩阵面积。 # # # # 示例 1: # # # # # 输入:matrix = [[0,0,1],[1,1,1],[1,0,1]] # 输出:4 # 解释:你可以按照上图方式重新排列矩阵的每一列。 # 最大的全 1 子矩阵是上图中加粗的部分,面积为 4 。 # # # 示例 2: # # # # # 输入:matrix = [[1,0,1,0,1]] # 输出:3 # 解释:你可以按照上...
import os # how to print to a file instead of the console: # 't' mode opens the file as text file with open('file_io/test.txt', 'wt') as f: print('Hello World!\nHello Again', file=f) # use newline parameter to define new line signifier with open('file_io/test.txt', 'rt', newline='') as f: g = f.read() # writ...
for value in range(1,5): # "range()" starts from 1 and ends at 5, never containing 5 in return value print(value) for value in range(1,6): print(value) numbers = list(range(1,6)) # list() record each occurrence by range() print(numbers) print(list(range(1,20,3))) # the third parameter in range() give the ...
"test of equality" cars = ['audi','bmw','subaru','toyota'] for car in cars: if car == 'bmw': # double equality sign "==" is used for the testing print(car.upper()) # conditional tests to determine if a variable meets the condition else: print(car.title()) "test of inequality" requested_toppi...
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a ...
import sys import json def read_json(): if (len(sys.argv) < 2): raise Exception("You must give the json file as a system argument!") with open (sys.argv[1], 'r') as f: data = json.load(f) return data def checkKey(dict, key): if key in dict.keys(): return True return Fa...
def increasing_or_decreasing(seq): lst = seq[1:] is_increasing = all([lst[lst_index] > seq[lst_index] for lst_index in range(len(lst))]) is_decreasing = all([lst[lst_index] < seq[lst_index] for lst_index in range(len(lst))]) if is_increasing: return "Up" if is_decreasing: retu...
# copy the code from sum1.py into this file, THEN: # change your program so it keeps reading numbers until it gets a -1, then prints the sum of all numbers read # write a program that reads in 10 numbers, then prints the sum of those total = 0 run = True while run: try: x = int(input("Input a number: ")...