text
stringlengths
37
1.41M
# ДЗ к Уроку №6 Гладышев ВВ """ Задание №1 Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. Урок 3 Задание №7 В одномерном массиве целых чисел определит...
# 할인된 상품 가격 출력 def product(): product = { '쌀': 9900, '상추': 1900, '고추': 2900, '마늘': 8900, '통닭': 5600, '햄': 6900, '치즈': 3900 } return product def computeDiscount(dp): p = product() for k, v in p.items(): # price = v - (v * dp / 100) price = v * (1 - (dp / 100)) ...
# 컴프리헨션(comprehension) # 반복문 축약 # 파이썬에서는 4가지 축약을 지원 # list(py2) set, dict, generator(py3) # 다양한 데이터 객체에 사용하는 복잡한 구문을 단순하게 작성할 수 있도록 지원하는 기능 # 1~10까지 정수를 리스트에 저장 numlist = [] for i in range(1, 10 + 1): numlist.append(i) print(numlist) # for 축약문 # [ 표현식 for 항목 in 반복가능객체 ] numlist2 = [ i for i in range(1, 10 + 1) ]...
fname=input('Enter the file name:') try: fh=open(fname) except: print('File not found:',fname) quit() res=[] for line in fh: line=line.rstrip() stuff=line.split() for word in stuff: if word in res: continue res.append(word) print(res)
class Solution: def isMatch(self, s: str, p: str): if s=='' and p=='': return True s = list(s)+['\0'] p = list(p)+['\0'] #需要最后一个值表示结尾。 self.log = {} #回溯法,会产生很多次的重复调用。对于子问题重复计算。 self.log[(len(s)-1,len(p)-1)] = True return self.helper(s,p,0,0) d...
# -*- coding: utf-8 -*- """ BUSCAMINAS Con espacio marca/desmarca la mina Con las flechas se mueve Con ENTER destapa Con ESCAPE se sale del juego Instale la librería curses en WINDOWS con: python -m pip install windows-curses """ import random import curses import numpy as np...
def fun1(val1, val2, val3, calc_suma=True): if calc_suma: # Calcule la suma return val1 + val2 + val3 else: # Calcule mejor el promedio return (val1 + val2 + val3)/3 def fun2(val1=0, val2=0): return val1 - val2 print(fun1(1, 2, 3)) print(fun1(1, 2, 3, False)) print(fun1(1, 2,...
d = {'xxx': 123, 'yyy': 456, 'zzz': 789} for k in d: print(k) for k in d: print(d[k]) for k, v in d.items(): print(k, v)
def es_primo(num): '''Detemina si un número es primo o identifica los primos de una lista/tupla es_primo(num) Parametro de entrada: num: número entero, tupla o lista Retorna: Si num es un entero, retorna True o False dependiendo si num es primo Si num es una lista o tupl...
# enumerate retorna el índice y el valor for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v) # zip() acopla dos secuencias al mismo tiempo questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for q, a in zip(questions, answers): print('What is your {0}? It is {1...
c = ord('A') while True: ch = chr(c) print(ch, end=' ') if ch == 'Z': break c += 1 print()
from typing import List, Dict, Tuple, Optional, Union # names es una lista de cadenas def print_names(names: List[str]) -> None: for student in names: print(student) # grades es un diccionario con keys=cadenas y values=flotantes def print_name_and_grade(grades: Dict[str, float]) -> None: for student, ...
for n in range(2,10): if n%2 == 0: print(n, "es un número par") continue print(n, "es un número impar")
import pandas as pd from pathlib import Path from datetime import datetime class HistoricalDataSaver: """Saves Historical Candlestick data to a .csv file. Can also load up the data. """ def __init__(self, storage_location): """Initialize the HistoricalDataSaver with a storage_location, and ...
import json input = ''' [ {"name":"sahil" ,"ID":"001"}, {"name":"aditya" ,"ID":"002"} ]''' info = json.loads(input) print("user count:",len(info)) for item in info: print("Name:",item['name']) print("ID",item['ID'])
#!/usr/bin/python3 # familycsv2json.py: convert a family tree CSV file from # http://mcdemarco.net/tools/family-tree-generator/lineage.html to a # JSON file, stripping out some of the less-useful data. # Original data: pid, name, gender, generation, byear, dyear, dage, # myear, mage, ptype, clan, spouseId, parentId1,...
a=int(input()) stringNum= str(a) first= stringNum[0] last=stringNum[len(stringNum)-1] middle= stringNum[1:len(stringNum)-1][::-1] result=int(first+middle+last) print(result)
# -*- coding: utf-8 -*- def make_counter(): count = 0 def counter(): nonlocal count # use python 3 count = 1 print(count) return count print(count) return counter var = 0 def func(num): print(num) func.var = var # func.var is referring the local ...
# -*- coding: utf-8 -*- # !/usr/bin/python def g(): x = yield 'hello' print('x = %s' % x) y = 5 + (yield x + 5) print('y = %s' % y)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- from typing import Generic, TypeVar, List T = TypeVar("T") class Queue(Generic[T]): def __init__(self, capacity: int): self.capacity = capacity self.size = 0 self._data = [] def add(self, val: T): if self.size >= self.capacity: ...
def test_print(): i = (1) print(type(i)) if "int" in str(type(i)): print("====one====") print(i) print("====one====") else: print("====two====") for j in i: print(j) print("====two====")
# Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário. class AreaQuadrado: def __init__(self): self.valorLado = int(input('Digite o valor do lado do quadrado')) def CalcularArea(self): self.area = self.valorLado ** 2 ...
import turtle theBoardList = [] squaresize = 50 whichturn = 1 redCounterx = [0, 0, 0, 0, 0, 0] blackCounterx = [0, 0, 0, 0, 0, 0] winner = False userXpos = 0 BORDER = 10 WINDOWWIDTH = 6*squaresize+BORDER WINDOWHEIGHT = 7*squaresize+BORDER BROSEF = turtle.Turtle() # defines a list of lists 6x7 to create the game board...
from blackjack.game import Game def run(): # start first game print("Welcome to Black Jack!") # prompt user for name and chips name = input("Enter your name: ") while True: chip_total = input("Enter how many chips you have [Enter an integer]: ") if chip_total.isdigit(): ...
#!/usr/bin/env python age = raw_input("How old are you?") height = raw_input("How tall are you?") power = raw_input("What is your power level?") print "So you are %r and %r tall.\n" %(age, height) print "And your power level is %r!!!" %(power)
#!/usr/bin python the_count =[1,2,3,4,5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number #same as above for fruit in fruits: print "fruits: %s" % ...
__author__ = 'danieloram' #create a list with string representations for each element's index position seq = [str(x) for x in range(10)] #=>['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] #create a list of squares seq2 = [x*x for x in range(10)] #=>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] #delete elements of a list ...
import time from tkinter import ttk, constants, StringVar class TimerFrame: """A timer frame, to be used as a component in exercise views. Contains necessary information for keeping track of time used and time left. Shows them to the user. """ def __init__(self, root, use_timer, time_limit): ...
import unittest from entities.operations import AdditionOperation, SubstractionOperation, \ MultiplicationOperation, DivisionOperation class TestAdditionOperation(unittest.TestCase): def setUp(self): self._default_addition = AdditionOperation(1, 2) def test_addition_result_correct(self): ...
import functools from tkinter import StringVar, ttk, constants from entities.settings import Settings class KeypadFrame: """A keypad frame used for inputting answers without a keyboard. By default the keypad starts out hidden. Users can show it by clicking a button. Attributes: keypad_hidden: An...
##### Filename: util.py ##### Author: Yankang Yang ##### Date: 9/6/2017 ##### Email: yankangyang@college.harvard.edu import copy from collections import deque ## Problem 1 def matrix_multiply(x, y): ## initialize list of lists calculated = [[ 0 for b in range(len(y[0]))] for a in range(len(x)) ] ## loop ...
"""Methods for displaying common data. Uses matplotlib library. Data is mostly numpy arrays or of pandas types. """ import math from itertools import cycle import matplotlib.mlab as mlab import matplotlib.pyplot as plt def _scatter_cv( ax, data_frame, group_by_column, plot_columns, transformation=Non...
''' 访问一个网址 更改自己的UA 进行伪装 ''' from urllib import request, error if __name__ == '__main__': url = "http://www.baidu.com" try: # 使用head方法进行伪装UA # headers = {} # headers['UserAgent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 S...
# Martyna Piasecka 224398 # Hubert Gawłowski 224298 # 3.1 Approximation def approximation(n): product = 1.0 for i in range(1, n): numerator = (2 * i) * (2 * i) denominator = (2 * i - 1) * (2 * i + 1) product *= numerator / denominator # print(product * 2) print("Przybl...
import random import time def merge_sort(int_array): """ Sorts numbers using a merge sort algorithm :param int_array: integer array :return: numbers sorted in decreasing order """ merge_sort_helper(int_array) return int_array def merge_sort_helper(array): # if greater than 1, split ...
class heap: def __init__(self, A): self.heapsize = len(A) self.A = A for i in xrange((self.heapsize/2),-1,-1): self.Heapify(i) def Parent(self,i): return (i+1)/2-1 def Left(self,i): return 2*i+1 def Right(self,i): return 2*i+2 def Heap...
""" Name: Riley Fagan Date started: 04/09/2020 GitHub URL: https://github.com/RileyFagan/assignment_1 """ import csv MENU = """Menu: L - List Places A - Add new place M - Mark a place as visited Q - Quit""" file_list = [] with open("places.csv", "r") as places_file: places_data = csv.reader(places_file) for ...
""" palindromer tests """ import unittest from palindromer import load_words_from_url, find_palindromes, is_palingram, find_palingrams class TestPoorMansBarChart(unittest.TestCase): def test_load_words_from_url_when_url_is_None_raises_ValueError(self): # Arrange, Act, Assert with self.assertR...
# -*- coding: utf-8 -*- import sys f = open(sys.argv[-1]) lines = f.read().split('\n') f.close() lines = filter(lambda str: str != '', lines) words = set() for line in lines: cols = line.split('\t') words.add(cols[0]) for elem in words: print(elem)
# Python script to rename files, find-and-replace style from datetime import datetime import glob, os, re, sys def renameFiles(find_pattern, replace_pattern, commit=False): print " Replacing substring " + find_pattern + " in file names with pattern " + replace_pattern if not commit: print " Printing file names ...
from abc import ABC, abstractmethod from collections import namedtuple Customer = namedtuple('Customer', 'name fidelity') joe = Customer('Jone Doe', 0) ann = Customer('Ann Smith', 1100) class LineItem: def __init__(self, product, quantity, price): self.product = product self.quantity = quantity ...
''' 일급객체의 정의 1) 런타임에 생성이 가능하다 2) 데어터 구조체의 변수나 요소에 할당할 수 있다(일급객체를 하나의 묶음으로 다룰 수 있다) 3) 함수 인수로 전달할 수 있다 4) 함수 결과로 반환할 수 있다 파이썬에서 function은 일급객체(first-class object) ''' def factorial(n): '''return n!''' return 1 if n < 2 else n * factorial(n-1) print(factorial(42)) print(factorial.__doc__) print(type(factorial)...
# this is a wheather app that uses api to get information and uses a tkinter app to display it import requests from tkinter import * import threading from tkinter import font import random import time class weather_app(): def __init__(self): self.win = Tk() self.win.title("Weather It") self.win.geometry("1300...
print('1*2*3*4*5... 합계') i=1 s=1 while i<5: i=i+1 s=s*i print(s)
print('자릿수를 출력하는 프로그램') a = int(input('양의 정수를 입력해 주세요 >>> ')) if a > 0: print('{} > {} 자리수 '.format(a,len(str(a)))) else: print('양의 정수가 아닙니다.')
print('1부터 100까지 소수') n=100 def isPrime(a): if a < 2: return False for i in range(2,a): if a % i == 0: return False return True for i in range(n+1): if isPrime(i): print(i, end=',') print()
print('''배수 판별하면 배수 구하기. 배수 = 그 수를 나눠 떨어지는 수 15는 3의 배수 = 15/3 = 5로 나눠떨어짐 3의 배수 2의 배수 => 15 % 2 = 0 3의 배수 => 15 % 3 = 0 4의 배수 => 15 % 4 = 3 5의 배수 => 15 % 5 = 0 < 1부터 20까지의 수 중에서 5의 배수 구하기 > ''') cnt=0 sum=0 for i in range(1,11): if i % 5 == 0: cnt = cnt + 1 sum = sum + i print('{}\t{}\t{}'.format(i,cnt,sum)) pri...
print('시저 암호 풀기') # word = input('word >> ') # num = input('num >> ') word, n = 'CAT', 5 AZ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for char in word: print(AZ[(AZ.find(char)+n)%26], end=' ') print() print(''.join([AZ[(AZ.find(char)+n)%26] for char in word])) print(len(AZ)) print(AZ.find('Z')) print((AZ.find('Z')+5)%26) pri...
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",") print(names) print() kcnt, lcnt, lee = 0, 0, 0 new_names = [] for name in names: if name[0] == '김': kcnt += 1 if name[0] == '이': lcnt += 1 if name == '이재영': lee += 1 if name not in new_names: new_names.append(name) p...
print(''' 2에서 100까지 정수 중 소수 15개 구하기 < 에라토스테네스의 체 > - 2부터 100까지의 수를 나열 한다. - 자기 자신을 제외한 2의 배수를 모두 지운다 - 남아있는 수 가운데 3은 소수이미로 오른쪽에 3을 쓴다 - 자기 자신을 제외한 3의 배수를 모두 지운다 - 위의 과정을 반복하면 구하는 구간의 모든 소수가 남는다. ''') n = 100 a = [False, False] + [True]*(n-1) primes=[] for i in range(2,n+1): if a[i]: primes.append(i) for j in ran...
print('''파일찾기 A라는 디렉토리 하위에 있는 텍스트 파일 (*.txt)중에서 LIFE IS TOO SHORT라는 문자열을 포함하고 있는 파일들을 모두 찾을 수 있는 프로그램 작성 단, 하위 디렉토리도 포함해서 검색해야 한다. ''') import os A = './data' for root, dirs, files in os.walk(A): for file in files: file_name = root + '/' + file with open(file_name, 'r', encoding ='UTF-8') as fp: if fp.read().f...
data = [[0,1],[1,1],[2,1],[1,10],[10,10],[11,10]] def page(m,n): page = m//n if m%n>0: page += 1 return page for row in range(len(data)): for col in range(1): print(data[row][col],data[row][col+1],page(data[row][col],data[row][col+1]))
print('''Multiples of 3 and 5 3과 5의 배수의 총합 구하기 3,5,6,9 = 23 ''') lst = [] # 메모리 사용량 증가 for i in range(1,10): # 0~9까지 숫자 if (i % 3 == 0) or (i % 5 == 0): # 3과 5의 배수 lst.append(i) print(sum(lst)) # 23 sum1=0 for i in range(1,10): if i%3==0 or i%5==0: sum1 = sum1 + i print(sum1) print(list([x for x in rang...
print('1+2+4+7+11+16 합계') print('a:증가치, i: 각 항, s:합계') a=0 i=1 s=1 while a<5: a=a+1 i=i+a s=s+i print(s) i=1 s=0 for a in range(6): i=i+a s=s+i print(s)
from dataclasses import field from typing import List from . import CardHand, CardPlayer class CardDealer(CardPlayer): """ Deals cards from a special device called a "dealer's shoe". """ HandType = CardHand def __post_init__(self): """ Initialize the `CardDealer` with an empty `...
def solution(): cur_max = int(input()) cur_count = 1 if cur_max == 0: return 0 should_continue = True while should_continue: pending_num = int(input()) if pending_num == 0: should_continue = False elif pending_num > cur_max: cur_max = pending_n...
# TODO: Можно решить с двумя левыми поисками, один больше-вавно, и другой строго больше # 1. Для начала определяем функции бинарного поиска сдева и справа: # (все в соответствии с тем подходом, который был изложен в лекции) def l_bin_search(left, right, check, check_params): while left < right: m = (l...
##Q5. Write a program to convert a temperature given in Fahrenheit to centigrade and vice versa ############################################################################################################# ##Program Objective: to convert a temperature given in Fahrenheit to centigrade and vice versa #...
##Bitwise Operator ## ##&, |, ~, ^,>>, << ## ##Write program(s) to demonstrate the use of all bitwise operators. ############################################################################## a=0B1001 b=0B1000 print(bin(a & b)) print(bin(a | b)) print(bin(a ^ b)) print(bin(~a)) print(bin(~b)) print(bin...
def square(n): ''' A function to return the square of a number. ''' return n**2 def cube(n): ''' A function to return the cube of a number. Usage: cube() ''' return n**3 def power(a,n): ''' A function to calculate power of n to a ''' return a**...
##Q2. Write a program to swap two no. ########################################################################## ##Program Objective: to swap two no. ## ##Coded by: KNR ## ##Date: 17/09/2019 22:20 ...
##Membership Operator ## ##In, not in ## ##Write program(s) to demonstrate the use of all membership operators. ############################################################################## a=[1, "Kris", 3.333333, 90, 'A', True, False, 'XYZ', 34, 28] print(1 in a) print("K" in a) print(90 not in a) print('...
""" Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first subs...
from util import * class EmptySquare(object): def __init__(self, board): self.color = None def __repr__(self): return '-' class ChessPiece(object): def move(self, board, start, placement): if self.check_legal_move(board, start, placement): set_square_to_zero(board, start) board[place...
from math import * def f(x): return cos(x)*x - 2 def LeftPr(a,b,n): h = (b - a) / n Integ = 0 x = a for i in range(n-1): Integ = Integ + f(x) x = x + h Integ = Integ * h return Integ def precision(Integ): n = 1 while abs(LeftPr(a,b,n) - LeftPr(a,b,n * 2)) > eps: ...
# https://www.codingame.com/ide/puzzle/winamax-battle class Game(): KARTS = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} _player1deck = [] _player2deck = [] _player1table = [] _player2table = [] _winner = "PAT" _r...
# from here http://codegists.com/snippet/python/teads-sponsored-contestpy_workofartiz_python from collections import defaultdict edges = defaultdict(list) for i in range(int(input())): xi, yi = [int(j) for j in input().split()] edges[xi].append(yi) edges[yi].append(xi) # calculates the maximum depth (no...
# based on https://github.com/aethersg/codingame-puzzle/blob/master/Python/hard/Genome%20Sequencing.py import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. def nested(strings): res = strings.pop() while len(strings) > 0: ...
# https://www.codingame.com/ide/puzzle/power-of-thor-episode-1 light_x, light_y, initial_tx, initial_ty = [int(i) for i in raw_input().split()] current_x, current_y = initial_tx, initial_ty while True: remaining_turns = int(raw_input()) # The remaining amount of turns Thor can move. Do not remove this line. mo...
# https://www.codingame.com/ide/puzzle/temperatures n = int(input()) # the number of temperatures to analyse temps = input() # the n temperatures expressed as integers ranging from -273 to 5526 if n !=0: array = temps.split(' ') min = int(array[0]) for i in range(1, n): if (abs(min)>abs(int(array[...
#########################################33 # Actors are binary strings # an actor is mutated by flipping a single bit # upon replication, an action of length n produces n children, # one for each possible mutation # # This simulation demonstrates of no evolution occurs in # the absense of of selection pressures. T...
print("test") def addition (a, b): return a+b c = addition(5,1) if (c>7): print( str(c) + " is greater than 7") elif (c < 7): print(str(c) + " is lower than 7") else: print(str(c) + " is equal 7") list1 = [1,3,5,7,9] print (list1.__getitem__(0)) list1.append(11) print(list1) for i in list1: pri...
import re from dataclasses import dataclass from pathlib import Path from typing import Set, Tuple, List, Iterator INPUT_FILE_NAME = "/Users/nesseri/github/advent_of_code/2020/data/02_passwords.txt" INPUT_REGEX = r"([0-9]+)-([0-9]+) (\w): (\w+)" @dataclass class Password: min_count: int max_count: int le...
def subArraySum(arr, n, tot): #Your code here low = 1 high = 2 total = arr[0]+arr[1] while(low<high and (low < n or high<=n)): if total == tot: return low,high elif total>tot: total = total - arr[low-1] low = low + 1 ...
# https://leetcode.com/problems/partition-equal-subset-sum/submissions/ def canPartition(self, nums: List[int]) -> bool: tot = sum(nums) if tot%2 == 1: return False tot = tot//2 def knapsack(nums,tot,i): if tot == 0: ...
#Matching and extraction the data #re.search() returns a false/tru statement depending on the string matches #for extraction we use re.findall() #Here output is python list import re x = 'My fav sport number is 10, My last ph number is 49' y = re.findall('[0-9]+',x) z = re.findall('[0-9]',x) print y print z a = re.find...
var1 = raw_input("print first number") var2 = raw_input("print second number") print "If second number is large it will give the value true otherwise false \n", var1 < var2
#Given an integer, , perform the following conditional actions: #If is odd, print Weird #If is even and in the inclusive range of to , print Not Weird #If is even and in the inclusive range of to , print Weird #If is even and greater than , print Not Weird n = int(input()) if n%2 == 1: print ("Weird") elif n%2 ...
## set command I dont know fname = raw_input("Enter file name: ") if len(fname) == 0: fh = open('romeo.txt') lst = list() for line in fh: for i in line.split(): lst.append(i) lst.sort() print list(set(lst))
n = int(input()) marksheet = [[input(), float(input())] for _ in range(n)] print (marksheet) 3 1 2 3 4 5 6 [['1', 2.0], ['3', 4.0], ['5', 6.0]] marksheet = [] for _ in range(0,int(input())): marksheet.append([input(), float(input())]) marksheet 2 1 2 3 4 [['1', 2.0], ['3', 4.0]] a = [['a', 1.0], ['b', 2.0],['c...
def valid_ip(address): try: host_bytes = address.split('.') valid = [int(b) for b in host_bytes] valid = [b for b in valid if b >= 0 and b<=255] return len(host_bytes) == 4 and len(valid) == 4 except: return False print valid_ip('266.10.20.30') --------------- def ipche...
def count(string, letter): print("The letter \""+letter+"\" appears",(string.lower()).count(letter),"times in the string: \""+string+"\"") count("This is a test", "s")
mylist = [1, 2, 3, 4, 5, 6] myotherlist = [[1,2,3],'b'] for element in myotherlist: mylist.append(element) print mylist
def count(string, letter): x = 0 for i in string: if i == letter: x += 1 print "The letter "+letter+" appears " +str(x)+" times in the string: "+string count("This is a test","s") #def count(string, letter): # x = 0 # for i in letter: # x += 1 # print "The lett...
people = 20 cats = 30 dogs = 15 if people < cats: print "cats are higher than people" if people > cats: print "people are higher than cats" if people < dogs: print "people are higher than dogs" if people > dogs: print "people are more than dogs" dogs += 5 if people >= dogs: print "people are greater or equal ...
#!/usr/bin/python """This is a simple calculator program """ def addition( val1 , val2 ): """This function adds two numbers and returns result""" return val1 + val2 def subtraction( val1, val2 ): """This function subtracts two numbers and returns result""" return val1 – val2 def multiply(val1 , val2...
y = int(input("Enter a Number :")) x = y // 2 # y > 1 while x > 1: if y % x == 0: # Remainder print(y, 'has factor', x) break # Skip else x -= 1 else: # Normal exit print(y, 'is prime')
#list append stuff = list() stuff.append('book') stuff.append('Hi') stuff.append(99) print stuff some=99 in stuff print some some='ss' in stuff print some some='ss' not in stuff print some
tall = int(input("what is you'r height")) print "heihgt is %r" %tall print "heihgt is %s" %tall love = raw_input("do you love S Number expecte") print "you said %s Subhanallah" % love
fruit = 'banana Mango' if 'a' in fruit: print "found it" #Capitalise Important because of searching we can change #everything to lower and do; easy for searching print fruit.lower() print fruit.upper() print type(fruit) ####Finding the postion position = fruit.find('na') print 'the postion of na is ', position print...
movies = list() movie1 = dict() movie1['Director'] = 'James Cameroon' movie1['Title'] = 'Avatar' movie1['Relasing date'] = '18 Deember 2009' movie1['Running Time'] = '144 minutes' movie1['Rating'] = 'PG-13' movies.append(movie1) movie2 = dict() movie2['Director'] = 'David Fincher' movie2['Title'] = 'The Social Newtwork...
while 1==1: print("enter your choice") door = int(input("1 to enter door1 or 2 to enter door2")) if( door == 1): print("Tell me whether you want to kill bear or beg life") dare = int(input("3 to kill bear or 4 to beg life")) if(dare == 3): print("you are brave person!!") co...
values = [] #fname = raw_input("Enter file name: ") fname = "mbox-short.txt" with open(fname, 'r') as fh: for line in fh.read().split('\n'): #creating a list of lines if line.startswith('X-DSPAM-Confidence:'): values.append(line.replace('X-DSPAM-Confidence: ', '')) # I don't know whats after the...
# Selection sort functions def comparison(val1, val2, reverse): return val1 > val2 if reverse else val1 < val2 def find_target_idx(in_list, start, stop, reverse): target_idx = start for idx in range(start + 1, stop): if comparison(in_list[idx], in_list[target_idx], reverse): t...
class Acervo: def __init__(self, titulo, autor, editora, ano_de_publicacao, ano_de_aquisicao, lido, data ): self.titulo = titulo self.autor = autor self.editora = editora self.ano_de_publicacao = ano_de_publicacao self.ano_de_aquisicao = ano_de_aquisicao se...
# 594.py -- Longest Harmonious Subsequence ''' We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences. A subsequence of array i...
# 4.py -- Median of Two sorted array ''' Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. Follow up: The overall run time complexity should be O(log (m+n)). ''' def find(A, B): n, m = len(A), len(B) if m > n: A, B, m, n = B, A, n, m ...
# 406.py -- Queue Reconstruction by Height ''' Description: Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Wri...
# 377.py -- Combination Sum V ''' Description: Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1...
# 518.py -- Coin Change 2 ''' Description: You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. Example 1: Input: amount = 5, coins = [1, 2, 5] O...