text
stringlengths
37
1.41M
def get_new_path (path, where): if not where: return path if where[0] == '.': where = where[1:] if not where: return path where = where[1:] return get_new_path (path, where) if where[0] == '..': where = where [1:] if not pat...
class Card(object): """ This class represents a standard card in a deck Each card consists of two attributes: value and suit There are 4 unique suits and 13 values """ def __init__(self, raw_card, value = None, suit = None): self.raw_card = raw_card self.value = self.get_value() self.suit = suit def get_...
from Tkinter import * def interface(account): window = Tk() window.geometry('450x220') window.title('Money Manager') app = App(window, account) window.mainloop() """ while on: refreshWindow() answer = raw_input("What would you like to do?\nAdd Transaction\nDeposit\nCheck Balance\nQuit\n\n") if (answe...
hislist = ["apple", "banana", "cherry"] for x in hislist: print( x ); if "apple" in hislist: hislist.append("nova fruta") print( "Yes sim en lista" ); #Print the number of items in the list: print( len(hislist) ) #Using the append() method to append an item: hislist.append("nova fruta"); #Insert an it...
import numpy as np # Matrix Operation Example W = np.array([[1, 2, 3], [4, 5, 6]]) X = np.array([[0, 1, 2], [3, 4, 5]]) print(W + X) print(W * X) # Broadcast Example A = np.array([[1, 2], [3, 4]]) b = np.array([10, 20]) print(A * b) # Vector Inner Product a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) print(np.dot...
# 듣보잡 (https://www.acmicpc.net/problem/1764) import sys n,m = map(int, input().split()) #한줄에 입력값 받는 법 n_list = set([sys.stdin.readline().strip() for i in range(n)]) m_list =set([sys.stdin.readline().strip() for i in range(m)]) res = sorted(list(n_list&m_list)) print(len(res)) for i in res: print(i)
a = int(input("Enter a number :")) b = int(input("Enter second number :")) print("Which operation you would like to do....") print("press 0 for addition") print("press 1 for subtraction") print("press 2 for multiplication") print("press 3 for divison") x = int(input("Give the digit :")) if(x==0): sum = a+b ...
class Attribute: def __init__(self, attributeType, attributeName, lineStart): self.lineStart = lineStart self.attributeType = attributeType self.attributeName = attributeName def print(self): return "----------------------------------------------------------\n" + \ ...
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("output.csv") y = df[:9] y["x"] = y.index y_ = df[8:] y_["x"] = y_.index print(y) print(y_) plt.plot(y["x"], y["target"], "r-") plt.plot(y_["x"], y_["target"], color="blue") plt.show()
""" PyBank HW Checklist: 1. Import CSV File (budget_data.csv) 1a. Open and Read CSV File 2. Print (Financial Analysis) 3. Print (----------------------------) 4. Calculate: The total number of months included in the dataset 4a. Print (Total Months: 86) 5. Calculate: The total net amount of "Profit/Losses" over the enti...
s = str(raw_input()) if s.isupper(): print s.lower() exit (0)
s1 = list(str(raw_input()).lower()) s2 = list(str(raw_input()).lower()) if s1 == s2 : print '0' elif s2 > s1: print '-1' elif s1 > s2: print '1'
def format_input(): meal = [] recipe = raw_input("Recipe name: ") recipe_mats = raw_input("Ingredients, separated by commas: ") recipe = recipe.replace(' ','_') meal.append(recipe+' =') meal.append(recipe_mats.split(', ')) return meal # append string (imitating list) to ingredients...
# Binary Tree implementation using List # Create Traverse Search Insert Delete # Binary tree has always at most 2 children # Creating is O(n), rest is O(1) # Linked list Insert is O(n) but also spcae complexity is O(n) class BinaryTree: def __init__(self, size): self.customList = size * [None] self...
import math from array import array print("hello"); print('mosh hamedani is my best youtube instructor') name = "Muwonge lawrence the programmer" age = 20 print('*' * 10) print(f'my name is {name} and my age is {age} so you are welcome to python programming.') print('*' * 10) print("3 squared is " + str(3 ** 2)) prin...
entradaTeclado = int(input("Entre com um valor \n")) for num in range(entradaTeclado + 1): #conta de zero a cem divisao = 0 for cont in range(1, num + 1): #contador aninhado restoDivisao = num % cont #resto if restoDivisao == 0: divisao += 1 if divisao == 2: ...
#Exercicios bimestre notaAprovado = 50 notaReprovado = 49 mensagemAprovado = "Parabéns voçê foi aprovado!!!" mensagemReprovado = "Voçê não foi aprovado, se dedique um pouco mais ano que vem!!!!" nomeAluno = str(input("Nome do Aluno ? \n")) #Nota do primeiro bimestre nota1 = float(input("Lançe a nota do 1º Bimestre \...
class Matrix: def mul(x,y): #self? if(len(x[0]) != len(y)): print('ValueError') else: result = [] for i in range(len(x)): temp = [] for j in range(len(y[0])) : temp2 = 0 for k in range(len(y))...
import sys def is_palindrome(s): num_s = len(s) for i in range(num_s / 2): if s[i] != s[num_s - 1 - i]: print "FAIL" sys.exit() print "PASS" if __name__ == "__main__": s_1 = ["a", "b", "c", "b", "a"] s_2 = ["a", "b", "c", "a", "b"] is_palindrome(s_1) is_pali...
# method 1 def shift_first_char(s): num = len(s) temp = s[0] for i in range(num - 1): s[i] = s[i + 1] s[num - 1] = temp def shift_char(s, n): for i in range(n): shift_first_char(s) print s # method 2 def shift_char_2(s, n): num = len(s) temp = [] for i in range(n): ...
for n in range(1, 101): output = "" if n % 3 == 0: output = output + "Fizz" if n % 5 == 0: output = output + "Buzz" if output == "": output = n print output
import farkle import position from itertools import chain, combinations import random from time import sleep class RandomPolicy: def __init__(self, name, verbose=False): self.name = name self.verbose = verbose def get_name(self): return self.name def start_turn(self, game, pos...
class Dequeue: DEFAULT_CAPACITY = 10 def __init__(self): self.data = [None] * Dequeue.DEFAULT_CAPACITY self.size = 0 self.front = 0 def __len__(self): return self.size def is_empty(self): return (self.size == 0) def first(self): if self.is_empty():...
def split_parity(lst): switch1 = 0 switch2 = 0 for i in lst: #O(n) if i % 2 == 1: #if odd... lst[switch1], lst[switch2] = lst[switch2], lst[switch1] switch1 = switch1 + 1 switch2 = switch2 + 1 if i % 2 == 0: #if even switch2 = switch2 + 1 r...
class EmptyTree(Exception): pass class LinkedBinaryTree: class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.left = left if (self.left is not None): self.left.parent = self self....
# Question 5 # # PERMUTATIONS FUNCTION IS LOCATED BELOW IN FILE! # class Empty(Exception): pass class ArrayStack: def __init__(self): self.data = [] def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, val): self.data.app...
def findchange(lst): highIndex = len(lst) - 1 lowIndex = 0 divideIndex = int((highIndex + lowIndex)/2) control = True # if(len(lst) == 2): # if(lst[1] == 1): # return 1 # else: # return "improper input, there needs to be 0s and 1s" # if(len(lst) == 1): ...
from cryptography.fernet import Fernet # Get existing Fernet key def get_fernet_key(): print("Enter Key:") key_str = input() key_bytes = key_str.encode() return Fernet(key_bytes) # Enter the encoded capture def get_encoded_capture(): print("\nEnter Capture:") capture_str = input() return c...
#!/usr/bin/env python # ----------------------------------- # remove files in each subfolder in the given path starting from the given indices # Author: Tao Chen # Date: 2016.10.16 # ----------------------------------- import os import sys import numbers import re def rm_riles(path, index): if not os.path.exists(p...
# 4. Days Calculator from datetime import datetime print("Date format dd/mm/yy") date1 = input("enter 1st date:") date2 = input("enter 2nd date:") date_format = "%d/%m/%Y" a = datetime.strptime(date1, date_format) b = datetime.strptime(date2, date_format) delta = b - a x = (delta.days) print("There are...
# 10. Calculate Interest amount = int(input("Please enter principal amount:")) rate = float(input("Please Enter Rate of interest in %:")) years = int(input("Enter number of years for investment:")) cal = (amount*(1+rate/100)**years) print("After", years, "years your principal amount", amount, "over...
# 9. Triangle area base = float(input("ENTER BASE:")) height = float(input("ENTER HEIGHT:")) area = 1/2*(base*height) print("Area of a Triangle with Height", height, "and Base", base, "is", area )
''' Text Based Seek Steering Behavior ''' import math import time from datetime import timedelta print("Implementing Seek Steering Behaviors...") print("\n") #The Player Class class player: def __init__(self, x, y): self.x = float(x) self.y = float(y) def current_position(self): ...
import os import csv #creating path to collect data from the my PyBank Folder budget_data = os.path.join('budget_file.csv') #delcare variables that will be used throughout program total_months = 0 #int value to hold number of months total_profit = 0 #int value to hold value of profit value = 0 #int variable that will...
import numpy as np import math import matplotlib.pyplot as plt import matplotlib as mpl def neuronio(x, weights): activation = weights[-1] for i in range(len(weights)-1): activation += weights[i] * x[i+2] return activation def training_weights(train): error=0.0 sum_error =1 epoch=1 while(sum_erro...
#GUI扩展 from tkinter import * from tkinter import ttk def get_value(key,kw): if key in kw.keys(): return kw[key] else: return None #label控件,宽高单位:像素 class Label_PX(): def __init__(self,root,**kw): self.width = get_value("width",kw) self.height = get_value("height",kw) ...
import string ALPHABET = string.ascii_uppercase def generate_key(message: str, keyword: str) -> str: key = keyword remain_length = len(message) - len(keyword) for i in range(remain_length): key += key[i] return key def encrypt(message: str, key: str) -> str: result = '' for i, char in enumerate(message): ...
# 1 def func(number): return number[0] # log n def func2(n): if n <= 1: return else: print(n) func2(n/2) # 0 def func3(numbers): for num in numbers: print(num) # n * log(n) def func4(n): for i in range(int(n)): print(i, end=' ') ...
import math from random import random, gauss class Attribute: def __init__(self, value, max_value, min_value, mutate_rate=.1, mutate_power=.1, replace_rate=.01): self.value = value self.initial_value = value self.max_value = max_value self.min_value = min_value self.mutate...
# In the following exercise you will finish writing smallest_positive which is a function that finds the smallest positive number in a list. def smallest_positive(in_list): x = None for item in in_list: if item <= 0: continue if x == None or item < x: x = i...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sam Quinn # 11-14-2016 import math def main(): x = 2000000 primes = [] for i in range(0,x): primes.append(i) primes[1] = 0 for i in range(2,int(math.sqrt(x))): if primes[i] != 0: j = i + i while(j < x): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sam Quinn # 1-29-2017 tri = [] rem = {} def main(): make_tri() #for i in tri: print i tot_sum = best(0,0) print "The best possible path is %s " % tot_sum def best(y,x): global tri global rem # If we have computed this value before return ...
from classes import AddressBook def main(): address_book = AddressBook('address_book.csv') print("Address book initialized. Source is:".format(address_book.fp)) while True: command = input("What you want to do? ADD, SHOW, FIND, EXIT") """ Validate input to check that input...
''' Created on 2016/11/7 kNN: k Nearest Neighbors Input: inX: vector to compare to existing dataset (1xN) dataSet: size m data set of known vectors (NxM) labels: data set labels (1xM vector) k: number of neighbors to use for comparison (should be an odd number) Out...
from bs4 import BeautifulSoup html = """ <html> <head> <title>BeautifulSoup Example</title> </head> <body> <h1>H1 Tag</h1> <h2>H2 Tag</h2> <p class="A">First P Tag</p> <p class="B">Second P Tag</p> <p id="C"> Third P Tag <p class = "D">Multiple P ...
import random def play(): user = input("\n:::::::::::::::::::::::::\nLet's play a game! \nChoose your weapon: enter 'rock', 'paper', 'scissors' or 'well': ").lower() computer = random.choice(['rock', 'paper', 'scissors', 'well']) print('\n:::::::::::::::::::::::::\nThe computer randomly entered "{}".\n\n⚡⚡...
__author__ = 'williamsb' def is_palindrome(number): string = str(number) start = 0 end = len(string) - 1 while string[start] == string[end] and start < end: start += 1 end -= 1 return start > end max_palindrome = 1 for i in range(0, 999): for j in range(0, 999): ...
import time import datetime as dt #-----CALCULATOR-------# #Calculo de minutos entre dos horas formato HH:MM. def dif_min_proy(time_1,time_2): start_dt = dt.datetime.strptime(time_2, '%H:%M') end_dt = dt.datetime.strptime(time_1, '%H:%M') diff = (start_dt - end_dt) minutos= int(diff.seconds/60) pr...
#FUNCION MODIFICACION ULTIMO PACIENTE INGRESADO def mod_last_dat(lista2,lista): if (lista2 == []): print("No hay pacientes para modificar") else: opc=0 while opc != "s": print("Ingrese una opcion valida") menuPrincipal = menu_mod() opc = opciones() ...
import sqlite3 class ViewContacts(): """ This class displays all saved members in the treeview and First of all, in order for the members to be displayed regularly, we have to delete them all at once """ def view_command(self): self.tree.delete(*self.tree.get_children()) conn = ...
""" file: trainMLP.py language: python3 author: rss1103@rit.edu Rohan Shiroor sm2290@rit.edu Sandhya Murali This program trains a multi-layer perceptron on training data provided by the user. """ import matplotlib.pyplot import csv import math import random def readFile(file): ''' Read...
# реализовать функцию my_func(), которая принимает три позиционных аргумента # и возвращает сумму наибольших двух аргументов def chek_num(user_string): """ проверка на ввод чисел(+целые +дробные +отрицательные) """ while True: user_chek = input(user_string) if user_chek.isdigit(): ...
# -*- coding: utf-8 -*- """ This script can be run on any Python intepreter to generate the answers to Q3 in HW2 of ENME 572 Walther Wennholz Johnson - walther.johnson@ucalgary.ca """ ## Imports import numpy as np import matplotlib.pyplot as plt ## Given Variables a = [1,10] # convective velocities k = 1 # thermal dif...
#!/bin/python3 import math import os import random import re import sys from collections import defaultdict # Complete the makingAnagrams function below. def makingAnagrams(s1, s2): d = defaultdict(int) for i in s1: d[i] += 1 #print(d[i]) for i in s2: d[i] -= 1 count = 0 f...
def mergesort(arr): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] mergesort(L) mergesort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: ...
def Knapsack(price, weights, cap): n = len(price) r = [[0 for _ in range(cap + 1)] for _ in range(n + 1)] # Build table r[][] in bottom up manner for i in range(n + 1): for j in range(cap + 1): if i == 0 or j == 0: r[i][j] = 0 elif weights[i - 1] <=...
import builtins INP = object() # object to recognize inputs class t(str): def __add__(self, other: object): if isinstance(other, str) or other is INP: return ColorChain([self, other]) elif isinstance(other, ColorChain): return ColorChain([self, *other]) else: ...
import math import copy import random from Program.ball import Ball from Program.helpers.constants import Constants from Program.space import Space ''' - - - | 0 | 1 | 2 | 3 | 4 | 5 | 6 | - - - | 7 | 8 | 9 | 10 | 11 | 12 | 13 | - - - | 14 | 15 | 16 | 17 | 18 | 19 | 20 | - - - | 21 | 2...
from typing import List from testcase import testcase class Solution: def numUniqueEmails(self, emails: List[str]) -> int: uniq = set() for email in emails: uniq.add(self.process(email)) return len(uniq) def process(self, email: str) -> str: localname, domain = em...
from testcase import testcase class Solution: def reverseBits(self, n: int) -> int: as_bin = bin(n)[2:] as_bin = "0" * (32 - len(as_bin)) + as_bin return int(as_bin[::-1], 2) def test(): s = Solution() for t, expected in testcase: assert s.reverseBits(t) == expected if ...
from itertools import combinations from typing import List from testcase import testcase class Solution: def totalHammingDistance(self, nums: List[int]) -> int: if not nums: return 0 bins = [str(bin(n))[:1:-1] for n in nums] longest = max(bins, key=len) longest_len = l...
from testcase import testcase class Solution: def isPowerOfFour(self, num: int) -> bool: if num == 1: return True num /= 4 if num < 1: return False return self.isPowerOfFour(num) def test(): s = Solution() for t, expected in testcase: asser...
from operator import mul from functools import reduce from testcase import testcase class Solution: def subtractProductAndSum(self, n: int) -> int: sequence = [int(s) for s in str(n)] return self.product(sequence) - self.sum(sequence) def product(self, s) -> int: return reduce(mul, s)...
#!/usr/bin/env python3 """ Decoders for binary representations. """ from toolz.itertoolz import pluck import numpy as np from .. decoder import Decoder ############################## # Class BinaryToIntDecoder ############################## class BinaryToIntDecoder(Decoder): """A decoder that converts a Bool...
import pygame from pygame.sprite import Sprite class Asteroid(Sprite): """space rock!""" def __init__(self, ai_settings, screen): super(Asteroid, self).__init__() self.ai_settings = ai_settings self.screen = screen self.speed_factor = self.ai_settings.asteroid_speed_factor ...
from math import sqrt from numpy import dot, argmax, zeros import numpy as np from random import sample import random def fast_norm(x): """ Returns norm-2 of a 1-D numpy array. """ return sqrt(dot(x, x.T)) def compet(x): """ Returns a 1-D numpy array with the same size as x, where the element having the...
from tkinter import * root = Tk() root.geometry("300x200") root.title('Code Core') root.configure(background='light gray') def chang_txt(): l1.config(text=e1.get()) l1=Label(root, text = " Hello World!",fg = "light green",bg = "darkgreen",font = "tahoma 16") l1.grid(row=0,column=0) #l1.place(x=10,y=10) Label(ro...
from stone import stone from scissors import scissors from palm import palm import random def judgment(a): if a == "stone": stone() elif a == "scissors": scissors() else: palm() number = 0 while True: if number > 0: c = input("Do you want to continue the game? Please en...
''' a='soft' b='warica' print(f' {b[-1::-1]}{a[-1::-1]} is my college') name='shoobham gadeula' print(name[-5:0:-1]) ''' ''' number=int(input("enter number ")) if number % 2 == 0: print('number is even') else: print("number is odd") '''
import random secretNumber = random.randint(1,20) global numberOfGuesses numberOfGuesses = 0 def game(secretNumber): print("Am thinking of a number between 1 and 20.") print("Take a guess.") guessLimit = 6 #global numberOfGuesses while numberOfGuesses <= guessLimit: yourNumb...
import numpy as np import pandas as pd #### creating dataframes, adding and dropping columns df = pd.DataFrame(np.arange(1,10).reshape(3,3),['A','B','C'],['w','x','y']) df.columns = ['W','X','Y'] # change column names df['Z']=df['X']+df['Y'] # new column with values X+Y df['XX']=df.apply(lambda row: row['X']*2, axis=...
# 12create script that converts ranges into list of item multiplied by 10 import string from collections import OrderedDict r = range(1, 10) ls = [10 * item for item in r] # print(ls) # 13 convert range into strings ls_string = map(str, ls) for item in ls_string: # print(item) # remove duplicates from list...
#who will pay the bill import random def randomChoice(min,max): return random.randint(min,max) def whoWillPay(): names=input("Enter Names separated by comma") namesList = names.split(',') numberOfPayer = len(namesList) randomName = randomChoice(0,numberOfPayer-1) print(randomName) paidBy = ...
age=10 if age<18: print("fuck u") elif age<25: print('fuck others') elif age<30: print('fucked by wife') else: print('fucked all th life') #switch #ternary
from functools import partial import colors as c print(c.color('my string', fg='blue')) print(c.color('some text', fg='red', bg='yellow', style='underline')) print() for i in range(256): if i % 8 != 7: print(c.color('Color #{0}'.format(i).ljust(10), fg=i), end='|') else: print(c.color('Color #...
for num in range(1, 101): if num % 15 is 0: print("buzzfizz") elif num % 3 is 0: print("kizz") elif num % 5 is 0: print("juzz") else: print(num)
""" Random Name Generator """ from collections import deque import random import importlib import warnings def fetch_words(list_name): """ Returns a tuple of words from the word libraries contained here. """ mod = importlib.import_module( '.lists.%s' % list_name, package='randomname') retu...
# ATP RACIOCÍNIO COMPUTACIONAL # Importa biblioteca datetime (data e hora) from datetime import datetime # VARIÁVEIS GLOBAIS - há outras dentro das funções meuNome = 'Isabela Milene Paniagua Zanardi' # Função OBTER LIMITE - Etapas 1 e 2 def obter_limite(): print('Bem-vindo à Loja da', meuNome) c...
# Christopher Lamy print('Hello. What language would you like to learn how to say "Hello" in?')# Question #Options print('A: Creole.') print('B: Swahili.') print('C: Swedish ') #Input option = input() #Choice of language user would like to learn. if option == 'A': print('Alo') elif option == 'B': print('Huj...
# test_TSH_Test_Diagnostics.py def test_TSH_diagnosis_normal(): '''Unit test for a list of normal TSH values This function is a unit test that receives a string of TSH values and tests whether the TSH_diagnosis code correctly orders the test results from low to high and outputs the correct diagnosis....
#https://brilliant.org/wiki/sorting-algorithms/#sorting-algorithms #basically just trying to get in some coding practice in my free time import random def mergeSort(x): if len(x) < 2: return x results = [] mid = len(x) // 2 y = mergeSort(x[:mid]) z = mergeSort(x[mid:]) while (len(y) >...
#ASSIGNMENT OPERATORS no1=10 no1+=2 print(no1) no1-=2 print(no1)
word={} data=input("Enter String ") dat=list(data) for i in dat: if(i not in word): word.update({i:1}) else: print("First Repeating Letter: ",i) break print(word)
#7 VOWELS def countvow(str): set1=set() count=0 set2={'a','e','i','o','u','A','E','I','O','U'} for i in str: if(i in set2): count+=1 set1.add(i) else: pass if(count!=0): print("No of vowels=",count) else: print("No Vowels Exist"...
top=-1 stack=[] size=int(input("Enter Size of Stack: ")) def push(): global stack global size global top element=int(input("Enter Element To Push: ")) if(top<size): top+=1 stack.insert(top,element) elif(top==size): print("Stack Full") def pop(): global stack globa...
#Input marks and print Grade of Student math=int(input("Enter Marks in maths ")) sc=int(input("Enter Marks in Science ")) comp=int(input("Enter Marks in Computer Science ")) sum=math+sc+comp if(sum>140): print("Grade A+") elif(sum>130&sum<=140): print("Grade A") elif(sum>120&sum<=130): print("Grade B+") eli...
tup=(1,2,3,4,7,3,"a") print(tup) # tup[0]=100 immutable #insersion Order preserved print(3 in tup) tup2=(100,50) employees=[(101,"Ayush",22,22000),(102,"John",29,23000),(103,"David",45,18000)] for i in employees: print(i) #to get only names for i in employees: print(i[1]) for i in employees: if(i[3]>2000...
no=int(input("Enter a no ")) if(no<0): print("Negative") elif(no==0): print("Neither negative or positive") else: print("Positive")
set=set() print(type(set)) set={10,20,20,10,40} print(set) #insersion Order not preserved set.add(105) print(set) print(set.pop()) days1={"Monday","Tuesday","Wednesday","Thursday"} days2={"Friday","Saturday","Sunday"} #union print(days1|days2) #or print(days1.union(days2)) #intersection set1={1,2,5,7,8} set2={3,4,5,...
# def cartesian(lst1,lst2): # tup=() # for i in lst1: # for j in lst2: # tup=(i,j) # print(tup) # # n1=int(input("Enter Size of List 1: ")) # n2=int(input("Enter Size of List 2: ")) # lst1=[] # lst2=[] # for i in range(0,n1): # el=int(input("Enter Element of List 1: ")) # ...
Vlr1 =int(input("ingrese primer numero")) Vlr2 =int(input("ingrese segundo numero")) Vlr3 =int(input("ingrese tercer numero")) suma = int(Vlr1) + int(Vlr2) + int(Vlr3) resta = int(Vlr1) - int(Vlr2) - int(Vlr3) multi = int(Vlr1) * int(Vlr2) * int(Vlr3) print("La suma es:.{}".format(suma)) print("La resta es:.{}".format(...
#GERSON ADILSON BOLVITO LOPEZ 5TO BIPC #Ejercicio 2 #ingrese un valor y mostrar los numeros desde el menos -10 al numero ingresado print("bienvenido al programa".center(50, "_")) num = int(input("ingrese valor: ")) contador = -10 while contador <= num: print (contador) contador+=1
#*-* coding:utf-8 *-* print "hello" print u"你好" list1 = [1,2,3,4,5] word = list1.pop(-1) print word print list1 print "list this".split(' ')
import numpy as np def mean_squared_error(estimates, targets): # """ # Mean squared error measures the average of the square of the errors (the # average squared difference between the estimated values and what is # estimated. The formula is: # # MSE = (1 / n) * \sum_{i=1}^{n} (Y_i - Yhat_i)^2 ...
# Generate the Twitter query for a specified file def load_query(query_path): # Create a list of the key phrases keys = [] # Open the file and read each line with open(query_path, 'r') as file: for line in file: parsed = line.strip() # Verify that the line is not empty ...
# -*- coding: utf-8 -*- def array_swap_items(input_array, index1, index2): """ Swap 2 items in an array :param array: the array where items are swapped :param index1: element to swap :param index2: element to swap :return: the array with items swapped """ output_array = input_array.copy...
import datetime as dt import time as tm print(tm.time()) print([1, 3]+[3, 7]) print("hh"+str(2)) dtnow = dt.datetime.fromtimestamp(tm.time()) # get year, month, day, etc.from a datetime dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second delta = dt.timedelta(days=-100, hours=2) # create a timede...
#1 to 10 # count = 1 # while count <= 10: # print count # count = count + 1 # n to m # start = int(raw_input("start number: ")) # end = int(raw_input("end number? ")) # while start <= end: # print start # start = start +1 #odd numbers # count = 1 # while count <=10: # if count % 2 != 0: # ...
choiceList = ["Chipotle", "Farm Burger" ,"RuSan's", "Exit"] # def counterTrack(count): # if count >= 5: # print "Limit reached fatty" def userChoice(): user_choice = int(raw_input("Pick a resturant - 1: Chipotle 2: Farm Burger 3: RuSan's 0: Exit " )) return user_choice def List_of_resturant(...
from turtle import * def center_turtle(): up() forward(150) left(90) left(270) down() def draw_a_square(): forward(100) right(90) forward(100) right(90) forward(100) right(90) forward(100) def fly_turtle_fly(): up() right(90) forward(150) down() def...