text
stringlengths
37
1.41M
""" This program is an example demonstrating finding duplicate files across many diirectories. At the end it print out list of duplicate files in the directories. Run this program is as shown below: $ python duplicate_file_finder.py dir1 dir2 dir3 dir4 ..... Eg. $ python duplicate_file_finder.py dir1 ...
''' Given A, B, C, find whether C is formed by the interleaving of A and B. Example: 1: A = "ab" B = "cd" C = "acdb" Here, C can be formed by the interleaving of A and B 2: A = "ab" B = "cd" C = "adbc" Here, C cannot be formed by the interleaving of A and B as 'd' and 'c' are coming out of orders in...
''' Topological sort with DFS: Start with any node in graph and add it to the head of a list L, if the node is not in L already do a DFS on the node's children (denoted by nodech) if nodech has children if some children are already in L, add nodech before \ the children with low...
#!/usr/bin/python import re notLetters = ('\'','"', ',', '.', '!', ' ', '\n','-','(',')',';',':','?','/','@','$','#','&',) count = 0 img = raw_input("what file? ") with open('data/'+str(img)+'.txt') as f: while True: c = f.read(1) if not c: break if c not in notLetters: #print c.upper() count += 1 p...
 import random ranTar=[0, 2, -2, 6, -6, 10, -10] #CJS 12/17/2016 sets=1 global frodo frodo = list() print ranTar[0] print frodo for x in range(1,sets+1, 1): random.shuffle(ranTar)#mix up the order frodo = frodo+[ranTar[0]] frodo = frodo+[ranTar[1]] frodo = frodo+[ranTar[2]] frodo = frodo+[ranTar[3]] frodo = fr...
def sierpinski(n): pattern = draw(n, 'L', 0) return pattern def draw(n, pattern, idx): """ Recursive function to draw the fractal until n is reached """ if idx == n: return pattern else: return draw(n, make_triangle(pattern), idx + 1) def make_triangle(pattern): """ Takes the pattern, then puts the pat...
# Form an array using np.arange which contains all even numbers. 10 to 30 import numpy as np array=np.arange(10,30,2) print("Array of all the even from 10 to 30") print(array)
# Get [1, 4, 5] from [[1, 2], [3, 4], [5, 6]] using indexing import numpy as np def extract(a_list): return a_list[0][0],a_list[1][1],a_list[2,0] arraylist = np.array([[1,2],[3,4],[5,6]]) print(extract(arraylist))
a=str(input("sA:")) b=str(input("sB:")) c=b.split(" ") n=c.count(a) if (n==1): print("子字串判斷為:YES") else: print("子字串判斷為:NO")
n=int(input("輸入一正整數:")) if(n%2==0 and n%11==0 and n%5!=0 and n%7!=0): print("%d為新公倍數?Yes"%n) else: print("%d為新公倍數?No"%n)
'''NON-RECURSIVE''' # def binpower(a,n): # res = 1 # cur = a # while n>0: # if n&1: # res *= cur # cur *= cur # n>>=1 # return res '''RECURSIVE''' def recubinpower(a,n): if n is 1: return a res = recubinpower(a,n//2) return res*res*(a if n%2 is not 0 else 1) a, n = input().split() a, n = int(a), int...
x = 0 if x < .0: print 'x must be atleat 0!' elif x == 0: print 'x equals to 0!' else: print 'x great than 0!'
user = raw_input('Enter login name:') print 'Your login is:', user num = raw_input('Now enter a number:') print 'Doubling your number: %d' % (int(num) * 2) help(raw_input)
#Desconto com juros, conforme escolha da forma de pagamento. print("{:=^40}".format(" LOJAS HELENA ")) preço = float(input("Digite o preço das compras R$ ")) print('''Formas de pagamento: [1] À VISTA - NO DINHEIRO OU CHEQUE [2] À VISTA - NO CARTÃO [3] 2 X NO CARTÃO [4] 3 X OU + NO CARTÃO ''') opção = int(inp...
student = { "name": "Arpista Banerjee", "age": "19", "location": "Kolkata", } student.clear() print(student) student = { "name": "Arpista Banerjee", "age": "19", "location": "Kolkata", } x = student.copy() print(x) a = ('key1', 'key2', 'key3') b = 0 dict1 = dict.fromkeys(x, y) print(dict1) ...
import numpy as np a = np.array([4, 10, 12, 23, -2, -1, 0, 0, 0, -6, 3, -7]) #1 print("There are", len(a[a < 0]), "negative numbers.") #2 print("There are", len(a[a > 0]), "positive numbers.") #3 b = a[a>0] print("There are", len(b[b%2 ==0]), "positive even numbers.") #4 c = a + 3 print("Adding 3 to each data point...
sum = 0 while True : num = int( input(" Enter Any Number : ")) sum = sum + num print(" Press 1 For Add Another Number ") choice = int( input(" Enter Your Choice : ")) if choice != 1: break print(" Sum of Given Number : " , sum )
year = int( input(" Enter Any Year : " )) # Normal year :- 365 days = 52 Weeks + 1 Day # Leap Year :- 366 days = 52 Weeks + 2 Day totaldays = ( year - 1 ) * 365 totaldays += ( year - 1 ) // 4 totaldays -= ( year - 1 ) // 100 totaldays += ( year - 1 ) // 400 rem = totaldays % 7 result = " On 1st January, " + str(yea...
hours = int( input(" Enter Hours : ")) minute = int( input(" Enter Minute : ")) minutes = hours * 60 + minute print(" Total Minute : " , minutes)
num = int( input(" Enter Any Number : ")) isprime = True range = num - 1 div = 2 while div <= range : if num % div == 0 : isprime = False div += 1 if isprime : print(" Given Number is Prime ") else : print(" Given Number is Composite ")
num = int( input(" Enter Any Five Digit Number : ")) temp = num rem = temp % 10 result = ( ( rem + 1 ) % 10 ) temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 10 + result temp = temp // 10 rem = temp % 10 result = ( ( rem + 1 ) % 10 ) * 100 + result temp = temp // 10 rem = temp % 10 result = ( ( ...
n1 = 432 n2 = 423 ans = n1 + n2 print(" The Answer : ans ") print(" The Answer : ", ans) print(" [ " , n1 , " + " , n2 , " = " , ans , " ] ")
print("how much miles you run...??") e=int(input()) f=e/1.60934 print(f"kilometers ranned: {e} converted to miles:{f}\n")
def check_validation(place, x, y): valid = True # 상하좌우 확인 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for d in directions: nx = x + d[0] ny = y + d[1] if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: continue if place[ny][nx] == 'P': # print(nx, ny,...
#! /usr/bin/env python # Revised Connection Example with Information retrival import socket print "Creating socket" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "done" print "Looking up port number" port = socket.getservbyname('http','tcp') print "done" print "Connecting to remote host on port %d .....
""" 言語処理100本ノック 2015 第1章: 準備運動 05. n-gram 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. """ def n_gram(text_sequence,n): """ 与えられたシーケンス(文字列やリストなど)からn-gramを作成 Args: text_sequence: 任意のシーケンス(文字列やリストなど) n: n-gramのn Raise: 特になし Return: ...
""" 言語処理100本ノック 2015 第1章: 準備運動 06. 集合 "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.さらに,'se'というbi-gramがXおよびYに 含まれるかどうかを調べよ. """ def n_gram(text_sequence, n): """ (05と共通)与えられたシーケンス(文字列やリストなど)からn-gramを作成 Args: str: 任意のシーケンス(文字列やリストなど) n: n-gramのn Raise: ...
""" 言語処理100本ノック 2015 第1章: 準備運動 07. テンプレートによる文生成 引数x, y, zを受け取り「x時のyはz」という文字列を返す関数を実装せよ.さらに,x=12, y="気温", z=22.4として,実行結果を確認せよ. """ def template(x,y,z): """ 指定された引数x、y、zをテンプレートに埋め込んで文字列を生成 Args: x,y,z: テンプレートに埋め込むデータ Raise: 特になし Return: テンプレートに引数で指定されたデータを埋め込んだ文字列 Note:  特になし ...
""" This script opens a simple GUI that allows a user to find the proper bike size for different sorts of bikes using the cyclist's measurements and preferences.""" from Tkinter import * import ttk import bikesizecalculator # Calls the bikesizecalculator method. Used for the button press def findbikes(): sear...
n = int(input("enter the no.\n")) fact=1 if(n==1 or n==0): print("factorial",fact) elif(n<0): "enter a positive integer" else: for i in range(n): fact = fact*n n=n-1 print("factorial of {} is:".format(n),fact)
year = int(input("enter the year:\n")) if((year%400 == 0) or ((year%100 != 0) and (year%4 == 0))): print(year,"is leap year") else: print(year, "not a leap year")
# # @lc app=leetcode id=201 lang=python # # [201] Bitwise AND of Numbers Range # # https://leetcode.com/problems/bitwise-and-of-numbers-range/description/ # # algorithms # Medium (35.72%) # Total Accepted: 79.9K # Total Submissions: 223.5K # Testcase Example: '5\n7' # # Given a range [m, n] where 0 <= m <= n <= 214...
import pandas as pd import numpy as np # Numpy Examples import numpy as np Nump_Array = np.array([[1,2,3],[4,5,6]]) print(Nump_Array) Nump_Array+=2 print(Nump_Array) #declare list of values list_of_strings = ["5","6","7","8","9", "10"] #declare empty list to store converted values result = [] #'not memory ef...
''' Program to turn off n number of bits ''' import my_util as util def turnoff_n_bits(num, pos, no_of_bits): return num & ~ ( (2 ** no_of_bits - 1) << (pos - no_of_bits) ) if __name__ == '__main__': num = int(input("Enter Number: ")) print('BINARY REPRESENTATION: ', util.decimal_to_binary(num)) p...
# Ali Shahdi # Coding test from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import urllib2 import json # Class for handling REST APIs class RESTHandler(BaseHTTPRequestHandler): # Generating the header for HTTP response def _set_headers(self): self.send_response(200) self.send_header('Conte...
from PIL import Image, ImageDraw import random as random my_map = Image.new('RGB', (600, 600), color=(0, 0, 0)) draw = ImageDraw.Draw(my_map) with open('elevation_small.txt') as file: # Use file to refer to the file object data = file.readlines() elevations = [[int(each) for each in line.split()] for line in data]...
# --- Lists---- # int, str : building blocks # list: data structures # list is a collection of items in a particular order # inside a list: numbers, strings, numbers and strings # -- creating list #0 #1 #2 #3 bicycles = ['trek','cannon','redline','specialized'] #-4 #-3 #-2 #-1 print(bic...
#사용자로부터 하나의 값을 입력받은 후 해당 값에 20을 뺀 값을 출력하라. 단 값의 범위는 0~255이다. 0보다 작은 값이되는 경우 0을 출력해야 한다. user = input("입력값: ") num = int(user) - 20 if num > 255: print(255) elif num < 0: print(0) else: print(num)
import sys max = -sys.maxsize -1 min = sys.maxsize num = [8,7,3,2,9,4,1,6,5] for i in range(len(num)): if min >= num[i]: min = num[i] if max <= num[i]: max = num[i] print("최댓값 :", max) print("최솟값 :", min)
def pow_xy(x,y): res = x**y return res print("3 * 2**4 + 5 =",(3 * pow_xy(2,4) +5))
import turtle as t t.shape("turtle") t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position()) t.write(t.position()) t.forward(100) t.write(t.position()) t.left(90) t.forward(100) t.write(t.position()) import turtle as t t.shape("turtle") t.write(t.positi...
import turtle as t def draw_pos(x,y): t.clear() t.setpos(x,y) t.stamp() hl = -(t.window_height() / 2) tm = 0 while True: d = (9.8 * tm**2) / 2 ny = y - int(d) if ny > hl: t.goto(x,ny) t.stamp() tm = tm + 0.3 el...
import random import math from problemGenerator.Node import Node import matplotlib.pyplot as plt class Generator: """ This class is used to generate random problems to the Multiple Knapsack Problem for Package Delivery Drones ... Attributes ---------- nodes : List<Node> a ...
# Crash Course in Python # Author: Breanna McBean # How to create plots using Python # May 28, 2019 ############################################## # Plotting in Python import numpy as np import pandas as pd import matplotlib.pyplot as plt # The package matplotlib allows you to create plots similar to the w...
def ex1(): num=int(input("inputnumber")) x=0 while x < num: x+=1 print(x) def ex2(): num=int(input("inputnumber")) x=0 while x < num: x+=1 if n%x ==0: print(x)
""" The "Cell Layout": | 11 | 7 12 | 4 8 13 | 2 5 9 14 | 1 3 6 10 15 """ def log(arg): # Reminder foo.bar don't like print! print(arg) pass def solution(x, y): """ Retrieve the value at location (x,y) in that cell layout above. """ # Use something like the radial axis, or what we'll cal...
''' 15 puzzle problem States are defined as string representations of the pieces on the puzzle. Actions denote what piece will be moved to the empty space. States must always be immutable. We will use strings, but internally most of the time we will convert those strings to lists, which are easier to handle. For exam...
import numpy as np def read_mask(file): """Read in a Polar Stereographic mask file. Args: file (string): full path to a Polar Stereographic mask file Returns: A tuple containing data, extent, hemisphere data: a two-dimensional numpy array, nrows x ncolumns extent: A tuple...
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna) def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence...
#!/usr/bin/env python import argparse import re import sys def find_color(data, color): bags = [] for k in data: if color in data[k]: bags.append(k) return bags def count_containing_bags(data, color): """ Depth First Search Recursive """ # print(path) total = 1 ...
#!/usr/bin/env python import argparse def main(args): costs = list() with open(args.input, 'r') as fh: for line in fh: line = line.rstrip() costs.append(int(line)) for z, entry in enumerate(costs): diff1 = 2020 - entry for y, entry2 in enumerate(costs): ...
print("Bienvenidos al transformador de Farenheit a Celsius.") Faren = float(input("Introduce grados Farenheit: ")) Cel = (Faren - 32) / 1.8 print("{} grados Farenheit son {} grados Celsius".format(Faren, Cel))
#Crear un programa que guarde e imprima varias listas y sean múltiplos de 2, de 3, de 5 y de 7. lista_user = input("Introduce un numero: (Escribe 'go' para iniciar) ") lista_numeros = [] while lista_user != 'go': if lista_user.isdigit(): lista_numeros.append(int(lista_user)) lista_user = (input("I...
pokemon_elegido = input("¿Contra que pokemon quieres luchar? (Squirtle / Charmander / Bulbasaur):").upper() vida_enemigo = 0 ataque_enemigo = 0 vida_picachu = 100 if pokemon_elegido == "SQUIRTLE": vida_enemigo = 90 ataque_enemigo = 8 nombre_pokemon = "SQUIRTLE" elif pokemon_elegido == "CHARMANDER": ...
#Crear un programa que le repita al usuario lo que dice pero con todas las vocales cambiadas por i. frase_user = input("Introduzca una frase: ") frase_modificada = [] vocales = ["a", "A", "e", "E", "o", "O", "u", "U"] for car in frase_user: if car in vocales: frase_user = frase_user.replace(car, "i") pri...
# -*- coding: utf-8 -*- """ Created on Fri Jun 11 23:48:35 2021 @author: Saptarshi Question - The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days. The span Si of the stock’s price on a given...
import tkinter as tk from tkinter import ttk mainwindow = tk.Tk() mainwindow.title("Combo box") label1 = ttk.Label(mainwindow, text="Label") label1.grid(column=0, row=0) name = tk.StringVar() # Tkinter isn't dynamically typed like Python proper fontsize = tk.StringVar() def pushbutton(): act.configure(text="...
import math def get_average(li): if not li: return float('NaN') sum = 0 for num in li: sum += num mean = sum / len(li) return mean def test_get_average(): assert math.isclose(get_average([1,2,3,4]), 2.5) def test_get_average_empty_list(): assert math.isnan(get_average(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: maxschallwig """ import requests url = "http://finance.yahoo.com/quote/AAPL?p=AAPL" response = requests.get(url) Indicators = ["Previous Close", "Open", "Bid", "Ask", "Day's Range", "52 Week Range"...
# -*- coding: utf-8 -*- """ hw2/fermat.py Created on Mon Sep 15 22:07:28 2014 @author: lauren """ #1 def check_fermat(a,b,c,n): if (c**n) == (a**n) + (b**n): print 'Holy Smokes, Fermat was wrong!' else: print 'No, that doesnt work' #2 def inputs(): a = raw_input('Value a?') b...
""" ArrayQueue.py Queue (FIFO) - Array Implementation - fized size Queue - keep a head and tail pointer and cycle both enqueue(key) | O(1) dequeue() | O(1) is_empty() | O(1) """ class ArrayQueue: def __init__(self, capacity): self.capacity = capacity + 1 self.head = 0 self.tail = 0 """ There is no conc...
# Python Program for n-th Fibonacci number number=int(input()) def fibonacci(n): if n < 0: print("Enter Positive number") if n == 1: return 0 elif n == 2: return 1 else: num1=0 num2=1 for i in range(1,number): next_number=num1+num2 ...
# Method1 - Class based """ In the below program, it is mandatory to implement the __enter__ and the __exit__ methods. After the __enter__ method ends, the code in the with block will be executed. Finally, the Context Manager will call the __exit__ method. """ class FileHandler(): def __init__(self, file_name, f...
palabra=[] let=0 print 'ingrese la palabra que desea analizar: ' palabra = raw_input() print (palabra) for bocal in palabra: if bocal=='a': let += 1 print("a-1") if bocal=='e': let += 1 print("e-1") if bocal=='i': let += 1 print("i-1") if bocal=='o': ...
# coding=utf-8 def euler_method(f, t0, x0, t1, h): """Explizites Euler-Verfahren. Einfachstes Verfahren zur numerischen Lösung eines Anfangswertproblems x' = f(t, x), x(t0) = x0 durch Berechnung von tk = t0 + k*h, k = 0, 1, 2, ... xk+1 = xk + h*f(tk, xk), k + 0, 1, 2, ... :par...
''' Instead of creating new objects setting the same attributes every time, Prototype method include prototyping the common objects into a cache and clones it to give a new instance. Later on the distinct attributes can be changed. ''' import copy class Player: name = None def set_name(self, name): self.name =...
num = input("Digite um número inteiro: ") numInt = int(num) result = (numInt // 10) % 10 print("O dígito das dezenas é",result)
def convert (full_name): printing_list=[] container_list= list(full_name.upper()) printing_list.append(container_list[0]) for i in range (0, len(container_list)): if (container_list[i]=="-"): printing_list.append(container_list[i+1]) else: continue print(''.jo...
import random from Pokemon_Proj.pokemon_battle_class import YourPokemon from Pokemon_Proj.pokemon_general_class import Pokemon player_info = {} player_location = [0, 0] Your_pokemon = [YourPokemon("Pikachu", 5, "thunder", "Female", 8000, 0, 2000), YourPokemon("Bulbasaur", 5, "grass", "Male", 6000, 0, 2...
math_txt=open('C:\Binus CS\math_expression.txt', 'r') infix=(math_txt.read()).split() print(infix) postfix=[] operator=[] def precedence(x): if x=="+" or x=="-" : return 1 elif x=="*" or x=="/": return 2 elif x=="(": return 0 def type(i): if i=="+" or i=="-" or i=="*" or i=="/"...
import unittest from moving_average import MovingAverage class TestMovingAverage(unittest.TestCase): def setUp(self): self.moving_average = MovingAverage() def test_compute_moving_average_example_1(self): result = self.moving_average.compute(3, [0, 1, 2, 3]) output = [0, 0.5, 1, 2] ...
#Знайти максимальний елемент серед мінімальних елементів стовпців матриці. import random m = int(input("Input M:")) n = int(input("Input N:")) numbers = [[0] * n for i in range(m)] for i in range(m): for j in range(n): numbers[i][j] = random.randint(1,30) for i in range(m): for j in range(n): ...
#У списку випадкових цілих чисел поміняти місцями мінімальний і максимальний елементи. import random n = int(input("Input N ")) numbers = [] print("Our list: ") for i in range(n): numbers.append(random.randint(1,10)) print("%2d " %numbers[i], end ="") print() print("Our new list: ") id_min_elem = numbers.index...
""" h=int(input('身長(cm)は?>>')) / 100 w=float(input('体重(kg)は?>>')) bmi = w / h /h print(f'BMIは{bmi:.1f}です') """ h,w =int(input('身長(cm)は?>>')) / 100,\ float(input('体重(kg)は?>>')) print(f'BMIは{w/h**2:.1f}です')
ages=[28,50,'ひみつ',20,78,25,22,10,'無回答',33] samples=list() for data in ages: if not isinstance(data,int): #数値でないデータはスキップ continue if data < 20 or data >= 30: continue samples.append(data) print(samples)
height=input('身長(cm)を入力してください>') weight=input('体重(kg)を入力してください>') height=float(height)/100 weight=float(weight) bmi=weight/height**2 print('BMI:',bmi) if bmi>=25: result='肥満' elif bmi>=18.5: result='標準体重' else: result='痩せ型' print(result)
import random input('Enterで対決開始') while True: mydice=[] pcdice=[] mresult=0 presult=0 for i in range(3): mydice[i]=random.randint(1,6) pcdice[i]=random.randint(1.6) mresult += mydice[i] presult += pcdice[i] print('あなたの出目') print(mydice) print('コンピューターの出目'...
#def eat(breakfast,lunch='ラーメン',dinner='カレー'): def eat(breakfast,lunch,dinner='カレー',desserts=()): print('朝は{}を食べました'.format(breakfast)) print('昼は{}を食べました'.format(lunch)) print('夜は{}を食べました'.format(dinner)) for d in desserts: print('おやつに{}を食べました'.format(d)) """ eat(breakfast='納豆ごはん',dinner='カレーうどん...
name=input('あなたの名前を教えてください>>') print('{}さん、こんにちは'.format(name)) food=input('{}さんの好きな食べ物を教えてください>>'.format(name)) if food == 'カレー': print('素敵です。カレーは最高ですよね!!') else: print('私も{}が好きですよ'.format(food))
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """Bullet类用来管理飞船发射的子弹""" def __init__(self,ai_setting,screen,ship): """子弹对象,位置和飞船一致""" #super(Bullet,self).__init__() super().__init__() #初始化父类 self.screen=screen #在(0,0)处创建一个表示子弹的矩形,再设置正确的位置 self.rect=pygame.Rect(0,0,ai_setting.bullet...
grade={} homepage=input('欢迎光临学生成绩信息管理系统!按任意键继续\n') while homepage: menu=('1.录入','2.查询','3.修改','4.删除','5.总览','6.退出') for feature in menu: print(feature) number=('1','2','3','4','5','6') order=input('请输入您想要操作的序号:') if order in number: num=int(order) while num==1: na...
import os import sqlite3 class Database: def __init__(self, dat_file): self.file_path = dat_file self.connection, self.cursor = None, None self.db_connect() # MANAGE CONNECTION def db_connect(self): self.connection = sqlite3.connect(self.file_path) self.cursor = se...
# Random Functions l1 = [1,2,3,4,5,6] import random as rd a =rd.choice([1,2,3,4,5,6]) a # Generate random flot number between 0<=random<1 b=rd.random() b # genearte radon interger for given range (doesnt work for float values) #it include last item and no step but in randrange not include last item and have step....
lst = ['football', 'handball', 'basketball', 1, 0.3 ] print(lst[0],type(lst[0])) print(lst[-1],type(lst[-1])) print(lst[-2],type(lst[-2]))
#Bruce Keller Task 2 -- Draft Project in a .py file #9/26/21 import requests def weather_data(query): api_key = "869668849cd4ddcff800a4cf956b06e3" base_url = "http://api.openweathermap.org/data/2.5/weather?" complete_url = base_url + "appid=" + api_key + "&" + query res=requests.get(complete_url)...
height = int(input()) perDay = int(input()) perNight = int(input()) print((height - perNight - 1) // (perDay - perNight) + 1)
hours1 = int(input()) minutes1 = int(input()) seconds1 = int(input()) hours2 = int(input()) minutes2 = int(input()) seconds2 = int(input()) print((hours2 - hours1) * 3600 + (minutes2 - minutes1) * 60 + seconds2 - seconds1)
# https://leetcode-cn.com/leetbook/read/linked-list/jy291/ # 时间复杂度: # addAtHead,addAtTail:O(1) # get,addAtIndex,delete:O(min(k,n−k)),其中k指的是元素的索引 # 空间复杂度:所有的操作都是O(1) class ListNode: def __init__(self, val): self.val = val self.next= None self.pre = None class DoubleLinkList: ...
# 快速排序:取一个元素,使元素p归位,列表被p分成两部分,左边都比p小,右边都比p大,递归完成排序 # 时间复杂度 nlogn 每一层复杂度是n # 缺点:1.递归最大深度 2.最坏情况 倒序排列,每次都是少一个数字 时间复杂度高 (加入随机化) import random # 框架 # def quick_sort(data, left, right): # if left < right: # mid = partition(data, left, right) # quick_sort(data, mid+1, right) # quick_sort(data, lef...
from datetime import datetime def linearSearch(list, target): #returns the index position of the number we are searching #if not found returns None for i in range(0, len(list)): if list[i] == target: return i return None def verify(list, target_num): ...
num = input() if (int(num[0]) + int(num[2])) / 2 == int(num[1]): print('Вы ввели красивое число') else: print('Жаль, вы ввели обычное число')
stone_bunch1 = int(input()) stone_bunch2 = int(input()) stone_bunch3 = int(input()) while stone_bunch3 != 0 or stone_bunch2 != 0 or stone_bunch1 != 0: bunch = int(input()) stone = int(input()) if bunch == 1: stone_bunch1 -= stone print(stone_bunch1, stone_bunch2, stone_bunch3) e...
degree = int(input()) count = 0 if degree == 1: print('Степень 0') elif degree <= 0 or degree % 2 > 0: print('НЕТ') else: while degree % 2 == 0: count += 1 degree //= 2 if degree == 1: print('Степень', count) elif degree % 2 != 0: print('Н...
from random import randrange print('Введите количество камней в куче № 1:') bunch1 = int(input()) print('Введите количество камней в куче № 2:') bunch2 = int(input()) sign = 0 if bunch1 > 2: x = bunch1 - 2 bunch_number = 1 bunch1 -= x elif bunch2 == 1 and bunch1 == 1: x = 1 bunch_number ...
total_price = 0 number_of_items = int(input("Number of Items: ")) while number_of_items < 0: number_of_items = int(input("Invalid number of items!\nNumber of Items: ")) for i in range(1, number_of_items + 1): price = float(input(f"Price of Item {i}: ")) total_price += price if total_price > 100: total...
fo = open("data.txt",'w+') print ("Name of the file: ", fo.name) # Assuming that the file contains these lines # TechBeamers # Hello Viewers!! seq="TechBeamers\nHello Viewers!!" fo.writelines(seq ) fo.seek(0,0) for line in fo: print("brrr") print (line) fo.close()
f = open("Class Illustrations/demo.txt","a") # note I use linux, so I need to use a forward slash, for windows its backlash # case 1 f.write("yooo") f = open("Class Illustrations/demo.txt","r") # note I use linux, so I need to use a forward slash, for windows its backlash n = f.readlines() print(n) for i in n: pri...
# count the number of vovels in the text file f =open("Lab programs/prog13/progText.txt","r") s = f.read() def countVovels(s): s= s.lower() count =0 for ch in s: if (ch=="a" or ch=="e"or ch=="i" or ch=="o" or ch=="u"): count+=1 return count print("number of vovels= ", countVovel...
def arithmetic(a,b): sum= a+b product= a*b difference= a-b quotient= a/b remainder= a%b return sum, product, difference, quotient, remainder a= int(input("Enter number 1:")) b= int(input("Enter number 2:")) sum,product,difference,quotient,remainder=arithmetic(a,b) print("Sum:",sum...
def print_numbers(lower_limit,upper_limit): print("Even numbers:") for x in range(lower_limit,upper_limit): if x%2 == 0: print(x) print("Odd numbers:") for x in range(lower_limit,upper_limit): if x%2 != 0: print(x) upper_limit=int(input("E...