text
stringlengths
37
1.41M
from collections import defaultdict d = defaultdict(list) d['a'].append(1) d['a'].append(2) d['b'].append(4) print(d) d = defaultdict(set) d['a'].add(1) d['a'].add(2) d['b'].add(4) print(d) from collections import OrderedDict def ordered_dict(): d = OrderedDict() d['foo'] = 2 d['bar'] = 1 d['spam'] ...
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: ...
Problem: https://www.hackerrank.com/challenges/median/problem import math import bisect def print_median(f): mid = math.floor(len(f) / 2) if len(f) % 2 == 0: val=sum(f[mid-1:mid+1]) / 2 print("{:.0f}".format(val) if val.is_integer() else val) else: print(f[mid]) def median(op, x)...
a=int(input("enter a")) try: b=a/(a-3) if a==3: raise ZeroDivisionError elif a>3: raise NameError except ZeroDivisionError: print("division by 0 is not allowed") except NameError: print("type error") else: print(b)
# Created by Jordan Leich on 10/8/2020 # Imports import colors import restart # Global variables # TODO Add more food items here with the correct calorie amounts please pizza = 275 apple = 95 banana = 105 potato = 165 wing = 102 spaghetti = 221 burger = 354 grilled_cheese = 700 pie = 95 cake = 129 ri...
import random def multiple(var1, var2, var5, n): if n % 10 == 1: return var1 if n % 10 in [2, 3, 4]: return var2 if n % 10 in [5, 6, 7, 8, 9, 0]: return var5 def palochka(n): if n % 4 == 1: z = random.randint(1, 3) else: z = (n % 4 + 4 - 1)...
import tkinter from math import * SCREEN_SIZE = (600, 600) def xs(x): return SCREEN_SIZE[0] // 2 + x def ys(y): return SCREEN_SIZE[1] // 2 - y main = tkinter.Tk() canvas = tkinter.Canvas(main, bg='white', height=600, width=600) a = int(input()) alpha = int(input()) def square(alpha,x1,y1)...
sqr = [] for x in range(5): sqr.append(x**2) print(sqr) cubes = list(map(lambda x: x*3, range(5))) print(cubes) cubes2 = [x**3 for x in range(10)] print(cubes2)
def isPrime(num): k = 0 if num > 1: for i in range(2, num): if num % i == 0: k += 1 if k > 0: print("No Prime") else: print("prime") else: print("invalid no.") isPrime(int(input("Enter an integer:")))
"""Everything related with the network.""" from typing import Iterable from .auxiliary_functions import print_with_asterisks from .node import Node, SimulationNode from .link import Link, SimulationLink class Network: """Represents a Wireless Sensor Network formed by nodes and links.""" def __init__(self, ...
from math import floor valor = float(input()) dias_atraso = int(input()) multa = valor * 0.02 juros = valor * (0.033/100) * dias_atraso valor_total = valor + multa + juros pag_min = valor_total * 0.1 # incoerencia com exemplo print("Valor: R$", format(valor,".2f")) print("Multa: R$", format(multa,".2f")) ...
def mars(): a=[1,2,3,4,5,6,7,8,9,10] dup=[] sack=[] sack2=[] b=[i for i in a if i not in dup] print("All stones on Mars : ",a) print("") n = int(input("Enter number of elements : ")) print("") for i in range(0, n): ele...
# Example 1, Import a python module with python interpreter: # Put this in /home/el/foo/fox.py: def what_does_the_fox_say(): print("vixens cry") # Get into the python interpreter: # dkm@glitch:/home/el/foo$ python # Python 2.7.3 (default, Sep 26 2013, 20:03:06) # >>> import fox # >>> fox.what_does_the_fox_...
def solution(s): answer = True bracketlist = [] for bracket in s: if bracket == "(": bracketlist.append(bracket) continue if bracket == ")": if len(bracketlist) == 0: answer = False continue else: ...
def isExpansable(board, level): next = False nextBoard = [[0 for x in range(len(board[0]) - 1)] for y in range(len(board) - 1)] for y in range(len(board) - 1): for x in range(len(board[0]) - 1): if board[y][x] == 1 and board[y+1][x] == 1 and board[y][x+1] == 1 and board[y+1][x+1] == 1: ...
#Faça um Programa para uma loja de tintas. # O programa deverá pedir o tamanho em metros quadrados # da área a ser pintada. Considere que a cobertura # da tinta é de 1 litro para cada 6 metros quadrados # e que a tinta é vendida em latas de 18 litros, # que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$...
#Escreva um programa que mostre de 1 até 50 na tela. ''' x=1 #contador while x<=50: print(x) x+=1 #incrementamos o nosso contador a cada laço ''' for num in range(1,51): print(num)
#Faça um programa para a leitura de duas notas parciais de um aluno. #O programa deve calcular a média alcançada por aluno e apresentar: #A mensagem "Aprovado", se a média alcançada for maior ou igual a sete; #A mensagem "Reprovado", se a média for menor do que sete; #A mensagem "Aprovado com Distinção", se a média for...
#Faça um programa que peça a base #e a altura de um retângulo e calcule #e mostre na tela a área e o perímetro. base=float(input('Digite a base: ')) altura=float(input('Digite a altura: ')) area=base*altura perimetro=2*base+2*altura print(f'O retângulo digitado tem base {base} e altura {altura}.') print(f'A área de...
var = float( input("Digite um numero: ") ) enesimo = (var * (var + 1) * (var + 2 )) print(enesimo)
n=int (input("Digite um valor : ")) for i in range (1,11): print(f"{i} x {n} = {i*n}") #O range faz a repeticao
cedulas = [200.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.50, 0.25, 0.10, 0.05, 0.01] def qnt_cedulas(valor: float) -> None: '''Função que imprime a quantidade de cédulas para um dado valor. Argumentos: -- valor (float): valor informado para o cálculo da quantidade de cédulas. ''' for cedula in c...
'''Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações: Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa n...
#Faça um programa para uma loja de tintas. #O programa deverá pedir o tamanho em metros quadrados #da área a ser pintada. Considere que a cobertura #da tinta é de 1 litro para cada 3 metros quadrados #e que a tinta é vendida em latas de 18 litros, #que custam R$ 80,00. Informe ao usuário a quantidades #de latas de tin...
valor1 = float(input("Digite o primeiro valor: ")) valor2 = float(input("Digite o segundo valor: ")) valor3 = float(input("Digite o terceiro valor: ")) if valor1 > valor2 and valor3: print("O primeiro número digitado é o maior: ", valor1) elif valor2 > valor1 and valor3: print("O segundo número digitado é o ma...
import RPi.GPIO as GPIO import time sensor_input = 36 led = 40 ledstate = False #set numbering mode for the program # GPIO.setmode(GPIO.BOARD) # GPIO.setup(sensor_input, GPIO.IN,initial=0) # GPIO.setup(led, GPIO.OUT,initial=0) #this method will be invoked when the event occurs def switchledstate(channel): global...
#!/usr/bin/python3 from math import sqrt class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __iadd__(self, other): self = self + other return self def __sub__(self, other): if type(other) == Vector: return P...
""" Greg Lundberg 94283312 1/23/20 truffle manager is state of the art inventory management for the truffle industry - disguised as exercise in functional decomposition. parallel arrays of items and corresponding quantities are passed in. a main menu is displayed, prompting the user to select among options to Order, ...
def ReadHighScores(): with open("HighScores.txt", "r") as f: lines = f.read().splitlines() HighScoreLine = lines[-1] f.close() return(HighScoreLine) def ReadPseudocodeGuide(): file = open("pseudocodeguide.txt", "r") lines = file.readlines() for line in lines: ...
def find_message(text): """Find a secret message""" message = "" for n in range(0, len(text)): if text[n].isupper(): message += text[n] return message if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert find_mess...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import argparse import pandas as pd from lib.programme_data import * def filter_data(all_data): """ Takes the data from SIMS and removes all students not in block 1 of the current academic year. This should remove any students on placement (block 1...
# Question 6 Write a program that can output the following shape to the console: # xxxxx # xxxxx # xxxxx # xxxxx # xxxxx # Please ensure that you only have the following print statements within your application: # print("x", end='') # print("") # You will need to use two loops for this to work. rows = int(input("Pleas...
# Write a program to ask the user for numbers, and then print any repeating numbers in a list. Example: # Enter a number: 5 # Enter a number: 2 # Enter a number: 6 # Enter a number: 98 # Enter a number: 7 # Enter a number: 6 # Enter a number: 5 # Enter a number: x # Repeating numbers: [5, 6] nums = [] while True: ...
# Take guesses from user for number between 1 and 25 and disply if greater/less than random number. User has 7 guesses. # If number guessed correct, stop asking and show user the numbers they guessed # If number less/more than then tell that add guess to list and tell how many guesses left # num = 17 # user tryi...
import sys def sort(arr): if len(arr) <= 1: return arr pivot = arr[0] left = [i for i in arr if i < pivot] equal = [ i for i in arr if i == pivot] right = [ i for i in arr if i > pivot] return sort(left) + equal + sort(right) def trader(days, prices): cost = 0 shares = 0 a...
# -*- coding: utf-8 -*- """ Created on Fri Dec 14 09:49:36 2018 @author: saras """ ###Task 1 & 2# # #salary = {} #creates an empty directory # #salary['al'] = 20000 #salary['Sarika'] = 800000 #salary['Jenny'] = 700000 #print(salary) # # ###Task 2 - create own dictionary #tel = {} #tel = {'alf':111, 'bobby':222, 'calv...
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 09:59:29 2019 @author: saras """ #Task 1 class Person: def __init__(self,name,age,gender): self.name = name self.age = age if gender == 'm': self.isMale = True elif gender == 'f': self.isMale = False ...
# -*- coding: utf-8 -*- """ Created on Tue Dec 4 15:38:15 2018 @author: saras """ age = input("How old are you? ") height = input("How tall are you? ") weight = input("How much do you weigh? ") print ("So, you're %r years old, %r tall and %r heavy." % (age, height, weight))
# -*- coding: utf-8 -*- """ Created on Sat Dec 8 17:05:23 2018 @author: Sara """ print ("You enter a dark room with two doors. Do you go through door #1, door #2 or door #3?") door = input("> ") if door == "1": print ("There's a giant bear here eating a cheese cake. What do you do?") print ("1. Take the cak...
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 16:33:16 2018 @author: saras """ # -*- coding: utf-8 -*- """ Created on Thu Nov 29 09:36:11 2018 @author: saras """ #Task 1 - Simple operations# 5 - 6 8 * 9 6 / 2 5 / 2 5.0 / 2 5%2 2 * (10 + 3) 2**4 #Task 2 - Variable practice# age = 5 age = "almost three" age = 29...
class Circle: def __init__(self,r_circle): self.R = r_circle def S_Circle(self): print(self.R**2*3.14) Circle_a = Circle(5) Circle_a.S_Circle()
list1=["flower","flight","flow"] shortest_str = min(list1,key=len) def prefix(list1): for i,char in enumerate(shortest_str): for other in list1: if other[i]!=char: return(shortest_str[:i]) print(prefix(list1))
list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i=0 j=1 score=0 n=len(list) while n>0: if list[i]>score: print(list[i],"list[i]") score=list[i] print(list[i]) for number in list: print(number, "number", list[j], "list[j]") if number!=list[j]: score+=n...
def practice(): string1 = "good" string2 = "ogdo" dict = {} for char1 in string1: if char1 in dict: dict[char1] += 1 else: dict[char1]=1 print(dict) for char2 in string2: if char2 not in dict: return "false" else: ...
nums=[1,2,3,4,5,6,7] k=3 left=0 right=len(nums)-1 for i in range(k): nums.insert(0,nums.pop()) print(nums) # while k>0: # print("left",nums[left]) # print("right",nums[right])
#First Section of Chapter ''' def hello(): print('Howdy!') print('Howdy!!!!!!') print('Hello there.') hello() hello() hello() def hello(name, age, gender): print('Hello, '+ name + age + gender) hello('Cody', ' 24 ', ' Male') hello('Emilee', ' 25 ', ' Female') ''' #Second Section of Chapter #1 import random #2 de...
from spillebrett import Spillebrett def main(): print("Oppgi dimensjoner på spillebrettet") kolonner = int( input("Antall kolonner: ") ) rader = int( input("Antall rader: ") ) nyttSpill = Spillebrett(rader,kolonner) nyttSpill.tegnBrett() #naboer = nyttSpill.finnNabo(1,0) while( input("...
def minFunksjon(): for x in range(2): c = 2 print(c) c += 1 b =10 b += a print(b) return(b) def hovedprogram(): a = 42 b = 0 print(b) b = a a = minFunksjon() print(b) print(a) hovedprogram() ''' Først defineres funksjonen "minFunksj...
import math def primeNumbers(n): a=[] bol=[] for i in range(2,n+1): a.append(i) bol.append(1) b=math.sqrt(n) for i in a: if i>b: break for j in range(i*i,n+1,i): if bol[j-2]==1: a.remove(j) bol[j-2]=0 return a #driver code n=int(input("find prime numbers in range of :")) print(primeNumbers...
from tkinter import * import time import random tk = Tk() canvas = Canvas(tk, width=1920, height=1080, background="grey") canvas.pack() def xy(event): xm, ym = event.x, event.y def task(): w=random.randint(1,1000) h=random.randint(1,1000) canvas.create_rectangle(w,h,w+150,h+150) def callback(even...
def Knapsack(value, weight, count, maxWeight): table = [[0]*(maxWeight+1) for i in range(count+1)] #print(table) for w in range( 1, maxWeight+1 ): #print(w) for i in range( 1, count+1 ): one = table[i-1][w] two = 0 if(w - weight[i-1] >= 0 ): ...
#Sintaxe do dicionário # Chave: Valor meuDicionario = { "nome": "francine", "idade": 26 } print("Mostrando o dicionário: ", meuDicionario) #Acessando valor pela chave print("Mostrando valor pela chave: ", meuDicionario['nome']) #Acessando valor pelo método get() print("Mostrando valor pela chave usando get(...
#while usamos enquanto a condição for verdadeira (loop infinito) #comentei pq fica infinito, pode zikar teu computador. #while i <= 6: # print("loop infinito",i) #while loop finito (com parada se satisfaz a condição) i=0 while i<6: print("loop elegante", i) i=i+1 #while com loop finito e if com break para ...
from .task2utils import * def task2(firstname, lastname, email, phone, birth, address, apt, city, state, zipcode): phone = phone.split('-') birth = birth.split('/') email = email.split('@') email = email[0].split('_') phone1 = str(phone[0]) phone2 = str(phone[1]) phone3 = str(phone[2]) month = str(birth[0]) ...
from HangmanTest import Game game = Game() while True: print(game.play()) play_again = input("GAME FINISHED\nWould you like to try again? (T / F): ") if play_again is "F": break elif play_again is "T": continue else: print("That was not a valid answer") # solution = "bla...
import sys import numpy.linalg as linalg def solve_matrix(A, b): """ This will call the built in matrix solving utility in numpy and solve the matrix equation A.x=b for x. inputs - A: The matrix generated in a separate function with coefficients of temperature at each node - b: The array of c...
def counting_while(x): i = 1 numbers = [] while i <= 500: print "At the top i is %d" % i numbers.append(i) i += i print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers x = int(raw_input("Number?: ")) numbers = counting_while(x) print "The numbers: " for num in numbers: p...
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song(["They rally around the family", "With ...
#! /usr/bin/env python """ Author: Gary Foreman Last Modified: January 18, 2015 Solution to Exercise 9 of Andrew Ng's Machine Learning course on OpenClassroom """ from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os K = 16 #number of means used for k-means algorithm DATA...
"""This file implement generic Graph class and method. The method naming convention follows princeton algorithm course (java) rather than PEP8. """ from collections import defaultdict class Graph(object): def __init__(self, v): if not isinstance(v, int): raise TypeError("v must be int.") ...
from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier from sklearn.datasets import load_breast_cancer #loads the dataset data = load_breast_cancer() #Splits dataset into training and test set x_train, x_test, y_train, y_test = train_test_split(data['data'],data['...
class Event: """ Class that represents an event that happened on a processor. The event can be instantaneous or continuous (for one unit of time). """ class Type: """ Enum all the possible types of events. """ IDLE = 0 RUNNING = 1 RELEASE = 2 ...
def dividir(A,B): resultado=A/B return resultado print("Ingrese los dos numeros a dividir\n\n") A=float(input("Ingrese el primer numero ")) B=float(input("Ingrese el primer numero ")) division=dividir(A, B) print(f"\n{A}/{B}={division}")
operation = raw_input("Input the math operation you wish to perform (x,+,-,/):") num1 = raw_input("Input the first number of the maths:") num2 = raw_input("Input the second number of the maths:") if operation == "x": print(float(num1) * float(num2)) elif operation == "+": print(float(num1) + float(num2)) elif ...
# Structure this script entirely on your own. # See Chapter 8: Strings Exercise 5 for the task. # Please do provide function calls that test/demonstrate your # function. '''Returns the word with each of its characters rotated n times.''' def rotate_word(word, n): result = '' # Result string for letter in word: new...
"""var1 = 20 var2 = 30 print("Hello {} World {}".format(var1, var2))""" arr = [1, 2] if "1" in (num for num in str(arr)): print("true") else: print("false") print(" ".join(str(x) for x in arr)) arr.append(3) print(arr) arr.remove(3) #remove will delete the first matching argument parsed. pop will delete t...
#!/usr/bin/python # -*- coding: utf-8 -*- import prop import math import re # Združljivost za Python 2 in Python 3 try: basestring except NameError: basestring = str def iff(p, q): """Vrne logično ekvivalenco izrazov p in q kot konjunkcijo dveh implikacij.""" return prop.And(prop.Implies(p, q), p...
import statistics def getSum(coverted_numbers): summation = 0 for number in converted_numbers: summation += number return summation def getCount(converted_numbers): count = 0 for number in converted_numbers: count += 1 return count def getLines(converted_numbers): num_li...
import os import csv csvpath = os.path.join('Resources', 'election_data.csv') with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #print(csvreader) csv_header = next(csvreader) #print(f"CSV Header: {csv_header}") candidates = {} total_votes = 0 ...
from game import Board from Player import Player import random class RandomPlayer(Player): """ This player can play a game of Tic Tac Toe by randomly choosing a free spot on the board. It does not learn or get better. """ def __init__(self): """ Getting ready for playing tic tac to...
# ''' # Linked List hash table key/value pair # ''' class LinkedPair: def __init__(self, key, value): self.key = key self.value = value self.next = None def __repr__(self): return f"<{self.key}, {self.value}>" class HashTable: ''' A hash table that with `capacity` bu...
from tkinter import * from tkinter.ttk import * from tkinter import messagebox import run def is_valid_day(x): try: x = int(x) if(x >= 0 and x <= 365): return True return False except: return False def clicked(): #check for invalid inputs if(not is_valid_d...
处理哈希冲突的几种方法: 开放定址法 开放定址法就是产生冲突之后去寻找下一个空闲的空间,其中又包括下面两种: 线性探测法:di= i ,或者其他线性函数。相当于逐个探测存放地址的表,直到查找到一个空单元,然后放置在该单元。 平方探测法:(https://python123.io/index/topics/data_structure/hash_table) 链表法 这是另外一种类型解决冲突的办法,散列到同一位置的元素,不是继续往下探测,而是在这个位置是一个链表,这些元素则都放到这一个链表上。 再散列 如果一次不够,就再来一次,直到冲突不再发生。 建立公共溢出区 将哈希表分为基本表和溢出表两部分,凡是和基本表发生冲突的元素,一...
''' 基本的排序算法:冒泡 插入 常见排序算法:归并 快排(面试题40) 拓扑(主要用来解决依赖问题,比如abcde五门课的学习之间有依赖关系,最后决定学习顺序以顺利完成学业等) 其他排序算法 桶排序、堆排序 ''' def bubblesort(arr): for i in range(1,len(arr)): for j in range(0, len(arr)-i): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] return arr def insertionSort2...
Series:One-dimensional ndarray with axis labels (including time series). Construction:class pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) data : array-like, Iterable, dict, or scalar value->Contains data stored in Series. eg1:Series(ndarray,index = [id1,id2,id3]) eg2:...
__author__ = 'aligajani' # MIT License: www.aligajani.com # PyQuote | pyquote.py # Beautify your quotes from PIL import Image from PIL import ImageFont from PIL import ImageDraw class PyQuote(): # Break quote into seperate lines def chunk(self, quote, step): line = quote.split() chun...
def betterBnW(pic): pixels = getPixels(pic) for p in pixels: average = int((getRed(p)*0.299) + (getGreen(p)*0.587) + (getBlue(p)*0.114)) setColor(p,makeColor(average,average,average)) return pic def lineDrawing(pic): pic = betterBnW(pic) drawing = makeEmptyPicture(getWidth(pic)-1,getHeight(pic)-...
""" Unique elements Order Change of var Adding new var LIST NO YES YES YES TUPLE NO YES NO NO DICTIONARIES YES NO YES YES SET YES ...
# Provided is a list of tuples. Create another list called t_check that contains the third element of every tuple. lst_tups = [('Articuno', 'Moltres', 'Zaptos'), ('Beedrill', 'Metapod', 'Charizard', 'Venasaur', 'Squirtle'), ('Oddish', 'Poliwag', 'Diglett', 'Bellsprout'), ('Ponyta', "Farfetch'd", "Tauros", 'Dragonite'...
from bicycles import * david = Customers("David", 200) lara = Customers("Lara", 500) vicky = Customers("Vicky", 1000) wheel1 = Wheels("wheel_model_1", 5, 30) wheel2 = Wheels("wheel_model_2", 4, 70) wheel3 = Wheels("wheel_model_3", 6, 200) frame1 = Frames("aluminum", 10, 150) frame2 = Frames("carbon", 8, 30) frame...
#definir_datos de entrada nota_1 = 0 nota_2 = 0 nota_3 = 0 nota_4 = 0 nota1 = int(input("Ingresar valor de la 1 unidad: ")) nota2 = int(input("Ingresar valor de la 2 unidad: ")) nota3 = int(input("Ingresar valor de la 3 unidad: ")) nota4 = int(input("Ingresar valor de la 4 unidad: ")) #proceso_datos de proceso nota...
def create_spectrogram(filename): """ From the path of the wav file, produces a png file in the same location """ sampling_rate, samples = wavfile.read(filename) f, t, spectrogram = signal.spectrogram(samples, sampling_rate, nfft=2048) img = Image.fromarray(np.uint8(spectrogram), mode='L') ...
ciphertext = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' wordparts = ['ing','er','or','ess','ist','ast','ian','ant', 'oi','io','ll','to','on','ir','ri','uo','ou','ent','ee', 'ic','oo','ic','man','woman','person','eur'...
""" 计算(大)文件的哈希值 +md5 +sha1 """ import hashlib import time def sha1Value(file, buffer_size=1024): sha1 = hashlib.sha1() with open(r'%s' % file, 'rb') as f: data_buffer = f.read(buffer_size) while data_buffer: sha1.update(data_buffer) data_buffer = f.read(buffer_size) ...
print("Here is a list of all the prime numbers from 2-100,000!!! It'll take a while to rpint out ALL of them so bear") # I will now start the main thing! # Takes myNum, an integer # Returns True if n is prime # Returns False if n is composite def isPrime(y, list): x = range(1,int(y)) num = y - 2 ...
print("Hello, how old are you?") year_ = raw_input() myVar = str( year_ + 10 ) print( " In ten years, you will be" + myVar + " years old!")
import sys donuts = 40 donuts_str = str(donuts) people = 11 people_str = str(people) donuts_ = str( donuts // people ) print("our party has " + people_str + " people and " + donuts_str + " donuts.") print( "Each person at the party gets " + donuts_ + " donuts.")
#coding=utf-8 """ 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) def teleman(number,b,c,d): a = str(number) if a not i...
import pyshorteners your_url = input('Please enter your url:...\n') shortener = pyshorteners.Shortener() shortened_url = shortener.tinyurl.short(your_url) print("Your new short url is..: ", shortened_url)
# -*- coding: utf-8 -*- import sqlite3 import os class Sql(object): def __init__(self): pass def createTable(self): # 创建用户表 if not os.path.exists("game.db"): conn = sqlite3.connect('game.db') c = conn.cursor() c.execute('''CREATE TABLE USER ...
import time import pandas as pd import numpy as np import matplotlib.pyplot as plt CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Retu...
# -*- coding: utf-8 -*- from math import sqrt def dist(col1, col2): return sqrt(sum([(col1[i]-col2[i])**2 for i in range(3)])) def sort_dictionnary(dic): return {e:dic[e] for e in sorted(dic)} def give_bottom_left_corner(points): """" Give the bottom left point of the rectangle conta...
# Naming the file : avoid spaces, avoid upper cases, '_' can be used to separate words # new_variables.py (python), newVariables.java (java) # Variables are temporarily conatiners. # Variables: #naming: should not start numbers # nameofthevariables = value , declaring and setting a value for the variable vname = "G...
#a comment, this is so you can read the program later #anything after the # is ignored by python print "I could have code like this" # and comment ignored here #you can also use a comment to disable or comment out a piece of code: #print "shit this wont run" print "hey, but this will run"
## For Users ## #user_id = input("Enter your Membership Name: ") #print("Hello! " + user_id) def test(): name = input('enter name of the actor:') if(name== 'Will Smith') or (name== "will smith"): print ("Spies in Disguise") print("I am Legend") print("Gemini Man") print("Suici...
import pandas as pd from keras.models import Sequential from keras.layers import Dense from keras.callbacks import EarlyStopping # Implementacion de Red Neuronal (Secuencial) con Keras #read data file df = pd.read_csv('data/SolucionSuma.csv', header=None) df.rename(columns={0: 'idSolucion', 1: 'idProblema', 2: 'param...
from cipher import Cipher from text import Text from english import ENGLISH_LETTERS class Affine(Cipher): def __init__(self, text): super(Affine, self).__init__(text) def decipher(self): best_result = Text(self.text) # go through all possible affine alphabets for a in ( 1, 3, 5...
''' How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf. I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it? According to Wikipedia, ROT13 (http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes on...
''' Simple Pig Latin Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. Examples pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway ! ''' def is_punctuation(word): return word[0] not i...
from csp import Constraint, CSP class QueensConstraint(Constraint): def __init__(self, columns): super().__init__(columns) self.columns = columns def satisfied(self, assignment): # q_0_c = queen 0 column, q_0_r = queen 0 row for q_0_c, q_0_r in assignment.items(): #...