text
stringlengths
37
1.41M
if __name__ == '__main__': while True: entrada = input().split() n1 = int(entrada[0]) n2 = int(entrada[1]) if n1 == 0 and n2 == 0: break print(n1*n2)
entrada = int (input()); for x in range(0,entrada): numbers = input().split(" "); n = int((int(numbers[0]) * int(numbers[1]))/2) print(n,"cm2");
import numpy as np import matplotlib.pyplot as plt from json import loads from datetime import datetime, timedelta import dateutil.parser dev_id = "keypad" date = "13.11.2018" gateway = "trt-olav-loragw01" somedate = datetime Datarates = ["SF12BW125", "SF11BW125", "SF10BW125","SF9BW125", "SF8BW125", "...
# Learn Python The Hard Way # Exercise 6 x = "There are %d types of people." %10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y # %r for debugging since it displays the raw, others are for display print "I said: %r." % x print "I also said: '%s'." % y ...
# Coursera: Introduction to Interactive Programming # Mini Project 5 # AY 20141025 # http://www.codeskulptor.org/#user38_ao5ySmgBgC_11.py import simplegui import random global turns turns = 0 # helper function to initialize globals def new_game(): global deck global exposed global state state = 0 ...
# Write a program that calculates the minimum fixed monthly payment needed # in order pay off a credit card balance within 12 months. balance = 3926 annualInterestRate = 0.2 monthly_payment = 0 step = 10 month = 1 current_balance = balance #x = balance, y = monthly payment, z = annualInterestRate def newmonth(x,y,z...
# Write a program to calculate the credit card balance after one year if a # person only pays the minimum monthly payment required by the credit card # company each month. balance = 4842 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 month = 1 total_paid = 0 while month <= 12: print 'Month: %r' % month ...
info = [ {"My name is": "Ryan"}, {"My age is": "33"}, {"My country of birth is": "The US"}, {"My favorite language is": "Python"} ] for i in range(0, len(info)): print info[i]
log_file = open("um-server-01.txt") # Opens the file named "um-server-01.txt" and assigns it to log_file def sales_reports(log_file): # Creates a function called sales_reports with a paramater of log_file for line in log_file: # A for loops that goes over the lines in log_file line = line.rstrip() # Makes...
#Reducer and computer for Realestate Data import sys totalcost = 0 #Counter for Total Cost totasqr = 0 #Counter for total square feet for line in sys.stdin: #reads through input file line by line data = line.strip().split("\t") #assigns line to list called data if len(data) = 2: #checks to make sure corre...
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. #init...
''' Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [3,3,5,5,6,7] Explanation: Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6...
''' word = 'abbcccb', k =3 means can delete consecutive char first : delete ccc, and then becomes 'abbb' Second : delete bbb, and then becomes "a" return a word = 'abbcccbddddb', k =4 delete dddd return "abbcccbb" ''' def compressWord(word, k): # Write your code here stack = [] for w in word: i...
""" curses test if window: pip install (--user) window-curses """ import curses def main(console): """ Fonction principal qui sera envoloppée" par "curses" et aura accès à la console en tant que "console" """ console.leaveok(True) console.clear() console.addstr(4, 10, "...
def render_list(self, block: str, block_type: str, y: int, ordered) -> int: """ Renders the items of a list (ordered and unordered). Replaces the supplied numbers / hyphen with the correctly ordered numbers / unicode character for display. :param self: MarkdownRenderer :param block: string of text ...
#-----------------------------------------------------------# # Tumblr Artwork Miner # # Author: Rocio Ng # # Purpose: Extracts information and urls # # for Original Artwork posted by # # artists obtained from Artist Miner # #-----------------------------------------------------...
#Comma seperated file, look at position 0 #Position 0 is either 1, 2, or 99 #Old computer understands parameter mode "0" #OPCODE SUPERLIST: #99 == program is finished and should stop #1 == add two numbers together and store the third #2 == same as 1 except multiply #3 == takes one number and saves it to the position gi...
#Comma seperated file, look at position 0 #Position 0 is either 1, 2, or 99 #Old computer understands parameter mode "0" #OPCODE SUPERLIST: #99 == program is finished and should stop #1 == add two numbers together and store the third #2 == same as 1 except multiply #3 == takes one number and saves it to the position gi...
''' elena corpus csci 160 tuesday 5 -7 pm entering a string and finding out if it is a palindrome and if it is even or odd user_str = input('Enter a String: ') length_user_str = len(user_str) while user_str != ' ' : reversed_str = '' length_user_str = len(user_str) for character in range(length_user_str ...
''' Initial while loop Counting from counter (1) to the target value (user input) ''' counter = 1 target = int ( input ("How high should the program count? ")) while counter <= target: #pretest loop #if counter % 100000 == 0: print (counter) counter = counter + 1 print ("The loop executed", target, "times...
def printPhoneBook (message, data): print(message) for contact in data: print(format(contact,"15s"), format(data[contact],">15s")) print() def printSortedPhoneBook(message, data): print(message) sortedNames = list(data.keys()) sortedNames.sort() for contact in data: print(fo...
''' Elena Corpus CSCI 160 Tuesday 5-7 pm writing a program that asks for the length of a line using astriks ''' #for loops line_length = int(input("Enter the length of line you wish to draw: ")) for line_length in range(1,line_length + 1): line_length = "*" print(line_length, end=' ') #while ...
TIME_FRAME = 15 for hour in range (9, 12 + 1): for minute in range (0, 60, TIME_FRAME): print (format (hour, "2d"), ":", format (minute, "02d"), sep='') for hour in range (1, 4): for minute in range (0, 60, TIME_FRAME): print (format (hour, "2d"), format (minute, "02d"), sep=":") hour = 4 minute ...
def sumavg(): values = [] def avg(value): values.append(value) return sum(values) // len(values) return avg if __name__ == '__main__': sa = sumavg() # 1 print(sa(1)) # 2 print(sa(3)) # 4 print(sa(10))
""" 生成器表达式和列表表达式的区别 列表表达式 : [expression] 生成器表达式 : (expression) """ generator = (i for i in range(0, 20)) # 延迟生成 print(next(generator)) print(next(generator)) print(next(generator))
from collections import deque """ deque : 一个线程安全的双向队列 maxlen : 队列最大长度,不可修改 """ dq = deque(range(0, 10), maxlen=10) print(dq.popleft()) print(dq.pop()) dq.append("123") dq.appendleft("abc")
import re from collections.abc import Iterable, Iterator RE = re.compile("\w+") class Sentence(Iterable): def __init__(self, words): self._words = words def __iter__(self) -> Iterator: # 懒正则解析 # 生成器表达式 return (item.group() for item in RE.finditer(self._words)) if __name__ ...
class MyNumList: def __init__(self, nums): assert isinstance(nums, list), "nums必须是一个数组" self.nums = nums # += def __iadd__(self, other): self.nums += other.nums return self def __imul__(self, other): min_len = min(len(self.nums), len(other.nums)) for i ...
"""This is the entry point of the program.""" def highest_number_cubed(limit): number = 0 while True: number += 1 if number ** 3 > limit: return number - 1
x = 20 y = 5 res = 0 res = x+y print(res) res +=x print(res) res *=x print(res) res /=x print(res) res = 5 res%= x print(res) res **=x print(res) res //=x print(res)
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.start = None def InsertLast(self,value): NewNode = Node(value) if self.start == None: self.start = NewNode else: t...
#binary tree class BinarySearchTreeNode: def __init__(self,data): self.data=data self.right=None self.left=None def add_child(self,data): if data ==self.data: return if data < self.data: #add data to left subtree: if self.lef...
from information_extraction import answer_question, process_data_from_input_file def question_answers(question): print '=================================' print 'Question: ' + question try: answer_question(question) except Exception as e: print 'Failed to answer this question.' pri...
import argparse import sys def main(): parser = argparse.ArgumentParser() parser.add_argument('--x', type=str, default = 'trundle', help="What is the troll?") args = parser.parse_args() sys.stdout.write(str(troll(args))) def troll(args): if args.x == 'trund...
import urllib import requests import bs4 import re import os #making a new dir os.makedirs('Wallhaven', exist_ok=True) print ('''\n\n Welcome to the Wallpaper Downloader With this Script you can download wallpapers from Wallhaven site''') #fetching latest wallpapers def latest(): print(''' Downloading ...
import tkinter as tk from tkinter import messagebox def komunikat(): zmienna=messagebox.askyesnocancel('Pytanie','czy chcesz wyjść?') print('koniec') if zmienna == True: Aplikacja.destroy () return def komunikat(): return Aplikacja = tk.Tk() Aplikacja.geometry ('400x40...
import math class Vector: def __init__(self, components): self.dim = len(components) self.components = components def dot_product(self, vector): if self.dim != vector.dim: raise ValueError("Dimension mismatch") product = 0 for i, component in enumerate(self...
class NeuralNetwork: """ Implementation of an Artificial Neural Network with back propogation. """ def __init__(self, learning_rate, layers): """ Initialize Neural Network parameters Args: learning_rate: Learning rate of the neural network """ self.learn...
# -*- coding: utf-8 -*- from body_data import Body_data class Molecule(Body_data): """stores the body_data associated with a specific molecule""" def __init__(self, data, molecule_id): """builds the molecule by creating a new body_data object with the atom_style from the passed in data. the ne...
# -*- coding: utf-8 -*- class Header_data(object): """stores, reads and writes data in header lines from LAMMPS data files.""" def __init__(self): """initializes the data stored in header lines and creates a dictionary relating the header keywords to the header data""" self.atom_num = ...
import random import time class Caculater: def __init__(self): self.operation_num = 3 self.min = -10 self.max = 10 self.max_num = 100 self.min_num = -100 self.operations = ['*', '/', '+', '-'] self.ans = [3, 4, 5, 6] self.opra_nums = [0]*4 def g...
""" ref: https://twitter.com/nikitonsky/status/1443959126338543616?s=08 """ import numpy as np from collections import defaultdict input = [ {"age": 18, "rate": 30}, {"age": 18, "rate": 15}, {"age": 50, "rate": 35} ] def calculate_avg_rate(input: list) -> dict: result = dict() collected_dict = def...
##Counts the number of inversions (reversals of position from sorted order) ##in the input file whilst sorting the array using mergesort. def merge_and_count_split_inv(b, c): sorted_list = [] count = 0 i = 0 j = 0 len_b = len(b) len_c = len(c) while i < len_b and j < len_c: if b[i]...
def split_join(): #Описание: данная программа принимает на ввод строку - на выходе заменяет пробелы #на нижние подчеркивания, при этом удаляет лишние пробелы, если их было несколько, #и вместо n-го количества пробелов заменяет на один знак '_' a = input('') print('_'.join(a.split())) split_join()
def bigger_price(limit,data): from operator import itemgetter max_price = sorted(data, key = itemgetter('price'),reverse=True) return(max_price[0:limit]) print(bigger_price(2,[{'name':'kakawka', 'price':30},{'name':'zalypa','price':10}, {'name':'sychara','price':20 }]))
class Restraunt(): def __init__(self, name, food, drink, starry_restraunt): self.name = name self.food = food self.drink = drink self.starry_restraunt = starry_restraunt def seats(self): self.seat = 100 print('Ресторан ' + self.name + ' имеет ' + str(self.seat)+' ...
def quicksort(x): if len(x) == 1 or len(x) == 0: return x else: pivot = x[0] i = 0 for j in range(len(x) - 1): if x[j + 1] < pivot: x[j + 1], x[i + 1] = x[i + 1], x[j + 1] i += 1 x[0], x[i] = x[i], x[0] a1 = q...
def matchSequence(a, b): if a == b: return True else: return False gapPenalty = int(input('Unesite koliko zelite da bodujete prazninu: ')) matchScore = int(input('Unesite koliko zelite da bodujete pogodak: ')) mismatchScore = int(input('Unesite koliko zelite da bodujete promasaj: ')) with open...
import sys class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit @classmethod def from_position(cls, position): """ Given a number from 1 to 52, creates the card in the correct position assuming the deck is sorted by alphabetical suits and t...
import sys #Find the perfect squares with a given number of digits def getQuirksomeSquares(): #Start by getting the perfect squares squares = {2:[], 4:[], 6:[], 8:[]} num = 0; square = num*num while square < 1e8: squares[8].append(square) if square < 1e6: squa...
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3,6 # 10: ...
def succ(Z): return Z+1 def pred(Z): if Z>=1: return Z-1 else: return 0 # macro resta acotada def resta(X,Y): Z=0; while Z!=Y: X=pred(X) Z=succ(Z) return X # Con la macro del producto, la resta y la asignacion """ He de contar hasta cuando puedo elevar 10 a u...
def succ(Z): return Z + 1 def pred(Z): if Z >= 1: return Z - 1 else: return 0 """ PW-E4-c): Construir un PW que compute f(X)=fact(X). Empleando macros: producto y asignacion """ # Pasar al f como argumento las k varibles (X1, X2, ...Xk) del programa while k variables construido def pw(X1,X...
print("Welcome to this Game!") print('''Rules : 1 You have 3 Attemepts 2 Guess the Correct number to win 3 You can take a hint''') secret = 9 guess_count = 0 guess_avaliable = 3 while guess_count < guess_avaliable: guess = int(input("Guess: ")) guess_count += 1 if guess == secret: ...
#!/usr/bin/env python # coding: utf-8 # ## Coverting kilometers to miles # In[12]: km = float(input("Enter value in kilometers: ")) miles = 0.621371*km print(km,"km is: ",miles,"Miles") # ## Converting Celsius to Fahrenheit # In[14]: Celsius= float(input("Enter value in celcius: ")) Fahrenheit = (Celsius * 9/5...
def longestPalindrome(self, s: str) -> str: n = len(s) if(n<2): return s left = 0 right = 0 palindrome = [[0]*n for _ in range(n)] for j in range(1, n): for i in range(0, i): innerIsPalindrome = palindrome[i+1][j-1] or j-i<=2 if (s[j] == s[i] and innerIs...
class Dog: def __init__(self, name, breed): self.name=name self.breed=breed print("dog initialized!") def bark(self): print("Woof!") def sit(self): print(self.name,"sits") def roll(self): print(self.name,"rolls over")
import random,urllib.request import sqlite3 conn=sqlite3.connect('mydb.db') def create_db(): ##create a new username and password c=conn.execute('select usid,pw from account') for row in c: row[0] row[1] a=input('\nenter current username: ') b=input('enter current password: ') if(a...
import sqlite3 conn=sqlite3.connect('sentence.db') ##tables sentence and neglect are created '''conn.execute('create table sentence(text not null);') conn.execute('create table neglect(text not null);')''' a=input('sentence: ') b=input('neglecting words: ') c=a.split(' ') d=b.split(' ') e=conn.execute('insert into se...
##importing the k-means clustering mmodel from sklearn.cluster import KMeans ##importing of the pandas library. import pandas ##importing matplotlib import matplotlib.pyplot as plt #read the data in the name of 'games' and store the values of 'added games.csv' in it games = pandas.read_csv('added_games.csv') ##prin...
##name = "Liza" ##num = 15 ##num_2 = 45.5 ## ##print(num, num_2, name) ##temp = str(float(int(input("Input value: ")))) # Ввожу переменную temp ##print(temp) # + # - # * # / # % # // # ** # == # != # > # < # >= # <= # or # and # True and False ##age = int(input()) ## ##if age > 1...
# 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: def trim(str): n = len(str) aa = 0 bb = n for i in range(n): if str[i] == ' ': aa += 1 else: break for j in range(1,n+1): if str[-j] == ' ': bb -= 1 else: break ...
import itertools def pi(N): # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ... odd = itertools.count(1,2) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. odd_n = itertools.takewhile(lambda x:x<=2*N-1,odd) # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... odd_n_n = map(lambda x:(-1)**(x//2)*4/x,odd_n) ...
# -*- coding: utf-8 -*- # # This file is part of Flask-Wiki # Copyright (C) 2023 RERO # # Flask-Wiki is free software; you can redistribute it and/or modify # it under the terms of the Revised BSD License; see LICENSE file for # more details. """Misc utils functions.""" import re from flask import url_for def clea...
import random f=open('C:\Python34\state-capitals.txt','r') h=open('C:\Python34\hangman.txt','r') first_input = input("Please type 1 to play states-capitals game, type 2 to play hangman! :") if first_input == '1': lines=f.readlines() states=[splitted.split(',')[0] for splitted in lines] capitals =[splitted.split(...
import xlrd def open_file(path): """ Open and read an Excel file """ book = xlrd.open_workbook(path) # get the first worksheet first_sheet = book.sheet_by_index(0) print(first_sheet.get_rows()) mainData_book = xlrd.open_workbook(path, formatting_info=True) mainData_sheet = mai...
def answer(n): if len(n)>32: n=long(n) else: n=int(n) return even_divide(n, 0) def even_divide(n, step): if n==0: return step if n==2: return step+1 while n%2==0: n>>=1 step+=1 return odd_divide(n, step) def odd_divide(n, step): if n==1: return step if n==3: return step+2 # low=even_divide(n...
def answers(total_lambs): mg=most_generous(total_lambs) ms=most_stingy(total_lambs) return ms-mg def most_stingy(n): ''' first and second lowest level get paid one lambs other level henchmen gets paid the sum of their subordinates and subordinate's subordinate's pay 1,1,2,3,5,8,13, ... ''' prev_prev=1 prev...
import datetime from nepali_date import NepaliDate def split_date(date): ''' split the year month string and return it format: yyyy-mm-dd ''' splitted_date = date.split('-') year = splitted_date[0] month = splitted_date[1] day = splitted_date[2] return year, month, day def ...
# searching for an item in an ordered list # this technique uses a binary search items = [6, 8, 19, 20, 23, 41, 49, 53, 56, 87] def binary_search(item, item_list): # get the list size list_size = len(item_list) - 1 # start the two ends of the list lower_index = 0 upper_index = list_s...
from sys import argv def scale(n, o, N): return float(o)**(float(n)/float(N)) if len(argv) != 3: exit('usage: scale octave N') print argv[0], argv[1], argv[2] table = [scale(i, float(argv[1]), float(argv[2])) for i in xrange(0, int(argv[2])+1)] for val in table: print '%.32f'%val
a=2 print (a) b=4.25 print (b) c="c" print (c) print(c*3) d="HELLO" print (d) print(d*3)
import datetime def Viernes(x): x = datetime.date.weekday(x) if (x ==4): return True return False cfecha = input("Escribe una fecha formato dd/mm/yyyy") dfecha = datetime.datetime.strptime(cfecha, "%d/%m/%Y") print(Viernes(dfecha))
one = int(input("一元的张数:")) two = int(input("二元的张数:")) five = int(input("五元的张数:")) print(one+two*2+five*5)
#!/bin/python import sys import numpy as np import math import random import time # Command line arguments # Number of columns for the Betsy board. Set variable as integer to allow numerical operations n = int(sys.argv[1]) # Player whose turn it is. player = sys.argv[2] # The current state of the board board = sys.a...
# Reading packages import pandas as pd # Iteration tracking import time # Xgboost models import xgboost as xgb # Reading data d = pd.read_csv("train_data.csv", low_memory=False).sample(100000) # Converting to categorical all the categorical variables cat_cols = [ 'Store', 'DayOfWeek', 'ShopOpen', ...
# def add_end(L=[]): # L.append('END') # return L # # print(add_end()) # print(add_end()) # print(add_end()) def add_end(L=None): if L is None: L = [] L.append('END') return L print(add_end()) print(add_end()) print(add_end()) def calc(*numbers): sum = 0 for n in numbers: ...
from tkinter import * import sqlite3 import sys import tkinter.messagebox # create connection conn = sqlite3.connect('database1.db') # cursor to move c = conn.cursor() # tkinter window class Application: def __init__(self,master): self.master = master #labe...
import math a = int(input('Input number: ')) b = int(input('Input number: ')) c = int(input('Input number: ')) x = (b**2) - (4*a*c) def first_solution(a: int, b: int, c: int) -> int: if x < 0: return 'Math error' return (-b-math.sqrt(x))/(2*a) def second_solution(a: int, b: int, c: int) -> int: ...
int('100') # String -> Integer str(100) # Integer -> String float(10) # Integer -> Float list((1, 2, 3)) # Tuple -> List list({1, 2, 3}) # Set -> List tuple([1, 2, 3]) # List -> Tuple tuple({1, 2, 3}) # Set -> Tuple set([1, 2, 3]) # List -> Set set((1, 2, 3)) # Tuple -> Set # Also Change Data Type Using * tpl = (1, 2,...
a, b, c = 100, 200, 300 if a > b and a > c: print(f"{a} is biggest number!") elif b > a and b > c: print(f"{b} is biggest number!") else: print(f"{c} is a biggest number!") # Output: 300 is a biggest number! a, b = 100, 200 print(f"{a} > {b} or {a} < {b}") if a > b or a < b else print(f"{a} = {b}") # Out...
lista = ["Polak","Rosjanin","Niemiec"] print(lista) lista.append("Turek") #dodoanie elementu do listy print(lista) lista.sort() #sortowanie listy print(lista) lista.reverse() #sortowanie malejące print(lista) liczby = [4,53,27,67,9,23,64,4,372] liczby.sort() print(liczby) liczby.sort(reverse=T...
def lookAndSay(number): result = "" lastDigit = number[0] digitCount = 1 for index in range(1, len(number)): digit = number[index] if digit == lastDigit: digitCount += 1 else: result += str(digitCount) digitCount = 1 result += lastD...
#challenge one print("First challenge") print("Python is fun") print("Everyday I learn and grow in different ways.") #challenge two print("Second challenge") n = 11 if n < 10: print("variable is less than 10") else: print("variable is greater than or equal to 10") #challenge 3 print("Third challenge") n = 26 ...
n = input("임의의 정수(1~9) 입력:") for i in range(n): for j in range(n): if i >= j: print("j", end = "") else: print("*", end = "") print("")
# -*- coding: utf-8 -*- """Module containing functions that find repeat sequences using regular expressions. by Cristian Escobar cristian.escobar.b@gmail.com Last update 3/10/2022 """ import time import re def open_sequence(file_name): """Open Nucleotide sequence file. Method that opens g...
""" Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. https://drive.google.com/file/d/10Q1r4ooc2-w_mgZgrBY4zqUlYibBHdQI/view?usp=sharing """ numbers_count = int(input('Введите кол-во чисел в последовательности 1 -0.5 0.25 -0.125 ...: ')) num...
# Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого) a = float(input(f'Введите число a: ')) b = float(input(f'Введите число b: ')) c = float(input(f'Введите число c: ')) if b < a < c or c < a < b: print('Среднее:', a) elif a < b < c or c < b < a: print('Среднее:...
""" Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. https://drive.google.com/file/d/10Q1r4ooc2-w_mgZgrBY4zqUlYibBHdQI/view?usp=sharing """ user_number = input('Введите целое положительно число: ') num...
#!/usr/bin/env python graph = {} numberOfNodes = input() for i in xrange(numberOfNodes): v = raw_input() edges = list(raw_input().split()) weights = map(int, list(raw_input().split())) graph[v] = dict(zip(edges, weights)) nodes = graph.keys() distances = graph unvisited = {node: None for node in nodes...
""" ways to get objects. By ID driver.find_element_by_id By Class Name driver.find_element_by_class_name By Tag Name driver.find_element_by_tag_name By Name driver.find_element_by_name By Link Text driver.find_element_by_link_tex...
import numpy as np from PIL import Image import os import sys def convert_rgb_to_grayScale(image, image_shape): new_image = np.zeros((image_shape[0], image_shape[1])) for i in range(0, image_shape[0]): for j in range(0, image_shape[1]): new_image[i][j] = np.average(image[i][j]) return new_image # We know ...
import types import numpy as np import math """ Trapezius Rule (an approximation of an integral) @param f: lambda function, f(i) returns a float value. @param a: interval initial x value, float. @param b: interval final x value, float. @param h: interval step, float. @return : float (area). """ def trapezius(f, a, b,...
''' Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. ''' def isPalindrome(number): if str(number) == str(number)[::-1]: return True else: return False print(isPalindrome(-111))
import Procedure import Syntax from Types import dot, symbol from fractions import Fraction as rational def Schemify(exp): '''Convert an expression to Scheme syntax for display purposes.''' # Nothing to represent if exp == None: return '' # Procedures elif isinstance(exp, Procedure.Procedure): if exp.N...
#empty list list1 = [] #list of intergers list2 = [2, 50, 94, 48] #list with mixed datatypes list3 = ["Danny", 24, "Murder", 54] #nested lists list4 = [10000, ["hacks", 101, "brute", 504],"Flames",[707]] #accessing a list eg, list3 murder segment print(list3[2]) #accessing a whole list by slicing operator : ...
def ChkNum(): num1 = input("Enter number : ") print(num1) # Check Condition if int(num1) % 2 == 0: print("Even Number") else: print("Odd Number") ChkNum()
# Script creates a Hashmap object class Hash: # The maximum elements, m, in the Hashmap is defined when the class is instantiated def __init__(self, m): self.array = [0]*m self.size = 0 self.max = m # ___Hash Functions___ # The modulos ensure that the numbers don't exceed a cer...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Yan Somethingrussian <yans@yancomm.net>" __version__ = "0.1.0" __description__ = "An automatic format string generation library." """ Finding the character offset: 1. Run the program 2. Provide the format string, e.g., "FORMATSTRING%n%n%n%n" as input 3. C...
playlist = {"title": "Patagonia Bus", "author": "Marius Toader", "songs": [ {"title": "song1", "artist": ["blue"], "duration": 2.35}, {"title": "song2", "artist": ["kitty", "dj kat"], "duration": 2.55}, {"title": "miau", "artist": ["garfield"], "duration": 2.00} ] } total_length = 0 for song in playlist[...