text
stringlengths
37
1.41M
# SpiralMyName.py - prints a colorful spiral of the user's name import turtle # Set up turtle graphics t = turtle.Pen() turtle.bgcolor("black") colors = ["red", "yellow", "blue", "green",] # Ask the user's name using turtle's texttinput pop-up window your_name = "Boo" sides = 4 # Draw a spiral of the na...
#mylist = [20,30,40,50,1,100,90] #Approach1 : Sort the list in ascending order and print the first and last element in the list. mylist = [20,30,40,50,1,100,90] mylist.sort() #Sorting print(mylist) #[1, 20, 30, 40, 50, 90, 100] print("Smallest element is:",mylist[0]) print("Largest element is:",mylist[-1]) ...
#approach1 #Input : [5,10,15,20] #Output: 50 mylist=[5,10,15,20] total=0 for i in range(0,len(mylist)): total=total+mylist[i] #Index number print("Sum of all elements in given list:", total) #Approach2 mylist=[5,10,15,20] total=sum(mylist) print("Sum of all elements in given list:", total) ...
#Copy from previous lessons class Seq: """A class for representing sequences""" def __init__(self, strbases): # this method is called every time a new object is created self.strbases = strbases def len(self): return str(len(self.strbases)) def complement(self): seq =...
from collections import deque def search(lines, pattern, history=2): previous_lines = deque(maxlen=history) for line in lines: previous_lines.append(line) if pattern in line: yield line, previous_lines if __name__ == '__main__': lines = ['hello girl morining boy', ...
istenen = int(input("Pozitif bir tamsayı giriniz:")) x = 2 while x <= istenen : i = 2 while i*i <= x : if x%i == 0: break i += 1 else : print(x) x += 1
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> # 연간 투자의 미래 가치를 계산하는 프로그램 >>> def main(): payment = eval(input("Enter amount to invest each year: ")) apr = eval(input("Enter the annualize...
# 무조건 첫 문자 하나를 맨 뒤로 보내고 그 뒤에 'ay'를 붙이는 프로그램 a = 'happy'; b = 'pig'; c = 'python' new_a = a[1:] + a[0] + 'ay' new_b = b[1:] + b[0] + 'ay' new_c = c[1:] + c[0] + 'ay' string = '{} -> {}' print(string.format(a, new_a)) print(string.format(b, new_b)) print(string.format(c, new_c))
"""A number-guessing game.""" # Put your code here name = input("Howdy, what's is your name?") print(name) print(name,"I'm thinking of a number between 1 and 100.Try to guess my number.") import random num1 = random.randint(0,101) ct = 0 while True: try: num = int(input("Your guess?")) except V...
class Rectangle(object): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height def __eq__(self, other): return self.x == other.x and \ self.y == other.y and \ self.width == other.wi...
def number_entities(tree, start_e1, end_e1, start_e2, end_e2): ''' returns the node number of the entities ''' number_node_e1 = None number_node_e2 = None for i in range(1, len(tree.nodes)): node = tree.nodes[i] # it's not a bracket if 'start' in node: if ((s...
#user/python3 for num in range(100,1000) #依次取出num的值,第一次101,最后一次999 bai = num //100 shi = num //10 % 10 ge = num % 10 if(bai**3+shi**3+ge**3 ==num): print (num, end = ' ') #使输出的数不换行,以空格隔开同行输出
import collections def part1_is_nice_string(test_string): """ --- Day 5: Doesn't He Have Intern-Elves For This? --- Santa needs help figuring out which strings in his text file are naughty or nice. A nice string is one with all of the following properties: It contains at least three vow...
#!/usr/bin/env python import inout def area(corners, n): area = 0.0 for i in range(n): j = (i + 1) % n area += corners[i][0] * corners[j][1] area -= corners[j][0] * corners[i][1] area = abs(area) / 2.0 return area print("Corners must be ordered in Clockwise or Counter-Clockwise ...
import random questions_cnt = 10 max_trials = 3 questions_list = [] for i in range(questions_cnt): a = random.randint(1, 10) b = random.randint(1, 10) if (a,b) in questions_list: continue # avoid duplicate questions else: questions_list.append((a,b)) for j i...
#!/usr/bin/env python import random def bitonic_sort(up,x): if len(x)<=1: return x else: first = bitonic_sort(True,x[:len(x)/2]) second = bitonic_sort(False,x[len(x)/2:]) return bitonic_merge(up,first+second) def bitonic_merge(up,x): # assume input x is bitonic, and sor...
def palindromePermutation(word): dict={} for c in word: if (c!=" "): if (c not in dict): dict[c] = 1 else: x = dict[c] dict.update({c: x+1}) counter = 0 for x in dict: incorrect_chars = False if dict[x] == 1:...
""" Stack class. @author: Gautham Ganapathy @organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS) @contact: gautham@lisphacker.org """ from lems.base.base import LEMSBase from lems.base.errors import StackError class Stack(LEMSBase): """ Basic stack implementation. """ ...
#!/usr/bin/env python3 from array import * from math import * def parse_arguments(): ''' Parse the arguments. ''' import argparse parser=argparse.ArgumentParser() parser.add_argument("pqr",help="pqr file containing fpocket spheres defining pocket") args=parser.parse_args() return args...
from config import term_regex, num_regex import re def search_terms(prepare_line): return [(term[1], term[-1]) for term in term_regex.findall(prepare_line)[:-1]] def parse_term(term: str): coef = re.fullmatch(num_regex, term) if coef: return {'coef': float(coef.group())} degree = num_regex.s...
# Utilizando Módulos # Módulo matemático ''' import math # Importação que abrange TODO o módulo num = int(input('Digite um número: ')) raiz = math.sqrt(num) quadrado = math.pow(num,2) print('As operações realizadas com o número {} foram:'.format(num)) print('Raiz quadrada: {}'.format(raiz)) print('Raiz quadrada aproxim...
# Leia 3 numeros e informe o maior e o menor n1 = int(input('Informe um número: ')) n2 = int(input('Informe outro número: ')) n3 = int(input('Informe o último número: ')) nums = [n1, n2, n3] nums.sort() print('O maior número foi: {} e o menor: {}'.format(nums[-1], nums[0]))
# Leia um número informado e diga se é um ano bisexto ano = int(input('Informe um ano: ')) if ano % 4 == 0: print('{} é um ano bissexto'.format(ano)) else: print('{} não é um ano bissexto'.format(ano))
#! List of acceptable profanities which is mutable to make changes anytime dict_of_profanities={ 'low':('abc','pqr','xyz'), 'medium':('defg','hijk'), 'high':('qwerty','zxcvbn','asdfgh') } #! An Abstract Data Type to store the user comment during degree_check class Comment(): """ Comment is an ...
#!/usr/bin/env python3 VALID_2ND_POSITION_TOKENS = ('NAME', 'SEX', 'BIRT', 'DEAT', 'FAMC', 'FAMS', 'MARR', 'HUSB', 'WIFE', 'CHIL', 'DIV', 'DATE', 'HEAD', 'TRLR', 'NOTE') VALID_3RD_POSITION_TOKENS = ('INDI', 'FAM') def detect_tokens(line): # determines tokens in a GEDCOM file line ...
import sys import os import math import time # helper function to calculate the distance between city1 & city2 def getDistance(city1, city2): # tried this initially with pow - it works, but it's slower dist1 = (city1[0]-city2[0])**2 dist2 = (city1[1]-city2[1])**2 # dont use decimals return int(round(math.sqrt(di...
from numpy import * def sigmoid(x): """ The formula of sigmoid function :param x: The value of x to map to the sigmoid function :return: The value of f(x) on the sigmoid curve """ return 1 / (1 + exp(-x)) def sigmoid_derivative(x): """ The formula of the sigmoid gradi...
# Node object class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None # Tree object class BST(object): def __init__(self, root): self.root = Node(root) def insert(self, new_val): self.insert_helper(self.root, new_val) ...
# f(x) = 2x + 1 def f(x): return 2 * x + 1 print(f(10)) # p(x) = x^2 + 2x + 1 def p(y): return y ** 2 + 2 * y + 1 # 다른 표현 : y * y + 2 * y + 1 print(p(10)) # 실행결과 # 3150 def mul(*values): output = 1 for value in values: output *= value return output print(mul(5, 7, ...
# 실행결과 # 태어난 월을 입력해주세요 > 1 # 물병자리 입니다 str_input = input("태어난 월을 입력해 주세요>") birth_start_month = int(str_input) % 12 if birth_start_month == 3: print("양자리입니다") elif birth_start_month == 4: print("황소자리입니다") elif birth_start_month == 5: print("쌍둥이자리입니다") elif birth_start_month == 6: print(...
def even_nums(n): even = [] for x in n: if x % 2 == 0: even.append(x) return even print(even_nums([1, 2, 3, 4, 5, 6, 7, 8, 9]))
# "Stopwatch: The Game" import simplegui # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def init(): global stop_watch,counter_hits,counter_success,stop_watch_state stop_watch=0 counter_hits=0 counter_success=0 stop_watch_state=False def incr...
#Write a short Python function, minmax(data),that takes a sequence of #one or more numbers, and returns the smallest and largest numbers, #in the form of a tuple of length two, Do no use the built-in functions #min or max in implementing your solution. def minMax(data): print(data) Mi = data[0] Ma = data[...
''' Implement the __mul__ method for the Vector class of Section 2.3.3, so that the expression v*3 returns a new vector with coordinates that are 3 times the respective coordinates of v. ''' def __mul__(self,n): result = Vector(len(self)) for i in range(len(self)): result[i] = self.[i]*n return result
#Give an example of a Python code fragment that attempts to write #an element to a list based on an index that may be out of bounds. #If that index is out of bounds,the program should catch the #exception that results, and print the following erros message: #"Don't try buffer overflow attacks in Pyton!" a = [1,2,3,4,...
#In our implementation of the scale function(page 25),the body of the loop #executes the command data[j] *= factor. We have discussed that numeric #types are immutable, and that use of the *= operator in this context causes #the creation of a new instance (not the mutation of an existion instance). #how is it still pos...
#Write a short Python function that takes a string s, representing a #sentence, and return a copy of the string with all punctuation removed. s = input("please, input .a sentence ?") def removePun(s): for char in (",.?'/;:"): s = s.replace(char,"") return s print(removePun(s))
def is_multiple(n,m): x,y = divmod(n,m) if x >=1 and y ==0: print('n is %d time of m'%x) else: print('n is not multiple of m') n = int(input('please input first number')) m = int(input('please input second number')) is_multiple(n,m)
''' If the parameter to the make payment method of the CreditCard class were a negative number, that would have the effect of raising the balance on the account. Revise the implementation so that it raises a ValueError if a negative value is sent. ''' def make_payment(self,amount): if amount < 0: raise ValueError(...
import sqlite3 # Database: stationDB.sqlite # Table: stations # Columns: stn_number, letters_left NUM_STATIONS = 10 DEFAULT_REDEMPTIONS = 3 class StationDBHelper: def __init__(self, dbname="stationDB.sqlite"): self.dbname = dbname self.conn = sqlite3.connect(dbname, check_same_thread=False) ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 22:56:34 2020 @author: Marty """ from numpy import diff from collections import Counter data = open("Problem 10 Data.txt", "r").read() data = data[:-1].split('\n') numbers = [int(x) for x in data] # PART 1 numbers.sort() numbers.insert(0, 0) # the starting 0 jolts f...
""" Given two arrays A1[] and A2[] of size N and M respectively. The task is to sort A1 in such a way that the relative order among the elements will be same as those in A2. For the elements not present in A2, append them at last in sorted order. It is also given that the number of elements in A2[] are smaller than or ...
from factorial import factorial def combination(n, r): return int(factorial(n)/(factorial(r)*factorial(n-r))) def permutation(n, r): return int(factorial(n)/factorial(n-r)) def main(): nums= input("Enter n,r: ") n, r=int(nums.split(",")[0]),int(nums.split(",")[1]) print("Combination: "...
""" Programmer-friendly interface to the neural network. """ import json import numpy as np from decisiontree import DecisionTree from card import format_input class Bot(object): """ Object that wraps around the neural net, handling concepts such as "hand" and the list of previous plays. """ de...
"""Miscellaneous functions for dealing with cards.""" from random import randrange def format_input(card, prev_card): """ Format two cards in a manner that the decision tree can understand them. """ if prev_card[0] < card[0]: rank = 0 elif prev_card[0] == card[0]: rank = 1 else...
def mod(n1,n2): return n1*n2 def mod2(n1,n2,n3): return n1*n2*n3 print(mod2(10,11,12))
import sys import os from PIL import Image ''' taking two commandline arguments as source and target folder converting all jpg files in the source folder to png and save in the target folder ''' src_folder = sys.argv[1] tar_folder = sys.argv[2] # if target folder does not exist, create one if not os.path.isdir(tar_fol...
#!/usr/bin/env python3 ''' What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' from sys import argv class Factors: def __init__(self, num): self.set = set() self.counts = dict() self.update(num) def product(self): p = 1 ...
#!/usr/bin/env python3 # Find the sum of all the multiples of 3 or 5 below 1000. def do(): sum = 0 for i in range(1000): if (i % 3 == 0) or (i % 5 == 0): sum += i return sum if __name__ == '__main__': print(do())
#!/bin/python3 import os import sys # # Complete the runningMedian function below. # class LinkedList(object): def __init__(self, value, next_node = None): self.value = value self.next_node = next_node def add_node_to_linkedlist(node, value): head = node new_node = None if ...
''' Longest Substring Without Repeating Characters Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with ...
def insert(r,val): if r == None: root = Node(val) return root else: rec(r, val) return r #Enter you code here. def rec(r, val): if val < r.data: if r.left == None: node = Node(val) r.left = node else: rec(r.left, val) eli...
prime_numbers = [] is_prime = True for num in range(2, 2001): check_till = int(num/2) is_prime = True for x in range(2, check_till+1): if num%x == 0: is_prime = False if is_prime == True: prime_numbers.append(num) print ('Prime number between 1 to 2000 (including) are') pri...
""" Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.data (the value of the node)""" def insert(r,val): if r == None: return Node(val) p = r while p != None: if p.data < val: if p.right == None: p.right = Nod...
def runProgram(fileList): printFiles(fileList) fileName = takeInput(fileList) dic = getDicFromFile(fileName) count = askNumber(len(dic)) worngWordDic = quizzed(dic, count) print(''' Do you want to export wrong word to txt file? 1. yes 2. no ''') question = int(input()) if(question == 1): name = input("ple...
def intToRoman(s): roman = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M'] no_list = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000] no_list.reverse() roman.reverse() number = '' i = 0; while s > 0: while s >= no_list[i]: s -= no_list[i] ...
## The sum of the squares of the first ten natural numbers is, # 1^2 + 2^2 + ... + 10^2 = 385 # # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)^2 = 55^2 = 3025 # # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is 3025 −...
#Prints out odd or even numbers x = str(input("odd/even = ")) if x == 'even': for i in range(2,11,2): print(i) elif x == "odd": for i in range(1,11,2): print(i)
parrot = "Norwegian Blue" print(parrot) print(parrot[3]) print(parrot[4]) print(parrot[9]) print(parrot[3]) print(parrot[6]) print(parrot[8]) print() print(parrot[-1]) print(parrot[-14]) print() print(parrot[3 - 14]) print(parrot[4 - 14]) print(parrot[9 - 14]) print(parrot[3 - 14]) print(parrot[6 - 14]) print(par...
""" The alignment is to right; For the first item it'll take 2 places, for the second item it'll take 3 places and for the third - last one, it'll tale four places. """ for i in range(1, 13): print("No. {0:2} squared is {1:3} and cubed is {2:4}".format(i, i ** 2, i ** 3)) print() """ Due to '<' sign, the alignme...
def transfer2string(list): str_list = "" for i in range(len(list)): if list[i] == list[-1]: str_list += "and " + list[i] else: str_list += list[i] + ", " return str_list spam = ['apples', 'bananas', 'tofu', 'cats'] str_spam = transfer2string(spam) print(str_spam)
stanje = 0 while stanje > (-100): sprememba = int(input("Sprememba ")) stanje += sprememba print("Stanje ", stanje) print("Bankrot")
""" from random import * from math import * r = 1 i = 1 n = 0 st_koordinatov = 1000 while i <= st_koordinatov: x = 2 * random() - 1 y = 2 * random() - 1 if sqrt(x**2 + y**2) < r: n += 1 i += 1 pi_rac = 4 * n / st_koordinatov print("PI:", pi_rac) """ from random import * from math import *...
from math import * a = float(input("Kateta?")) b = float(input("Kateta?")) c = sqrt((a**2) + (b**2)) print("Hipotenuza: ",c)
vsota = 0 i = 1 while i <= 5: cena = int(input("Cena artikla: ")) vsota += cena i += 1 print("Vsota: ",vsota)
# Determinar si un número entero proporcionado por el usuario es primo. m= int(2); band = "V"; numero = int(input("Ingrese el numero: ")); while((band == "V") and (m < numero)): if((numero % m) == 0): band = "F"; else: m = m + 1; if(band == "V"): print("El numero leido es pr...
# Diseñar un algoritmo tal que dados como datos dos variables de tipo entero, obtenga el resultado de la siguiente función: num= int(input("Ingrese numero: ")) V= int(input("Ingrese valor: ")) if num == 1: resp=100*V elif num == 2: resp=100**V elif num == 3: resp=100/V else: resp=0 print("...
class CircularPrime(object): def __init__(self): super(CircularPrime, self).__init__() def is_prime(self, number): if number == 2: return True if (number < 2) or not (number % 2): return False for i in range(3, int(number**0.5) + 1, 2): if (...
"""Defines the encryption protocol.""" import random import string import numpy as np from typing import List from collections import deque from content.helper.constant import Key from content.encrypt_item.cube import Cube class Encryption: """Perform encryption and decryption of the input.""" def __init__(...
import binascii from Cryptodome.Cipher import AES KEY = 'This is a key123' IV = 'This is an IV456' MODE = AES.MODE_CFB BLOCK_SIZE = 16 SEGMENT_SIZE = 128 def encrypt(key, iv, plaintext): aes = AES.new(key, MODE, iv)#, segment_size=SEGMENT_SIZE) plaintext = _pad_string(plaintext) encrypted_text = aes.encry...
import math def gap(g, m, n): prime = 2 for i in range(m, n+1): is_prime = True for j in range(2,int(math.sqrt(n))+1): if i % j == 0: is_prime = False break if is_prime: if i - prime == g: return [prime, i] ...
# def compress(string): # finalString = "" # if string == "": # return "\"\"" # if len(string) == 1: # return finalString + 1 # count = 1 # i = 1 # for letter in string: # if letter == string[i - 1]: # # finalString = finalString + letter + str(count + 1)...
# Declaring a Node class and forming a singly linked list class Node(object): def __init__(self, value): self.value = value self.next = None def cycle_checker(self): next = self.next while next is not None: if self.value == next.value: return True ...
class Stack(object): """ Implementing my own stack reference: https://digitalu.udemy.com/course/python-for-data-structures-algorithms-and-interviews/learn/lecture/3179606#overview """ def __init__(self): self.items = [] def isEmpty(self): return self.items == [] ...
''' TAREA3 Examina cómo las diferencias en los tiempos de ejecución de los diferentes ordenamientos cambian cuando se varía el número de núcleos asignados al cluster, utilizando como datos de entrada un vector que contiene primos grandes, descargados de https://primes.utm.edu/lists/small/mil...
def check_matches(fn ="test.csv"): import pandas as pd vsc = {} df = pd.read_csv(fn) for row in df.iterrows(): r = row[1] for row1 in df.iterrows(): r1 = row1[1] if r.Week == r1.Week and (r.Match1 == r1.Match1 or r.Match2 == r1.Match2 or r.Match3 == r1.Match3...
import collections class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def height(self, root, cached): max_height = 1 if len(root.children) > 0: for child in root.children: if child...
def find_pivot(arr): i, j, pivot_idx = -1, 0, len(arr)-1 while j < len(arr)-1: if i >= 0 and arr[j] <= arr[pivot_idx]: temp = arr[i] arr[i] = arr[j] arr[j] = temp i += 1 else: if i == -1 and arr[j] > arr[pivot_idx]: ...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def largestValues(self, root): queue, largest = [(root, 0)], [] last_depth = 0 running = [] while len(queue) > 0: node, de...
import heapq class Solution(object): def merge(self, enc, u): i = 0 while 0 <= i < len(enc): x, y = enc[i] if y >= 3: u -= y if i-1 >= 0 and i+1 < len(enc) and enc[i-1][0] == enc[i+1][0]: enc = enc[:i-1] + [(enc[i-1][0], en...
class Solution: def custom_merge(self, nums1, nums2): i, j = 0, 0 out = [] while i < len(nums1) and j < len(nums2): if int(str(nums1[i]) + str(nums2[j])) > int(str(nums2[j]) + str(nums1[i])): out.append(nums1[i]) i += 1 else: ...
numeros = [0,1,2,3,4,5,6,7,8,9] soma = 0 for i in numeros: soma = soma + numeros[i] print(soma)
# Descripcion: Programa que permite a un usuario jugar a Piedra, papel o tijera con un jugador virtual PC # Entrada: Seleccion entre piedra, papel o tijera hecha por el usuario # Salida: Felicitaciones al usuario ganador # Autor: EALCALA # Fecha: 03.05.2017 # Version: 1.0 #Plataforma: Python v2.7 import sys w = in...
# Descripcion: Programa que genera una contrasena fuerte o debil segun desea el usuario # Entrada: Solicitud de contrasena fuerte o debil # Salida: Contrasena aleatoriamente generada # Autor: EALCALA # Fecha: 17.05.2017 # Version: 3.0 #Plataforma: Python v2.7 def nivel(): return raw_input("Introduzca ...
# Descripcion: Programa que juega con un usuario vacas y toros # Entrada: Eleccion para adivinar de un numero de 4 digitos # Salida: Numero de Vacas y Toros hasta acertar # Autor: EALCALA # Fecha: 19.05.2017 # Version: 1.0 #Plataforma: Python v2.7 def vacas_toros(): from random import randint v...
#!/usr/bin/env python3 import sys import csv import os def process_csv(csv_file): """Turn the contents of the CSV file into a list of lists""" print("Processing {}".format(csv_file)) with open(csv_file,"r") as datafile: data = list(csv.reader(datafile)) return data def data_to_html(title, data...
# creating a file 'GoldenThoughts.txt' in the same location like *.py file is //'w' FileWithParagraphs=open('GoldenThoughts.txt','w') # I save both paragraphs of the text into the created file FileWithParagraphs.write('What if I said that randomness, coincidence, chance, karma, miracle—all such notions do not exis...
from cs50 import * import sys def main(): if len(sys.argv) != 2: print("You must use exactly 1 command argument!\n") return key = int(sys.argv[1]) plain_text = get_string() for char in plain_text: if char.isalpha(): if char.isupper(): ...
def triangle(n): k = 2*n-2 for i in range(0,n): for j in range(0,k): k = k-1 for j in range(0,i+1): print("*",end="") print("\n") n = 5
n=10 for i in range(n): print(" "*(n-i-1)+'* '*(i+1)) for j in range(n-1,0,-1): print(' '*(n-j)+'* '*(j))
def my_fun(): global a a = 10 print(a) a = 20 my_fun() print(a) def my_fun(argv): # argv = k argv.append(2) k = [7,8] my_fun(k) print(k) def my_fun(): def inner(): k = 78 def inner_non(): nonlocal k k = 60 def inner_global(): global k k = 90 k ...
str = input() sub = input() c = 0 for i in range(0,len(str)-len(sub)+1): if sub == str[0:3]: c = c+1 print(c)
class User: def __init__(self, first_name, last_name, age, height, weight, login_attempts=0): self.first_name = first_name self.last_name = last_name self.age = age self.height = height self.weight = weight self.login_attempts = login_attempts def increment_login...
import math from ZeroTwoPi import ZeroTwoPi as ZeroTwoPi def CartToSph(cn,ce,cd): ''' CartToSph converts from Cartesian to spherical coordinates CartToSph(cn,ce,cd) returns the trend (trd) and plunge (plg) of a line for input north (cn), east (ce), and down (cd) direction cosines NOTE: Trend and plu...
import math def SphToCart(trd,plg,k): ''' SphToCart converts from spherical to Cartesian coordinates SphToCart(trd,plg,k) returns the north (cn), east (ce), and down (cd) direction cosines of a line. k: integer to tell whether the trend and plunge of a line (k = 0) or strike and dip of a plane in right hand r...
import numpy as np def OutcropTrace(strike,dip,p1,XG,YG,ZG): ''' OutcropTrace estimates the outcrop trace of a plane, given the strike (strike) and dip (dip) of the plane, the ENU coordinates of a point (p1) where the plane outcrops, and a DEM of the terrain as a regular grid of points with E (XG), N (YG) and U ...
from constants import BASIC_TAX_EXEMPT from sales_tax import CalculateTax # Added items in cart represented in list format order_one = [ '1 book at 12.49', '1 music CD at 14.99', '1 chocolate bar at 0.85' ] order_two = [ '1 imported box of chocolates at 10.00', '1 imported bottle of perfume at 47...
#!/usr/bin/env python # -*- coding: utf-8 -*- # função que verifica se o programa está infectado def infected(path, pathInfected): # score conta as chamadas diferentes # total conta o número de chamadas do arquivo score, total = 0, 0 # abre o arquivo sadio para leitura file = open(path, "r") ...
#finding the fibonacci series using recursive method. #defining the function. def fibonacci(n): #if the given input is less than or equal to 1 then return the following. if n <= 1: return n #if the given input is greater than 1 then return the following. else: return (fibonacci(n-1) + fi...
class Clock(object): def __init__(self, hour, minute): extra_hours, minute = self.__calculate_minute(minute) hour = self.__calculate_hour(extra_hours, hour) self.hour = hour self.minute = minute def __calculate_minute(self, minute): result = (0, 0) if minute >=...