text
stringlengths
37
1.41M
#!/usr/bin/env python from __future__ import division from sys import stdin from copy import copy """ Strategies to implement: * Create a list of high priority planets for me and for the enemy * expansion phase when the enemy does not have that many planets (i.e., at beginning) or when the enemy does not have much ...
""" Documentation for misc_utils A collection of various useful function to be reused outside class""" import datetime import logging from logging.handlers import RotatingFileHandler class funcLogger(): """This is a class to manage file logging""" _func_count = {} def __init__(self, filename="timings.txt...
def sumofdiv(number): divisors = [1] for i in range(2, number+1): if (number % i)==0: divisors.append(i) return sum(divisors) t = int(input()) for i in range(t): c = int(input()) for i in range(1,c): if c == sumofdiv(i): print(i) else: print(-1) print('Hello, World') print(...
import util """ Data sturctures we will use are stack, queue and priority queue. Stack: first in last out Queue: first in first out collection.push(element): insert element element = collection.pop() get and remove element from collection Priority queue: pq.update('eat', 2) pq.update('study', 1) ...
class Solution: def rotate(self, matrix): import math """ Do not return anything, modify matrix in-place instead. """ n=len(matrix) half=math.ceil(n/2) print(n,half) for i in range(n): for j in range(i,n): matrix[i][j],matr...
''' 1367. 二叉树中的列表 ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None ...
""" Representation of some objects used in regex. """ class Node: # pylint: disable=too-few-public-methods """ Represents a node in the tree representation of a regex Parameters ---------- value : str The value of the node """ def __init__(self, value): self._value = value ...
"""Provides the HTTP request handling interface.""" from typing import TYPE_CHECKING, Any, Optional import requests from .const import TIMEOUT, __version__ from .exceptions import InvalidInvocation, RequestException if TYPE_CHECKING: from requests.models import Response from .sessions import Session class...
# Написати клас Army, для того щоб оптимізувати код. І від нього спадкувати класи OrcArmy та ElfArmy class Army: def __init__(self, warrior_amount, damage_per_orc, warrior_health, shield=0): self.warrior_amount = warrior_amount self.damage_per_orc = damage_per_orc self.warrior_health = warri...
def get_next_multiple(num): result = 0 while True: result += num yield result gen_multiple_of_two = get_next_multiple(2) print(next(gen_multiple_of_two)) print(next(gen_multiple_of_two)) print(next(gen_multiple_of_two)) print(next(gen_multiple_of_two)) gen_multiple_of_thirteen = get_next_mul...
rainbow_colors = ("RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "INDIGO", "PURPLE") user_color = (input("Введите цвет: ")).upper() if user_color in rainbow_colors: index = rainbow_colors.index(user_color) if index != 0: print(rainbow_colors[index - 1]) if index != 6: print(rainbow_colors[index...
# Напишіть функцію beautiful_list_generator, що приймає список, символ (маркер) # та назву файлу. Функція створить файл з назвою, що в неї передали і маркером # та помістить цей список в сприйнятний для більшості формі. def beautiful_list_generator(lst: list, marker: str, file_name: str) -> bool: try: with ...
week_days = {"1": "monday", "2": "tuesday", "3": "wednesday", "4": "thursday", "5": "friday", "6": "saturday", "7": "sunday" } daily_routine = {"monday": ["wash and put away dishes", "wipe down mirrors"], "tuesd...
data = input("Enter your text: ") flag = False result = '' for symbol in data: if symbol == '.': flag = True if flag and symbol.isalpha(): symbol = symbol.upper() flag = False result += symbol print(result)
# Реалізуйте клас Apartment, який буде мати властивості номер квартири, кількість жителів квартири, # поверх та площа квартири. Використайте property, для задання та зміни параметрів. class Apartment: def __init__(self, number_flat, inhabitants, number_floor, area_flat): self.number_flat = number_flat ...
def draw_board(board): print("-------------") for i in range(3): print("|", board[0+i*3], "|", board[1+i*3], "|", board[2+i*3], "|") print("-------------") def validation(move, board): try: move = int(move) except: return False if move not in board: return ...
### Created on 25-05-2019 def input_matrix(matrix, row, col): for i in range(row): # Loop for row entries r = [] for j in range(col): # Loop for column entries r.append(int(input('Entry in row ' + str(i+1) + ' col ' + str(j+1) + ': '))) matrix.append(r) def add_matrix(mat...
### Created on 12-05-2019 nums = input('Enter some numbers (separate by space): ').split() # Calculate the average sum_of_nums = 0 for num in nums: sum_of_nums += float(num) avg = sum_of_nums / len(nums) # Display the numbers & the average print('\nYou entered:', *nums, end=' ') print('\nThe average:', avg)
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn import preprocessing import pandas as pd import matplotlib.pyplot as plt import numpy as np chocolate = pd.read_csv("C:\choco.csv", delimiter=',') data_random = chocolate.sample(frac=1) keep...
#coding:utf-8 import re #需求 :从下面的字符串吧c#替换成GO语言 a = 'C|C++|Java|C#|Python|Javascript|PythonC#C#' def convert(value): matched = value.group() return '!!' +matched +'!!' # r = re.sub('C#','Go',a) #运行:C|C++|Java|Go|Python|Javascript|PythonGoGo 默认是0 # r = re.sub('C#','Go',a ,0) #运行:C|C++|Java|Go|Python|Javasc...
#coding:utf-8 # CONDITION = True # i=1 # while i <= 10: # i=i+1 # print(i) # else: # print("玩了这么多把终于打到了最强王者") #while的使用场景 上王者使用while 设定一个目标 达到目标就不执行了 #递归算法里面用while是非常合适的 #for的使用场景 遍历序列或者集合 或者字典 a = ['apple','orange','banna','grage'] c = [['apple','orange','banna','grage'],(1,2,4)] b = {'达理',"2...
#!/usr/bin/python import sys import os import requests if len(sys.argv) < 2: print """ args are ip_address [param_name....] if no params are specifed, all are shown if one is requested, then its value is shown if more than one is requested, then they results are shown as param_name<tab>param_value ... """ ...
print("Hallo Selamat datang bebey") print("-----------------------") kondisi = int(input("Sekarang jam berapa iya?(ex: 13, format 24 jam): ")) print(" ") if 1<=kondisi<=4: print("Kamu belum tidur? Begadang? tidur lah bebey 😢") elif 5<=kondisi<=11: print("Selamat Pagi Bebey ❤ ❤ ❤") elif 12<=kondisi<=15: print("...
# two-part exercise from cs115 import map ''' Part 0 Here is a memoized version of edit distance. Your task: make it trace the calls to fastED_help, indented according to recursion depth. Hint: add a parameter to fastED_help. ''' def fastED(first, second): '''Returns the edit distance between the strings first a...
from cs115 import * def div(k): return n % k == 0 def divides(n): 'checks if there is a remainder' def div(k): return n % k == 0 return div def divisibles(n,L): 'assume L is a list of integers; return a list of the one divisible by n' if L==[]: return [...
from cs115 import * import math def inverse(n): '''returns the reciprocal''' return 1/n def add(x,y): '''adds 2 inputted variables''' return x+y def divideByFact(x): '''divides 1 by the inputted variales factorial''' return 1/math.factorial(x) def e(n): '''uses a taylor series to approxim...
def skill_agility(answer, person): # меняет ловкость use the 1 option as negative in question while person['skills']["luck"] > 0 and person['skills']["agility"] > 0: if answer == '1': person['skills']["luck"] = person['skills']["luck"] - person['cargo']["risk_precent"] person['s...
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("number\tsquare\tcube") number square cube >>> for i in range(6): print(i,"\t",pow(i,2),"\t",pow(i,3)) 0 0 0 1 1 1 2 4...
# pycal.functions.py from pprint import pprint import math class Trigonometry: def __init__(self, name:str=None, *args, **kwargs): ''' Trigonometry is a branch of mathematics that studies relationships between the sides and angles of triangles. ''' if name: se...
#a=int(input()) #if (a==4): # print("this is down. you win ") #if (a!=4): #else: # print("oops, your gues is wrong") #x=input() #y=input() #if (x>y): # print(x+("is greater")) #else: # print(y+("the number is greater")) x=int(input()) y=int(input()) if (x>y): print(str(x)+("is greater")) else: print(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from ..find_anagram import find_anagrams class TestFindAnagrams(unittest.TestCase): def test_should_find_anagram_with_list_arg(self): result = find_anagrams('roma', ['amor', 'teste', 'mora']) self.assertEqual(len(result), 2) def ...
class Node: def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def __len__(self): node = self.head length = 0 while node: node = node.next length += 1 retur...
t = int(input()) if (t%3==1): print((t//3 -1)*7 + 4) else: if (t%3 ==2): print((t//3)*7 +1 ) else: print(t // 3 * 7)
# Question: Calculate the sum of the values of keys a and b . d = {"a": 1, "b": 2, "c": 3} # Expected output: # 3 # Answer print(d['a'] + d['b']) # Explanation: # It's as easy as that. However, if you want to do the sum of all dictionary values you need to take another approach instead of accessing all values ...
""" use Monte Carlo method for simulation which uses random sampling to evaluate possible outcomes. this program will determine the probability of certain outcomes when rolling dice. Input: variable number of arguments for sides of dice Output: table of possible outcome example: roll_dice(4, 6, 6) => useing 4 side die...
# Question: Use Python to calculate the distance in kilometers between Jupiter and Sun # on January 1, 1230. # Hint 1: Use the ephem Python third party library. # Hint 2: Note that the units of ephem are in Astronomical Units (AU). # You need to convert them to kilometers. # Expected output: # 758085657.5026425 ...
class Account: def __init__(self, name, balance, min_balance): self.name = name self.balance = balance self.min_balance = min_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance - amount >= self.min_balance: ...
# download the attached ZIP file and extract its files in a folder. # Then, write a script that counts and prints out the number of .py files in that folder. import pathlib count = 0; for path in pathlib.Path('./92_files').iterdir(): if path.is_file() and path.suffix == '.py': count += 1; print(f'Number ...
import configparser def main(): print("***** Welcome to Your Weights on differnt Planets ***** ") user_answer = 'Y' try: while user_answer == "Y": weight = input("\nPlease enter your weight(lbs) on EARTH : ") if weight != "": weight_converter(int(weigh...
# Question: Make a script that prints out numbers from 1 to 10 # Expected output: # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Answer: for item in range(1,11): print(item) # Explanation: # A for loop is used to repeat an action (i.e. print ) until the iterating sequence (i.e. range ) is consumed. In our case it...
import pickle class Animal: def __init__(self, name, species): self.name = name self.species = species def __repr__(self): return f"{self.name} is a {self.species}" def make_sound(self, sound): print(f"this animal says {sound}") class Cat(Animal): def __init__(self, name, breed, toy): super().__init_...
collection = ["gold", "silver", "bronze"] # list comprehension new_list = [item.upper for item in collection] # generator expression # it is similar to list comprehension, but use () round brackets my_gen = (item.upper for item in collection)
# Input: A list / array with integers. For example: # [3, 4, 1, 2, 9] # Returns: # Nothing. However, this function will print out # a pair of numbers that adds up to 10. For example, # 1, 9. If no such pair is found, it should print # "There is no pair that adds up to 10.". def pair10(given_list): numbers_se...
def count_up(x, maximum): if x > maximum: print("Done!") return print(x) count_up(x+1, maximum) count_up(1, 10)
# Two nested loops are O(n^2) my_favourite_desserts = ["chocolate", "ice cream", "crackers"] quantities = [10, 20, 30] for item in my_favourite_desserts: for q in quantities: print(item, " - ", q)
import json people_string =''' { "people":[ { "name":"John-Smith", "phone":"123-456-789", "emails":["john@test.com","smith@gmail.com"], "has_license":false }, { "name":"Doey Timberlake", "phone":"444-555-666", ...
import random import configparser def main(): user_answer = 'Y' print("******* Welcome to Magic 8 Balls *******") while user_answer == 'Y': question = input("What would you like to know? please ask me your question.\n") if question == "": print("Seem like you have nothing t...
# Python Object Oriented Programming by Joe Marini course example # Using composition to build complex objects class Book: def __init__(self, title, price, author): self.title = title self.price = price self.author = author self.chapters = [] def addchapter(self, chapter): ...
def bubble_sort(items, ascending = True): n = len(items) is_sorted = True for i in range(n): for j in range(1, n - i): if ascending: if items[j] < items[j-1]: items[j], items[j-1] = items[j-1], items[j] is_sorted = False ...
""" Palindrome: word or phrase that reads the same forwards as backwards Input: string of word or phrase Output: True/False Only consider letters (A-Z) Ignore Capital Letters Example: level => Palindrome Example: Racecar => Palindrome Example: Go hang a salami - I'm a lasagna hog => Palindrome """ import re def is_pa...
import unittest import addition class TestMain(unittest.TestCase): def setUp(self): print("about to run a function.") def test_add_1(self): '''Sample doc string''' test_param1 = 10 test_param2 = 20 result = addition.add(test_param1,test_param2) self.assertEqual...
def fibonacci(n): '''Return nth number of fibonacci sequence''' if n < 2: return n else: return fibonacci(n-1) + fibonacci(n-2) if __name__ == "__main__": for i in range(1, 10): print(fibonacci(i))
from time import perf_counter from functools import wraps def timer(func): @wraps(func) def wrapper(*args, **kwargs): start = perf_counter() result = func(*args, **kwargs) end = perf_counter() duration = end - start args = str(*args) print(f"{func.__name__}({ar...
# This is generator function which will return generator object def even_integers_function(n): for i in range(n): if i%2 == 0: yield i if __name__ == "__main__": even_gen = even_integers_function(10) print(even_gen) #generator object got returned. print(list(even_gen)) #now generat...
"""Reterive and print words from a URL. Usage: python3 words.py <URL> Example: python words.py http://sixty-north.com/c/t.txt """ import requests import sys def fetch_words(url): """Fetch a list of string from URL. Args: url: The URL of a UTF-8 text document. Returns: A list o...
#from database.db, print out those countries with an area of greater than 2,000, 000. import sqlite3 conn = sqlite3.connect('database/database.db'); c = conn.cursor(); c.execute('SELECT * FROM countries WHERE area >= 2000000;'); results = c.fetchall(); for country in results: print(",".join(str(data) for data i...
# Question: The script is supposed to output the cosine of angle 1 radian, but instead it is throwing an error. Please fix the code so that it prints out the expected output. # import math # print(math.cosine(1)) # Expected output: # 0.5403023058681397 # Answer: import math print(math.cos(1)) print(dir(math)) #...
# # Example file for variables # # Declare a variable and initialize it x = 100 print(x) # # re-declaring the variable works x = "abc" print(x) # # ERROR: variables of different types cannot be combined # print("hello" + 123) print("hello" + str(123)) # Global vs. local variables in functions def some_func(): ...
from functools import reduce # def accumulator(acc, item): # print(acc, item) # return acc + item # acc gets assign this result on next run # items = [1, 2, 3] # print("Result: ", reduce(accumulator, items, 10)) #reducing list of string into total word length def word_length(acc, item): # return len(it...
# Python Essential Libraries by Joe Marini course example # Example file for using Requests library import requests # use a timeout value for a request resp = requests.get("https://httpbin.org/delay/0.5", timeout=1.0) print(resp.status_code) # simulating timeout error => website took 2.0 seconds to response, our prog...
#create a program that generate a password of 6 random alphanumeric characters in the range #abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()? # Answer 1: import random st = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?' password = '' for i in range(6): passwor...
# 1 What would be the output of the below 4 print statements? #Try to answer these before you click RUN! print("Hello {}, your balance is {}.".format("Cindy", 50)) print("Hello {0}, your balance is {1}.".format("Cindy", 50)) print("Hello {name}, your balance is {amount}.".format(name="Cindy", amount=50)) print("He...
# Question: Create a program that prints out Hello every two seconds. # Expected output: # ... # Hello # Hello # Hello # Hello # Hello # Hello # ... # Answer: import time while True: print('Hello') time.sleep(2) # Explanation: # The sleep method of the built-in time module suspends the execution of the ...
#create a script that lets user submit a password until they have satisifed three conditions. #1) Password contains at least one number #2) Contains one upper letter #3) It is at least 5 chars long # Print out message 'password is not fine' if the user didn't create a correctly satisfied password # Answer (using regex...
#filter def only_odd(item): return item % 2 != 0 my_list = [1,2,3] print(my_list) print(list(filter(only_odd, my_list)))
import random CHOICE = ["Rock", "Paper", "Scissor"] DRAW = 0 WIN = 1 LOSE = 2 def get_result(user_choice, computer_choice): if user_choice == "R" and computer_choice.startswith("P"): return 2 elif user_choice == "R" and computer_choice.startswith("S"): return 1 elif user_choice == "P" and ...
import pprint message = "Today is quite cloudy in Yangon. I just watched #Alive korean zombie moive which is pretty good." count = {} for character in message.upper(): count.setdefault(character, 0) #if key doesn't exist in dict, set 0 as default value count[character] = count[character] + 1 #pprint.pprint(...
"""" print the picture of the lists in terms of grid as below shape ..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... """" grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', ...
#!/usr/local/bin/python3 import sys import os SearchDir = "/" SearchExt = ".mp3" # Default extension. numargs = len(sys.argv) if numargs > 3: print("Error - too many arguments supplied.") sys.exit() elif numargs == 2: if sys.argv[1][0] == ".": SearchExt = sys.argv[1] else: if os.path.isdir(sys.argv[1]): ...
"""contient les méthodes d'accès aux fichiers""" import pickle class Files: def fopen(path): file = open(path, 'r') content = file.read() file.close() return content fopen = staticmethod(fopen) def dic_saver(origin, map, dictionnary): with open(origin+map, 'wb') a...
##################################################################################################################### # AUTHOR: # Gabrielle Talavera # # DESCRIPTION: This project simulates a mesh network where nodes and links may fail. Nodes may fail intermittently, # and as an input to the simulation, each node a...
#!/bin/python def sort2arrays(a,b): l = [] pta, ptb, ptl = 0,0,0 while pta < len(a) and ptb < len(b): if a[pta] < b[ptb]: l.append(a[i]) pta+=1 print sort2arrays([2,4,6,8,10], [1,3,5,7,9])
#!/usr/bin/python def insertion_sort(items): """ Implementation of insertion sort """ for i in range(1, len(items)): j = i while j > 0 and items[j] > items[j-1]: items[j], items[j-1] = items[j-1], items[j] print items ...
"Show-off the Circuitous code from the user's point of view" from __future__ import division from circuitous import Circle print u'Tutorial for Circuitous\N{trade mark sign}' print 'Circle class version %d.%d' % Circle.version[:2] c = Circle(10) print 'a circle with a radius of', c.radius print 'has an area of', c.ar...
#!/usr/bin/python fib_dict = {} def cache_fib(fib_func): print 'inside cache_fib' def fib_wrapper(n): if n not in fib_dict: fib_dict[n] = fib_func(n) return fib_dict[n] return fib_wrapper @cache_fib def fib(n): print 'aparna looses' if n == 0 or n ==1: return n...
import random def main(): print('Guessing game') print('Guess a number between 1 and 100') m,c = start() if c == 0: print(m) else: print(m+' in '+str(c)+' tries') def start(): guess = -1 c=0 f=True rannum = random.randint(1,100) print(rannum) while True: ...
# 列表推导式 # 计算从1到10的所有偶数的2次幂 # 第一种方式 alist = [] # 定义一个存放2次幂的列表 for i in range(1, 11): if i % 2 == 0: alist.append(i * i) print(alist) # 第二种方式,使用列表推导式 blist = [i * i for i in range(1, 11) if i % 2 == 0] print(blist)
price = 10 pen = 0.38 rain = True name = 'kevin' print(price, pen, rain, name) name = input('请输入名字:') print('Hello,' , name) height = input('请输入身高:') weight = input('input your weight:') print('你的身高是:' , height) print('你的体重是:' , weight, '该减肥了') major = input('input your major:') print('your major:' , major)
def bubble_sort(arr): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True x = -1 while swapped: swapped = False x = x + 1 for i in range(1, n - x): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = T...
import pandas as pd import numpy as np class dataPandas: def __init__(self): self.fields = ['season', 'week', 'away_team', 'a_score', 'away_elo_i', 'home_elo_i','away_elo_f', 'home_elo_f'] self.df = pd.read_csv('nfl_results.csv', usecols=self.fields, low_memory=False) self.away_team = self.season = self.week = ...
pizzas = ['New York','chicago','Pan','Thick','Cracker']; message = 'The first three items in the list are:'; print(message); print(pizzas[:3]); print('Three items from the middle of the list are:'); print(pizzas[1:4]); print('The last three items in the list are:'); print(pizzas[-3:]); friend_pizzas = []; pizzas.append...
#coding=gbk print('=========================ֵѵʼ========================================='); friend = {'first_name':'Ma', 'last_name':'Yuhua', 'age':'25', 'city':''}; print(friend); print(); likeNum = {'Mayh':'2','Mazh':'4','Magy':'8','Vsky':'5','fly':'9'}; print(likeNum); course = {'var':'','str':'ַ','num':'','list':'б...
#coding=gbk print('=========================ָ=========================='); class Resturaurant(): def __init__(self, restaurant_name, cuisine_type): """ʼrestaurant_name,cuisine_type""" self.restaurant_name = restaurant_name; self.cuisine_type = cuisine_type; self.number_served = 0; ...
import sqlite3 import json #Read data from json (Socrata Database) f = open("testjson.txt", "r") content = f.read() dict_all = json.loads(content) #Connection to SQLite Database conn = sqlite3.connect('testing3.db',isolation_level=None) c = conn.cursor() #Get count of all tables in the database c.execute("SELECT nam...
def replace_char(s , n , c): s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:] return s def replace_interval(a,b,s,c): for i in range(a,b+1): s = replace_char(s,i,c) return s def base_triangle(z): a = "1" b = "_" # c = "_" j = 1 n = z li = [] for i in range(0,n - 1): li.append(((b) * (...
class EmptyPiece: def __init__(self): self.player = -1 def get_neighbors(): return [] # Data structure to hold information about pieces # Useful for doing bfs class Piece: def __init__(self, player=-1, pos=None, neighbor1=None, neighbor2=None, neighbor3=None, neighbor4=None, neighbor5=Non...
#! /usr/bin/env python3 # Michael Gates # 23 October 2017 # Test suite implementations for lab07 # The parameter intList is supposed to be a list of integers. # The function returns the product of the odd integers from intList, and leaves intList not​ ​modified​. # For instance, given [1,2,3,4], the function retur...
#! /usr/bin/env python3 # Michael Gates # 3 October 2017 # Various math functions import testsuite def absolute_value(x): # return the absolute value of x return x if x >= 0 else x * -1 def is_divisible(x, y): # return true if x is divisible by y, false otherwise return x % y == 0 def to_power(x, ...
from helpers import alphabet_position, rotate_character def encrypt(text,rot): encrypted_word = "" for char in text: letter = rotate_character(char,rot) encrypted_word = encrypted_word + letter return encrypted_word def main(): text = input("Type a message: ") num = int(input...
from math import radians, cos, sin, asin, sqrt class Edge(object): """ Base class for Edge classes. """ @classmethod def connect_edge_pairs(cls, edge_pairs): """ Return a new list with edges (pairs of point_a, point_b) ordered as they're connected in the graph. Eg: ...
##################### # Hangman.py # # Simulates a "Hangman" game # # #################### import random import json import click def build_word_map(): """ words = {"fruit": ["apple", "banana", "grapes", "pear", "watermelon"], \ "places": ["school", "church", "library", "mall", "restaurant", "ai...
songs = ["ROCKSTAR", "Do It", "For The Night"] print(songs[0]) print(songs[len(songs) - 1]) print(songs[1:3]) songs[0] = "Butterfly Effect" print(songs) songs.extend(["Neon", "Lemonade", "Dil Nadia"]) print(songs) del songs[1] print(songs) animals = ["Fish", "Snake", "Turtle"] animals.append("Bird") print(anima...
import json def read_coordinates(filename='coordinates.json'): """ Summary line. Parameters ---------- arg1 : int Description of arg1 Returns ------- int Description of return value """ with open(filename, 'r') as input: # Example plot: http://www....
# https://adventofcode.com/2020/day/8 with open("day8.input.txt", "r") as f: input = f.read().splitlines() exampleInput = """nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6""".splitlines() def nop(argument, accumulator, i): return accumulator, i + 1 def acc(argument, accumulator, i): ...
def is_positive(number): if number > 0: return True return False def greet(name, time): if 7 < time < 12: print 'Good morning %s' % name elif time < 18: print 'Good afternoon %s' % name elif time < 23: print 'Good night %s' % name else: print '%s, you sho...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re def get_input(): s = raw_input("please input:") return s # while True: # print eval(get_input()) def is_exit(s): if "q" == s.lower(): print "bye~" exit(0) def check(s): # encode, decode if "/0" in s: print u"除数...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re s = "123*&sadf sdf13770976666Aa13770976677df12ssdf" match_re = ".*?((13|15)\d{9}).*" phone = re.match(match_re, s) type(phone) for i in phone.group: print i # if phone: # phone = phone.group(1) # print phone.group(2) # print phone
""" purpose : Add the Prime Numbers that are Anagram in the Range of 0 - 1000 in a Queue using the Linked List and Print the Anagrams from the Queue @Author : Rohini Zade @version : 1.0 @since : 30-11-2018 """ from com.bridgelabz.utility.Utility import Utility from com.bridgelabz.utility.Datastruc...
""" purpose : print the prime numbers which are anagram from given range in a 2D Array @Author : Rohini Zade @version : 1.0 @since : 29-11-2018 """ from com.bridgelabz.utility.Utility import Utility from com.bridgelabz.utility.Datastructure_utility import * if __name__ == "__main__": utility_obj = Utili...
file = open("mtainfo.csv", "r") csv = file.readlines() file.close() print (csv[:10]) def splitCommas(list): ctr = 0 while ctr < len(list): list[ctr] = list[ctr].split(", ") ctr += 1 ctr = 0 while ctr < len(list): list[ctr] = list[ctr][0].split(",") ...