text
stringlengths
37
1.41M
''' https://www.geeksforgeeks.org/mongodb-and-python/ ''' # importing module from pymongo import MongoClient # creation of MongoClient # Connect with the portnumber and host try: cluster = MongoClient("mongodb://localhost:27017/") # cluster = MongoClient("mongodb+srv://ameya:<pwd>@cluster0.csmbw.mongodb.ne...
import sys a = sys.argv[1] dosya = open(a, "r") liste = [i for i in dosya.read().split("\n")] chart = [i.split(" ") for i in liste] number_of_deleted = 0 def fibonacci(n): if n < 2: return n else: return fibonacci(n - 2) + fibonacci(n - 1) def deleteUp(row, column): globa...
import sys def fizz_buzz(line): X, Y, n = tuple([int(i) for i in line.split(' ')]) output_seq = ['1'] for i in range(2, n + 1, 1): result_str = '' if i / X == i // X: result_str = 'F' if i / Y == i // Y: result_str += 'B' if not result_str: result_str = str(i) output_seq.ap...
""" Useful decorators """ from functools import wraps from utils.seed import Seed def cascade(func): """ class method decorator, always returns the object that called the method """ @wraps(func) def wrapper(self, *args, **kwargs): func(self, *args, **kwargs) return self retu...
# numbers = range(1,4) # products = {} # for num1 in numbers: # for num2 in numbers: # products.update({num1*num2 : [(num1, num2)]}) # products = {1: [(1, 1)], 2: [(2, 1)], 3: [(3, 1)], 4: [(2, 2)], 6: [(3, 2)], 9: [(3, 3)]} # products[1][len(products[1])-1] = "blue" #print(products) # test_list = [1, ...
def convert(number): conversion = {3 : "Pling", 5 : "Plang", 7 : "Plong"} code = ''.join([value for key, value in conversion.items() if number % key == 0]) if code: return code return str(number)
from random import shuffle from random import randint class Robot: names = [] def __init__(self): self.name = self.pick_name() def reset(self): self.name = self.pick_name() return self.name def __repr__(self): return self.name def pick_name(sel...
class Matrix(object): def __init__(self, matrix_string): self.matrix_string = matrix_string splitted = self.matrix_string.splitlines() self.numbers = [[int(num) for num in item] for item in [item.split() for item in splitted]] def row(self, index): return self.numbers[index-1].co...
""" An Adaption of Homework 10, Problem 1, Part 1 from Numerical Analysis, Spring 2016 The general least squares method: (1) Create a 'Z' matrix --> a matrix which can be seen as transposed and concatenated lists of each value in a list of independent variables such that the first column...
# необходимо найти остаток от деления n-го числа Фибоначчи на m. def fib(): f = input().split() n, m = int(f[0]), int(f[1]) a = [0, 1, 1] while a[-1] != 1 or a[-2] != 0: a.append((a[-1] + a[-2]) % m) circle = len(a) - 2 print(a[n % circle] % m) fib()
from unittest import TestCase def main() -> None: x_coordinates: list[int] = [] y_coordinates: list[int] = [] for _ in range(int(input())): x, y = input().split() x_coordinates.append(int(x)) y_coordinates.append(int(y)) x1, y1, x2, y2 = count_rectangle(x_coordinates, y_coordin...
from collections import defaultdict from unittest import TestCase def main() -> None: word = input() letters_counts = count_letters(word) for letter, count in sorted(letters_counts.items()): print(f"{letter}: {count}") def count_letters(word: str) -> dict[str, int]: result = defaultdict(int)...
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ #if input_list is None: #print("the list is empty") ...
print("Enter the radius of the circle: ") radius=int(input()) units=input("units of measurement : ") py=3.142 Area=py*(radius*radius) Circumfrance = (2*py*radius) print(f"Area of the circle is {Area} squared {units}") print( f"while its circumference is {Circumfrance} {units}")
dictOfbirthday = {'Tilek':'11.07','Makhmud':'09.10','Jetigen':'04.07','Meka':'28.11'} name = input("who birthday do you want to know: ") data = dictOfbirthday[name.capitalize()] print(f'{name} has birthday on {data} ')
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/12/23 16:07 # @Author : lingxiangxiang # @File : demonIfWhileFor.py # python缩进 # main: # print("hello") # print("hello world") # c main(param){} # java main(param){} # if 判断条件: # 执行语句 # elif 判断条件: # 执行语句 # else: # 执行语句 # while 判断...
# -*- coding: utf-8 -*- """ Created on Thu Sep 23 18:36:29 2021 @author: Evgeniya Vorontsova LC Problem 168 Excel Sheet Column Title Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1:...
# -*- coding: utf-8 -*- """ Created on Thu Sep 9 19:28:23 2021 @author: Evgeniya Vorontsova LC Problem 202 Happy Number Write an algorithm to determine if a number n is happy. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the ...
# -*- coding: utf-8 -*- """ Created on Mon Sep 6 23:30:02 2021 @author: Evgeniya Vorontsova LC Problem 83 Remove Duplicates from Sorted List Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1,1...
# -*- coding: utf-8 -*- """ Created on Wed Sep 22 18:59:46 2021 @author: Evgeniya Vorontsova LC Problem 125 Valid Palindrome Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true Explanation...
import matplotlib.pyplot as plt x1 = [1,2,3,4] y1 = [3,6,7,8] plt.plot(x1,y1,label = "line 1", color = "green",\ linestyle = "dashed", marker="o", \ markerfacecolor="blue", markersize=12) plt.ylim(1,8) plt.xlim(1,8) plt.title("Stylised Line Graph") plt.legend() plt.show()
from random import randint count = 0 def add_quiz(num1, num2): answer = int(input("What is " + str(num1) + " + " + str(num2) + "? : ")) if answer == num1 + num2: print("You guessed it right! Good Job!") return 1 else: print(str(num1) + " + " + str(num2) + "should be " + str(n...
from random import randint number = randint(0,100) guess = 10000 while guess != number: number = randint(0,100) guess = int(input("Guess the number : ")) if guess > number: print("You've guessed too high!") elif guess < number: print("You've guessed too low!") else: ...
def prime(num): count = 0 for i in range(1,num): #[1,2,3,4,5,6,7,8,.......,num-1] if num % i == 0: count+=1 if count == 1: return num for i in range(100): #"Banana" if(prime(i)): print(i)
name = input("Enter Full Name\n") name.strip() name = " " + name abbr = "" for i in range(len(name)): if name[i] == " ": abbr += name[i+1].upper() + ". " print(abbr)
print("Enter two numbers whose greatest common divisor is to be found") num1 = int(input()) num2 = int(input()) gcd = 1 k = 2 while(k <= min(num1, num2)): if num1 % k == 0 and num2 % k == 0: gcd == k k+=1 print("The GCD of the two numbers is", gcd)
#!/usr/bin/python __author__ = "Fabian Schilling" __email__ = "fabsch@kth.se" import sys # conver int to str under certain base def int2str(num, base): (d, m) = divmod(num, base) if d > 0: return int2str(d, base) + str(m) return str(m) # convert from base 7 to (0, 1, 2, 5, 6, 8, 9) system def co...
# binary numbers # 1=0b0001 # 2=0b0010 # hexadecimal # 1=0o001 # 2=0o002 print(0o17) print(0x11) print(123e6) # operatii aritmetice # #x/y impartirea cu virgula number1 = 3 number2 = 4 print('impartire 3/4:', number1 / number2) print('floordiv4/3', number1 // number2) # partea intreaga din nr respectiv care rezulta ...
def crypt_decrypt(string, key): result = [] for letter in string: result.append(chr(ord(letter).__xor__(key))) return ''.join(result) def is_prime(number): for i in range(2, number // 2 + 2): if not number % i: return False return True def generate_primes(limit): res...
'''from tkinter import * mv=Tk() canvas=Canvas(mv, bg="black", height=900, width=1400) canvas.pack() photo=PhotoImage(file="hotel12.png") canvas.create_image(690,350, image=photo) mainloop()''' '''import tkinter from tkinter import * root=Tk() root.geometry("600x600") # def enterd(event): # btn.config(bg="red"...
import random from state import * class Searcher: """ A class for objects that perform random state-space search on an Eight Puzzle. This will also be used as a superclass of classes for other state-space search algorithms. """ def __init__(self, init_state, depth_limit): '...
# Python program to print positive Numbers in a List list1 = [12, -7, 5, 64, -14] list2 = [12, 14, -95, 3] for no in list1: if no >= 0: print(no, end = " ") print() for no in list2: if no >= 0: print(no, end = " ")
from shapely.geometry import Point class Image: """ A Class representing an image object as given in input data """ def __init__(self, row): """ Constructor for class Image, parsing raw feature and validating fields :param feature: feature data from geojson file """ ...
import sqlite3 # Database class DatabaseLogic(): # Constructor def __init__(self, database): # Database self.database = database # Connection and cursor self.con = sqlite3.connect(self.database) self.cursor = self.con.cursor() def checkUser(self, usernam...
from math import sqrt from Vertice import * ## A street # # More details. class Street: ## The constructor # @param name name of the street # @param vertices vertices list # @param oneway bool def __init__(self, name, vertices, oneway): #street name self.streetName = name #vertex list self.streetVertice...
import sys PYTHON_3 = sys.version_info[0] == 3 if PYTHON_3: import builtins else: import __builtin__ def make_builtin(func, name=None): """Make a function act like a built-in function in Python. This is intended to be used sparingly and really only for adding built-in functions so that ccino ...
#!/usr/bin/env python # coding: utf-8 # Diff entries from two sqlite3 db import os import sqlite3 import sys def get_entries(db_name): db = sqlite3.connect(db_name) cur = db.cursor() cur.execute("SELECT name, type, path from searchIndex") entries = cur.fetchall() db.commit() db.close() re...
def ceaser_cipher(): def encrypt_ceaseri( string, key ) : k = [] print "the message sting is is " + string for i in range(0, len(string)): d = ord (string [i]) if ( d + key > 122 ) : d = 97 + ((d+key) % 122)-1 else: d = ...
# sum_digits def sum_digits(num): '''Takes in a non-negative integer, and tells the sum of each of the digits.''' if num == 0: # Making a terminating case, with an if statement return 0 # Terminating Case always returns 0 else: return num % 10 + sum_digits(num // 10) # Recursive Case
# Enter your code here. Read input from STDIN. Print output to STDOUT n=input() lis=[] a =raw_input() lis=a.split() newlis=list(map(int,lis)) newlis.sort() st=set(newlis) st=st.union() L=list(st) L.sort() print L[-2]
#! /usr/bin/env python3 import os import csv import json def create_new_csv_from_json(file_to_write_to, json_data): with open(file_to_write_to, 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',') for line in json_data: # back_of_card = f"{line["kana"]} {line["eng"]...
# -*- coding: utf-8 -*- import random arquivo = open("entrada.txt", encoding="utf-8") palavras = arquivo.readlines() for i in range(len(palavras)-1): palavras[i] = palavras[i].strip().upper() if palavras[i] == '': del palavras[i] palavras[i] = palavras[i].strip().upper() pa = random.choice(palavras)...
#!/usr/bin/env python chars = 'abcdefghijklmnopqrstuvwxyz' while True: sum = 0 inputStr = raw_input() if inputStr: for char in inputStr: if char.lower() in chars: sum += chars.index(char.lower()) + 1 print sum else: break
class A: def sayhi(self): print("I'm in A") class B(A): def sayhi(self): print("I'm in B") objB=B() objB.sayhi() #Python does not support method overloading def add(instanceOf,*args): if instanceOf=='int': result=0 if instanceOf=='str': result='' for i i...
class Car: def __init__(self, brand,model, color, fuel): self.brand=brand self.model=model self.color=color self.fuel=fuel def start(self): pass def halt(self): pass def drift(self): pass def speedup(self): pass def turn(self): ...
from flask import Flask from flask import request app = Flask(__name__) @app.route('/') def monkey(): return ''' <html> <head> <title>Favorite Game</title> </head> <body> <a href="/whatsup?page=2">Next</a> <form action="/processLogin" method="get"> Enter your name:...
def factorial(n): if n==0: return 1 else: return n * factorial(n-1) factorial_of_five = factorial(5) print('The factorial of five is',factorial_of_five) factorial_of_ten = factorial(10) print('The factorial of ten is',factorial_of_ten) print('The factorial of six is',factorial(6)) f = facto...
from random import randint from time import sleep sort = [] temp = [] print('-' * 30) print(f'{"JOGA NA MEGA SENA":^30}') print('-' * 30) jog = int(input('Quantos jogos você quer que eu sorteie? ')) tot = 1 while tot <= jog: cont = 0 while True: num = randint(1, 60) if num not in temp: ...
numeros = [] while True: numeros.append(int(input('Digite um valor: '))) sair = ' ' while sair not in 'SN': sair = str(input('Quer continuar? [S/N] ')).upper().strip()[0] if sair == 'N': break print('=-' * 30) print(f'Você digitou {len(numeros)} elementos.') numeros.sort(reverse=True) pr...
lista = [] pares = [] impares = [] while True: lista.append(int(input('Digite um número: '))) sair = str(input('Quer continar? [S/N] ')) if sair in 'Nn': break for i, v in enumerate(lista): if v % 2 == 0: pares.append(v) else: impares.append(v) print('=-' * 30) print(f'A list...
#!/usr/bin/python for letter in 'this is another test': print('Letters: ', letter) for number in range(0,10000): print(number)
#multi level class name: def __init__(self,n): self.n=intput("name") def names(self): print(self.n) class roll(name): def __init__(self,r): name.__init__(self,n) self.r=r def rolls(self): print(self.r) class student(roll): def __init__(self,s): roll.__init__(self,r) self.s=s def disp...
class Employee: name=input("enter name") ID=int(input("enter your eid")) def Increment(self,bsal): self.bsal=bsal self.hra= (25/100)*self.bsal self.gross=self.bsal+self.hra print("gross",self.gross) obj1=Employee() obj1.Increment(1000) print("name:",getattr(obj1,"name")) print("eid:",getattr(obj1,...
#bitwise operators are used to perform operations on one bit(binary digit) at a time. a=10 b=20 print(a&b) #bitwise and print(a|b) #bitwise or print(a^b) #bitwise EX-OR print(a<<1) #bitwise left shift print(a>>1) #bitwise right shift
from abc import ABC,abstractmethod #abstract base class class AbstractClassExample(ABC): def __init__(self,value): self.value=value super().__init__() @abstractmethod def do_something(self): pass class DoAdd42(AbstractClassExample): def do_something(self): return self.value+42 class DoMul42(A...
def selection_sort(array): for i in range(len(array)): i_min = i for j in range(i+1, len(array)): if array[j] < array[i_min]: i_min = j # finding minimum value in unsorted array if i != i_min: array[i], array[i_min] = array[i_min], array[i] # swap if...
import Cell class Board(): board = [] max_rows = 0 max_columns = 0 def __str__(self): new_str = '' for row in range(self.max_rows): for col in range(self.max_columns): new_str += str(self.board[col + row * self.max_columns]) new_str += "\n" ...
#!/usr/local/bin/python # appends lexicographically smallest rotation at the end of the line import sys import os import re from Bio.Seq import Seq import subprocess as sp def RotateMe(text,mode=0,steps=1): # function from http://www.how2code.co.uk/2014/05/how-to-rotate-the-characters-in-a-text-string/ # Takes...
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup from urllib.request import urlopen import wget ''' Scraping web - Python 3 ''' def scraping_web(url, patron_link): """ Esta funcion me pide una url y me devuelve un lista con los links :param url: pide una url como http://www.google.com con http :...
import datetime last_id = 0 class Note: """ Class for representation of a single note with memo """ def __init__(self, memo, tags=''): """ Initializes a note with memo and tags (remembers creation date) """ self.memo = memo self.tags = tags self.creati...
#!/usr/bin/env python import time import random import RPi.GPIO as GPIO # led-blink.py # From a selection of 5 LEDs, blink them alternatively by randomly # turning each one on and off, while pausing on every loop. The # intention of this script is to create an "alarm" system for a model # house which will make all lig...
def rekursif(angka): if angka > 0 : print (angka) angka = angka - 1 rekursif(angka) else : print(angka) masukan = int(input("masukkan angka : ")) rekursif(masukan)
def reverseItem(item): toString = str(item) stringLent = len(toString) print item # import pdb # pdb.set_trace() newStr = toString[::-1] print newStr if newStr[stringLent-1] == '-': strToInt = 0 - int(newStr[0:stringLent-1]) else: strToInt = int(newStr) return...
"""This module contains basic codes for the project, such as a Wave object to save the rate and data from a .wav files and functions to read the speakers and the utterances. """ import scipy.io.wavfile as wavfile import numpy as np import os class Wave(object): """Class to describe a basic .wav file. The Wave o...
import cv2 from matplotlib import pyplot as plt import numpy as np image = cv2.imread("saggital.png") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # create a binary thresholded image _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_...
import robot import sys from time import sleep def run_auto(r): """ run_auto(r) - The robot will crawl until it sees blue and then turn 180 degrees and crawl the same distance again :param r: a robot class :return: nothing """ print(" ___________________________________") print(" / ...
#!/bin/python3 import math import os import random import re import sys import collections # # Complete the 'collectionfunc' function below. # # The function accepts following parameters: # 1. STRING text1 # 2. DICTIONARY dictionary1 # 3. LIST key1 # 4. LIST val1 # 5. DICTIONARY deduct # 6. LIST list1 # def c...
#!/bin/python3 import math import os import random import re import sys def Reverse(lst): lst.reverse() return lst def stringmethod(para, special1, special2, list1, strfind): # Section 1 --> Ok word1 = "" for character in para: if character not in special1: word1 = word1 + c...
m = bin(585).zfill(8) m = m.lstrip('-0b') palindrome_list = list() def is_palindrom(number): number = str(number) reversed_number = reverse_it(number) if number == reversed_number: binary_number = bin(int(number)) binary_number = binary_number.lstrip('-0b') binary_number = str(...
#Sum square difference number = 0 sum = 0 total= 0 totalsum = 0 numbersum= 0 for x in range(1,101): number = x*x total = total + number for x in range(1,101): numbersum = numbersum + x totalsum = numbersum * numbersum value= totalsum - total print(value)
a = input() b = input() list1 = b.split(' ') score = [] for i in list1: score.append(int(i)) mx1 = max(score) mx2 = -100 for i in score: if i < mx1 and i > mx2: mx2 = i print(mx2)
for cases in range(int(input())): n = int(input()) characters = {} for strings in range(n): string = input() for i in string: characters[i] = characters.get(i, 0) + 1 status = True for value in characters.values(): if value % n != 0: status = False ...
# -- coding: utf-8 -- name = 'hoohoo' age = 35 height = 74 weight = 180 eyes = 'Blue' teeth = "White" hair = 'Brown' print "Let's talk about %s." % name print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %r eyes and %s hair." % (eyes, hai...
import unittest import main class TestMain(unittest.TestCase): def setUp(self): self.graph_dict = { "a": {"b": 30, "c": 10}, "b": {"d": 40}, "c": {"a": 50}, "d": {"c": 20} } self.graph_matrix = [ [0, 30, 10, 0], [0, 0,...
#Loop exercise 4 another way for rows in range(5): # print("*" * 5) star = "" for cols in range(5): star += "*" print(star)
# -*- coding: utf-8 -*- """ Created on Sun Mar 31 11:04:14 2019 Text classification & NLP using Multinominal Naive Bayes """ # Step 1 : Import libraries import nltk from nltk.stem.lancaster import LancasterStemmer # word stemmer stemmer = LancasterStemmer() # Step 2 : Provide training data # 3 classes of training dat...
from Exer_04 import Pessoa def main(): nome = input("Digite seu nome: ") idade = int(input("Digite sua idade: ")) peso = float(input("Digite seu peso: ")) altura = float(input("Digite seu altura: ")) continua = True pessoa = Pessoa(nome, idade, peso, altura) ...
from pynput import keyboard from pynput.keyboard import Key def on_press(key): if isinstance(key ,Key): if key == keyboard.Key.esc: # Stop listener and exit keyboard.Listener.stop return False elif Key.space == key: ...
li=[] i=0 for i in range(5): print "Enter the value" r=raw_input() li.append(r) print li
import os import sys import signal import itertools def print_titles(file, inc=3): """ Print titles in a file Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ count = 0 with open(file) as f: for line in f: if count == 0 or count % 3 ==...
import json class Player(): def __init__(self, first_name, last_name, height_cm, weight_kg): self.first_name = first_name self.last_name = last_name self.height_cm = height_cm self.weight_kg = weight_kg class BasketballPlayer(Player): def __init__(self, first_name, last_name, ...
import heapq from collections import Counter, defaultdict class Solution(object): def __init__(self, nums, k): self.nums = nums self.k = k def counter(self): """ Elements with equal counts are ordered in the order first encountered. """ return [x[0] for x in Co...
class Stack(object): def __init__(self): self.len = 0 self.stack = [] self.max = [] # latest value reflects current maximum def Push(self, value): # empty if not self.max: self.max.append(value) else: self.max.append(max(value, self.max[-...
class Node(object): def __init__(self, v, n=None): self.next = n self.value = v def __eq__(self, other): curr = self while curr.next: if not curr.value == other.value: return False curr = curr.next other = other.next re...
Name = input('What is your name?: ') Favoritefood = input('What is your favorite food?: ') Swimming = input('What is your favorite place to swim?: ') print() print(Name + ' is a small boy ') print('he likes to eat ' + Favoritefood) print ('and loves to swim at the', Swimming)
from numbers import Number from rfrac import RationalFrac class Monomial(dict): """ The product of a coefficient and several variables. Represented as a dictionary from strings, which are variable names, to integers, which are their degrees. """ coefficient: RationalFrac def __init__(sel...
import cv2 path="/home/shishir/study/code/openCV/resource/" def threshold_img(): img = cv2.imread(f"{path}/crossword.jpg",0) print(img.shape) cv2.imshow("raw", img) ## if the pixel in greater then threshold value, it is assigned one value ## else it is assigned another value.cv2.imshow("raw", img) #if s(x,y) ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Sumner Evans <sumner.evans98@gmail.com> # # Distributed under terms of the MIT license. import sys from matrix import Matrix def rowreduce(matrix, start_y = 0, start_x = 0): pivot_found = False for (i, row) in enumerate(matr...
#Write a program split.py, that takes an integer n and a filename as command line arguments and splits the file into multiple small files with each having n lines. import sys def split(filename): n=int(sys.argv[2]) new='file' f=open(sys.argv[1]).read() print f x=1 for lines in ran...
#make a sum function to work for a list of strings to concatinate. def sum (c): s='' for i in c: s = s+i return s c = sum(["hello","world"] ) print c
#write a funtionname lensort to sort a list of strings based on length. def lensort(names): sort =[] for i in range(0,len(names)): temp ="" for j in range(i+1,len(names)): if len(names[i])>len(names[j]): temp= names[j] names[j] = names[i] ...
#Write a program csv2xls.py that reads a csv file and exports it as Excel file. The prigram should take two arguments. The name of the csv file to read as first argument and the name of the Excel file to write as the second argument. import tablib import sys f = open(sys.argv[1]).readlines() data = tablib.Dataset() f...
#Write a function unflatten_dict to do reverse of flatten_dict. #unflatten_dict({'a': 1, 'b.x': 2, 'b.y': 3, 'c': 4}) #{'a': 1, 'b': {'x': 2, 'y': 3}, 'c': 4} def unflatten_dict(d): result = {} for k in d.keys(): if "." in k: parent,child = k.split('.',1) if parent in result.keys(): ...
# Write a function mutate to compute all words generated by a single mutation on a given word. A mutation is defined as inserting a character, deleting a character, replacing a character, or swapping 2 consecutive characters in a string. def mutate(word): a=[] z=word s=word v=word st =[] l= ['a','b','c',...
#The head and tail commands take a file as argument and prints its first and last 10 lines of the file respectively. import sys def head(filename): temp = open(filename).readlines() print temp[0:10] def tail(filename): temp = len(open(filename).readlines()) z= open(filename).readlines() print z...
""" This code is from http://www.youtube.com/watch?v=6n5vW3DhElw. Thank you for putting this online! """ import os, time seconds = 0 minutes = 0 hours = 0 while seconds <=60: os.system("cls") print hours, "Hours", minutes, "Minutes", seconds, "Seconds" time.sleep(1) seconds +=1 if s...
import pandas as pd from math import radians, cos, sin, asin, sqrt import numpy as np import random def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ # convert decimal degrees to radians lon1, lat1,...
import numpy as np import matplotlib.pyplot as plt def corner_squares(ax,n,p): if n>0: i1 = [1,2,3,0,1] ax.plot(p[:,0],p[:,1],color='k') q = -250 + p[i1]*.5 #coordinates for bottom left corner_squares(ax,n-1,q) q = 750 + p[i1]*.5 #coordinate for top right ...
def encrypt(key, msg): encryped = [] for i, c in enumerate(msg): key_c = ord(key[i % len(key)]) msg_c = ord(c) encryped.append(chr((msg_c + key_c) % 127)) return ''.join(encryped) def decrypt(key, encryped): msg = [] for i, c in enumerate(encryped): key_c = ord(key[...
n=input("Enter the value of 'n': ") num=float(n) s=((2*num+1)*num*(num+1))/6 sum=str(s) print("The total sum is "+sum)