text
stringlengths
37
1.41M
def solution(inp: str) -> str: total: int = 0 for n in inp: total += int(n) if total % 9 == 0: return "Yes" else: return "No" inp: str = str(input()) print(solution(inp))
def write_string_to_disk_and_close(path, string): """ Write a string to the given path and close the file. """ with open(path, 'wb+') as destination: destination.write(string) destination.close() def write_file_to_disk_and_close(path, w_file): """ Write the file to the given path a...
##total = 0 ##for number in range(1, 10 + 1): ## print(number) ## total = total + number ##print(total) def add_number(): total = 0 for number in range(1, 10 + 1): print(number) total = total + number return(total) new_answer=total+10 answer=add_number() new_answer=answer+8 ...
def isUniqieChars1(string): ''' Apprach 1 ''' for i in range(0, len(string)): for j in range(len(string), 0, -1): if i!=j and string[i]==string[j]: return False return True def isUniqueChars2(string): '''Approach 2 - This is a slight variation to the approach explai...
def loadarray(): arrayFile = open("Integerarray.txt", "r") array = [] for i in arrayFile: array.append(int(i[:-1])) return array def sortCount(array): #Divide n = len(array) if n == 1: return array else: array1 = array[:n/2] array2 = arra...
## write linked list class LinkedList: def __init__(self): self.first = None def append(self, node): if self.first == None: self.first = node else: cur = self.first while cur.next != None: cur = cur.next cur.next = node def __repr__(self): cur = self.first print "first:", cur.value pr...
# # Bin Organizer # Jeff Shea, 2014 # # Python 2.7.6 # """Organizes pharmacy will-call bin structure based on number of name occurrences. Reads <filename>.csv as source data. Final sorted list will be output to BinOrder.txt in the local directory.""" import os import sys src = open( 'MOCK_DATA.csv' , mode='r...
#!/usr/bin/env python3 ####### Adapted from code by Pleuni Pennings https://github.com/pleunipennings/PlotNumWomenCongress ######## matplotlib import matplotlib.pyplot as plt import csv def get_data(): list_years = [] #create an empty list to store years list_num =[] #create an empty list to store th...
#!/usr/bin/env python # coding: utf-8 # #Implementation of DFS(Depth First Search) using Recursion # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from string import ascii_letters, ascii_lowercase, ascii_uppercase from collections import Counter from...
#!/usr/bin/env python # coding: utf-8 # Implementation of BFS(Breadth First Search) # # # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from string import ascii_letters, ascii_lowercase, ascii_uppercase from collections import Counter from itertool...
#!/usr/bin/env python # coding: utf-8 # #Implementation of PowerSet Using Iteration # In[1]: #!/usr/bin/python36 import os import subprocess as sp import math from random import randint, randrange from itertools import permutations, combinations, combinations_with_replacement from collections import Counter, dequ...
#!/usr/bin/python36 print("content-type: text/html") print("") ###input m1=int(input("input no of rows for first matrix")) n1=int(input("input no of columns for first matrix")) m2=int(input("input no of rows for second matrix")) n2=int(input("input no of columns for second matrix")) ##########################...
#! /usr/bin/env python3 """ Read stdin, turn input into 8 bit binary, output binary to stdout """ import sys import argparse import itertools import signal def parse_arguments(args): parser = argparse.ArgumentParser(description="Convert an input stream into binary") parser.add_argument( "in_file", ...
''' Input: an integer Returns: an integer ''' def eating_cookies(n, memory=None): if memory == None: memory = [0] * (n + 1) if n <= 1: memory[n] = 1 elif n == 2: memory[n] = 2 elif memory[n] == 0: memory[n] = eating_cookies(n - 1, memory) + eating_cookies(n - 2, memory) +...
# Psuedocode: # # x = //user input # if x > 0: //this will allow us account for positive ints - else statement at end of loop will account for negative input # # for square_root in range (abs(x) + 1): //runs from 0 up to absolute value of x+1. (allows exhaustive emuneration) # if square_root **2 >= abs(x): // i...
# Psuedocode # for number in range (2,20) # let the variable x = 1 // this will act as a semaphore # for i in range (2,number): # if number has no remainder: # print number equal to number 1 by number 2 # let x = 0 //switch semaphore state - forces program to run though entire range ...
euro_currency = float (input('Enter the number of Euro(s) to convert: ')) euro_to_pound = float (0.86) conversion = euro_currency * euro_to_pound if euro_currency <= 0: print("Amount must be >= 0. Please try again.") else: print('€' , euro_currency , 'converted to pounds = ' , '£' , conversion)
x = int (input('Please enter first int: ')) y = int (input('Please enter second int:')) z = int (input('Please enter third int:')) if (x%2 == 1 or y%2 == 1 or z%2 == 1): if (x>y and x>z): print(x, 'is the largest odd number'); elif (y>x and z>x): print(y, 'is the largest odd number'); ...
tableSize = int (input ('Please insert table size:')) i = 0 while i < 21: print (i, i*tableSize) i+=1
# Psuedocode # #def findDivisors(num1,num2): //define function that takes 2 argumets # divisors = (1,min(num1,num2)) //divisors initialised with 1,and min of the two x/y user input values. # for i in range (2, (min(num1,num2)+1)//2): //modified range between 2 and half of the number # if num1 % i == 0...
animals = 'herd of elephants' x=2 y=2 seg = animals [x:y] #prints result when x and y are the same (blank returned) print ('Segment is:',seg) x=7 y=3 seg = animals[x:y] #prints result when x is greater than y (blank returned) print ('Segment is:',seg) x=5 y=6 seg = animals[:y] #what happ...
x = raw_input("Please enter a random genre.") if x != "": print "Thank You!" x = raw_input("Please enter a random artist.") if x != "": print "Thank You!" x = raw_input("Please enter a random song.") if x != "": print "Thank You!" print ("It means a lot, thank you sooooo much.")
#Exercício Python 006: Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. num = int(input("Digite um número: ")) dobro = num*2 triplo = num*3 raiz = num**(1/2) print("O dobro de {} é {}.\nO triplo de {} é {}.\nA raiz de {} é {}.".format(num,dobro,num,triplo,num,round(raiz,2)))
#Exercício Python 017: Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa. from math import hypot oposto = float(input("Comprimento do cateto oposto: ")) adjacente = float(input("Comprimento do cateto adjacente: "))...
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. def porcentagem (num, porcent): resultado = num * porcent / ...
# Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. from datetime import dat...
class A: x = 4 y = 'kadabra' def __init__(self, a: int, b: int): print('konstruktor uruchomiony') self.x = a + b def square_x(self): print('podnoszę x do potęgi 2') self.x **= 2 def gg(n): g = [i * i for i in range(n)] return g w = [1, 2, 3] x = 12 w.append...
from dataclasses import dataclass @dataclass class Employee: name: str role: str vacation_days: int = 25 e = Employee(name="Joe", role="admin") print(e) # output: # Employee(name="Joe", role="admin", vacation_days=25) """ above example is equivalent of the following: """ class Employee: def __in...
print("包含中文的str") #获取字符的整数表示 print(ord('A')) print(ord('中')) #编码转化为对应的字符 print(chr(66)) print(chr(25991)) print(len('ABC')) print(len('中文')) print('Hello,%s' % 'world') print('Hi, %s, you have $%d.' % ('Michael', 1000000))
# # #1- Girilen bir sayının 0-100 arasında olup olmadıgını kontrol ediniz. # sayi1 = int(input("Bir sayi giriniz: ")) # result = (sayi1 >= 0) and (sayi1 <= 100) # print(f"Sayi 0 ile 100 arasındamı? : {result}") # # #2- Girilen bir sayının pozitif çift sayı olup olmadıgını kontrol ediniz. # sayi2 = int(input("Bir say...
#### ---- range metodu # for item in range(10): ### 0-10 a kadar olan sayilari range ile kısıtlayıp yazdırıyorum # print(item) # for item in range(2,10): ### 2 baslangic 10 bitis diyorum ve arasındaki sayilari istiyorum # print(item) # for item in range(2,10,2): ### 2 den 10 a kadar 2 ser atlayarak devam et di...
""" Modül Hakkında Bilgilendirme; """ print("Modül Eklenmiştir.") number = 10 numbers = [1,2,3] person = { "Name" : "Ali", "Age" : "24", "City" : "İstabul" } def func(x): """ Fonksiyon Hakkında Bilgilendirme; """ print(f"X: {x}") class Person: def speak(self): ...
# method list = [1,2,3] list.append(4) list.pop() print(type(list)) print(list) myString = "Hello" myString.upper() print(myString.upper()) print(type(myString)) #fonksiyon--> class bünyesinden değerlendirilmez! ##
## def sayWhat(name = ", boş bırakırsan böyle olur"): print("nerdesin def"+ name) sayWhat(", görüpde baktığın her yerde moruk") sayWhat(", 1 saat sonra halısahada") sayWhat() ###### def sayHello(name = "user"): return "hello " + name message = sayHello() message = sayHello("Mehmet") print(messag...
names = ["Ali","Yağmur","Hakan","Deniz"] years = [1998, 2000, 1998, 1987] #1- "Cenk" ismini listenin sonuna ekleyiniz. result = names.append("Cenk") result = names #2- "Sena" değerini listenin başına ekleyiniz. result = names.insert(0,"Sena") result = names #3- "Deniz" ismini listeden siliniz. result = names.remove(...
# # for ve while döngüsüne alternatif olarak kullanabileceğimz bir yöntem # for x in range(10): # print(x) # ##----------------------------------- # numbers = [x for x in range(10)] # print(numbers) # ##----------------------------------- # numbers = [] # for x in range(10): # numbers.append(x) # print(numbers)...
""" 1-100 arasında rastgele üretilecek bir sayıyı aşağı yukaru ifadeleri ile buldurmaya çalışın. ** "random modülü" için "python random" şeklinde arama yapın ** 100 üzerinden puanlama yapın her soru 20 puan. ** hak bilgisini kullanıcıdan alın ve her soru belirtilen can sayısı üzerinden hesaplansın. """ # import random...
#Dicionários #Criando dicionários dicionario = {} dicionario = dict () dicionario = {'nome': 'Grazi', 'idade': 35, 'altura':1.74} print(dicionario['idade']) print(dicionario) #Adicionando elementos em um dicionário dicionario['Analista de Dados'] = True print(dicionario) dicionario['altura'] = 1.7...
''' This is is a very basic stdio handler script. This is used by python.py example. ''' import time # Read an integer from the user: print('Give a small integer: ', end='') num = input() # Wait the given time for i in range(int(num)): print('waiter ' + str(i)) time.sleep(0.2) # Ask the name ...
import time import random def random_choice(): list = ["Mumbai", "Hyderbad", "Delhi", "Kolkata", "Calicut", "Chennai"] city = random.choice(list) print_pause("He has his hidden research lab somewhere here.So he will be" + " somewhere here in "+city+"'s dumpward.") print_pause("Now ...
""" Utility module Module used as a library of functions with an utility scope. No class are needed. """ def word_checker(user_input, possible_choices): """ Word in String Checker A simple way of checking what element of the possible choices list is more similar to the user input, in ...
""" Game module Game: this class is the game built with a specified characteristic function type and an adjacency matrix. """ from GAME.CHARACTERISTIC_FUNCTIONS.centrality_type_dictionary import TYPE_TO_CLASS class Game: """ Game Class This class has the basic information of the ga...
from .model_base import Model import numpy as np class LinearRegressionModel(Model): """ A model for Linear Regression. Arguments: input_features (int) output_features (int) normalize (bool) """ def __init__(self, input_features, output_features, normalize=False): ...
################################################################################ # Project Euler # Problem 4: Largest Palindrome Product # Description: Find the largest palindrome product of two 3-digit numbers ################################################################################ def getLargestPalindromePro...
TERM = 600851475143 currentNum = TERM divisible = False while (not divisible) and (currentNum > 1): print("currentNum is: " + str(currentNum)) # check if currentNum divides TERM if TERM % currentNum == 0: print("currentNum divides evenly: " + str(currentNum)) # check if currentNum is prime prime = True ...
#object oriented #(1)python class #when we write funtion in a class, it called method #when we write variable in class, it called attribute class User: name = '' email = '' password = '' login = False def login(self): email= input("enter email: ") password= input("enter password...
# 131、132 分割回文串 # 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 # 回文串 是正着读和反着读都一样的字符串。 # https://leetcode-cn.com/problems/palindrome-partitioning/ # 回溯法: 是一种算法思想,而递归是一种编程方法,回溯可以用递归来实现 class Solution: # 判断字符串是否为回文 def is_palindrome(self, p): return p == p[::-1] def partition(self, s): ...
# Generates a key # Created by JPCatarino - 28/10/2020 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.backends import default_backend import random import string # Generates a random string with letters and numbers # Taken f...
def function(): spisok_stud = ["Никита", "Рома", "Катя", "Лена", "Богдан", "Диасдастан", "Влад", "Стас", ] x = input("Добавьте человека") spisok_stud.append(x) print(spisok_stud) function()
from calculos import Calculos from comodo import Comodo calc = Calculos() def montando_comodo(vez): print(f"Vamos para o {vez}º comodo.\n") comprimento = float(input("Qual o comprimento do comodo em metros? ")) largura = float(input("E a largura? ")) comod = Comodo(comprimento, largura) ...
# Prompts user to enter file, reads file, and prints the file to the screen. fileName = input('Enter file name to be printed to screen: ') file_handle = open(fileName,'r') text = file_handle.read() print(text) file_handle.close()
m = int(input('Start from: ')) n = int(input('End on: ')) + 1 for i in range(m, n): print(i)
class Person: """ Person class saves names, emails, phone numbers, and friends to an object. Method greet() greets one person from another. Method print_contact_info prints objects email & phone number. """ def __init__(self, name, email, phone): friends = [] count = 0 ...
import random que = 'n' while True: my_random_number = random.randint(1, 10) print('Random', my_random_number) count = 5 print('I am thinking of a number from 1 to 10.') print('You have', count, 'guesses left.') while True: prompt = int(input("What's the number? ")) if prompt...
# Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta # necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. largura = float(input('Largura da parede: ')) altura = float(input('Altura da parede: ')) area = la...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- X_PLAYER = 1 O_PLAYER = -1 import numpy as np class TTTBoard: """ represents a tic tac toe board for the board """ def __init__(self, pos = [0 for _ in range(9)]): self.pos = pos def checkPos(self, pos): assert self.isValid(...
print("Im asking for the first and the last numbers of a range.") while True: try: x = int(input("Please give me the first number:")) y = int(input("Please give me the last number:")) if(x > y): print(x,"is greater than",y,"! Please give me the right order.") elif(x == y...
from math import * def distance(x1,y1,x2,y2): d = sqrt((x2 - x1)**2+(y2 - y1)**2) return(d) print(distance(2,3,5,6))
"""Floyd-Warshall algorithm for finding shortest path between all vertices in a graph. Works both undirected and directed graphs as long as all edges have property 'weight'. The only limitation is that graph may not contain negative cycles so undirected graphs with negative weights are not allowed. Time complexity: O(...
"""Hash-table that uses open addressing where collisions are solved by storing the item to next free slot. """ from itertools import chain, islice # Sentinel object used to mark unused slots SENTINEL = object() # Default size INITIAL_SIZE = 7 # Max load factor, once this is reached table will be grown LOAD_FACTOR =...
"""Directed graph that doesn't have multi-edges but may contain loops. Both vertices and edges may have associated properties. Vertices as stored as an adjacency matrix using dicts and as a separate dict that maybe iterated over. Time complexity of the operations: - check if edge (x, y) exists: O(1) - check degree of ...
"""Insertion sort.""" def sort(lst): """In-place insertion sort. Args: lst: List to sort """ for i in range(1, len(lst)): for j in range(i, 0, -1): if lst[j - 1] <= lst[j]: break lst[j - 1], lst[j] = lst[j], lst[j - 1]
#!/usr/bin/env python # Given the variable countries defined as: # Name Capital Populations (millions) countries = [['China','Beijing',1350], ['India','Delhi',1210], ['Romania','Bucharest',21], ['United States','Washington',307]] # Write code to print out ...
#!/usr/bin/env python def bad_hash_string(keyword,buckets): return ord(keyword[0]) % buckets def test_hash_function(func, keys, size): results = [0] * size keys_used = [] for w in keys: hv = func(w,size) results[hv] += 1 keys_used.append(w) return results #.s...
#!/usr/bin/env python def find_element(alist,value): for index in range(len(alist)): element = alist[index] if element == value: return index return - 1 print find_element([1,2,3],3) print find_element(['alpha','beta'],'gamma')
# 리스트 안의 동명이인을 찾아 집합으로 반환하시오. name = ["Booki", "Jeeeun", "Jungwoo", "Booki"] name2 = ["Booki", "Jeeeun", "Jungwoo", "Booki", "Jeeeun"] def find_namesake(a): n = len(a) result = set() for i in range(0, n - 1): for j in range(i + 1, n): if a[i] == a[j]: result.add(a[i]) ...
class MaxPriorityQueue: # A Priority Queue where the maximum element is removed first. # Implemented using a Heap. # TODO Add in place heap creation. def __init__(self): self.heap = [] self.size = 0 def insert_max(self, value): self.heap.append(value) self.bubble_up_...
import torch import math import matplotlib.pyplot as plt class KMeans: """ Implementation of KMeans clustering in pytorch Parameters: n_clusters : number of clusters (int) max_iter : maximum number of iteration (int) tol : tolerance (float) Attributes: centroids : cluster centroids (torch.Tensor) """ d...
import sys import os import datetime from argparse import ArgumentParser # Invoke this script using CMD e.g.: # # python art_sort.py --dry-run=false D:\pictures D:\OneDrive\new_sorted_art # ## parser = ArgumentParser( description="""Commandline tool for sorting files. Specify a source directory containing fi...
# Program que implementa uma função que gera a contraparte invertida de um numero inteiro: def inverso(numero): # Como strings podem ser invertidas, convertemos o numero de entrada # para uma string, invertemos seus caracteres e depois o convertemos de # vota, para então, retorná-lo. numero_str = str(nu...
# Esse programa implementa uma função principal de contagem de palavras, que recebe um # texto e retorna um dicionário cujas chaves são as palavras do texto e os valores # são suas frequências de aparição, mas só para as palavras cuja frequência de apariç~ao # está acima de um determinado limiar. Para ta, define-se dua...
# Programa que produz um córpus como o da atividade prática, a partir de arquivos # de texto separados que contenham as sentenças de cada classe, salvando # o córpus resultante num arquivo serializado, usando o módulo pickle. import pickle # importa-se a referência ao módulo # Define-se uma função auxiliarq que faz ...
from .cards import Card __all__ = ['Hand'] class Hand(object): """ Represents a playing card game hand containing instances of :class:`cardsource.cards.Card` A ``Hand`` is an iterable Python object that supports being added to other hands as well as other common iterable operations. Hands a...
# 荷兰国旗问题,将红白蓝分别记为0,1,2。解决方法是将0全部放前面,1全部放后面。 import random def Dutch_Flag(relist): length = len(relist) begin = 0 end = -1 current = 0 while True: # 如果为0,那么要放到前面,注意begin和current的值要互换,因为begin处的值可能为1。 # 然后begin、current都向右移 if str(relist[current]) == "0": relist[begin],relist[current] = relist[current],relis...
# 题目描述 # 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 # 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 # -*- coding:utf-8 -*- class Solution: def minNumberInRotateArray(self, rotateArray): # write code here if len(rotateArray) == 0: return ...
print('***********Welcome to Rock Paper Scissors Game***********') print('Rules: Rock beats scissors, Scissors beats paper, Paper beats rock \n') while True: player1 = input("What's your name?") player2 = input("And your name?") game_start={'rock': 1,'paper': 2,'scissors': 3} player_1 = input("%s,...
import datetime sum =0 while (True): user_input = input('enter the price of item: \n') user_input1 = input('enter the name of item:\n') print(f"{user_input}:{user_input1}") if user_input!='q': sum = sum + int(user_input) print(f"order total so far:{sum}") else: print(f"your ...
# -*- coding: utf-8 -*- __author__ = 'Fábio Rodrigues Pereira' __email__ = 'faro@nmbu.no' class LCGRand: """ It implements a linear congruential generator (LCG), which generates numbers according to the following equation r[n+1] = a * r[n] mod m where a = 7**5 = 16807 and m = 2**31-1. The con...
# -*- coding: utf-8 -*- import pytest __author__ = 'FABIO RODRIGUES PEREIRA' __email__ = 'faro@nmbu.no' def median(data): """ Returns median of data. :param data: An iterable of containing numbers :return: Median of data """ sdata = sorted(data) n = len(sdata) if not data: r...
from typing import Tuple # class TrieNode(object): # """ # Our trie node implementation. Very basic. but does the job # """ # # def __init__(self, char: str): # self.char = char # self.children = [] # # Is it the last character of the word.` # self.word_finished = False #...
# grow_river.py - # # A demonstration of a technique for generating random rivers in a gameworld. Specifically, # it demonstrates how one might build a world one region at a time, creating regions only # as the player explores them. This technique allows one to grow a river that terminates # at a body of water in one...
a = list(range(1,15)) def double(el): return el*2 def is_even(el): return el%2 == 0; double_even_in_a= [ double(el) for el in a if is_even(el)] print(double_even_in_a) # [4, 8, 12, 16, 20, 24, 28]
str = "hello world" print("str:", str) # 大写首字母 print("str.title():", str.title()) # 大写所有字符 print("str.upper():", str.upper()) # 小写所有字符 print("str.lower():", str.lower()) # 拼接字符 print("'a''b':", 'a''b') print("'1' + str:", '1' + str) # 删除前后的空白 print("str.rstripe():", ('\t'+str+'\t').rstrip())
# 验证关键字实参的调用 def hi(time, name): print(time+" " + name) hi(time='morning', name="tom") # 直接指明形参名则无需考虑传入顺序 hi(name='tom', time="morning")
for num in [1,2,3,4]: if num % 2 == 0: print("even number: ", num) continue print("this code never execute") print("odd number: ", num)
def hi(self): print(f'hi {self.name}') class C1: def __init__(self, name): self.name = name hi = hi c1 = C1('tom') # 1. 实例调用 c1.hi() # hi tom # 2. 实例方法赋值给变量进行调用 g = c1.hi g() # hi tom # 3. 类调用 C1.hi(c1) # 4. 类方法赋值给变量调用 h = C1.hi h(c1) # hi tom # 5. 函数调用 hi(c1) # hi tom
''' String literals in python are surrounded by either single or double quotation marks ''' #The strings can be displayed using the print() function print('Hello') # output : Hello print("Hello") # output : Hello #Assigning a string to a variable a = "Hello there" print(a) # output : Hello there #Multiline ...
import numpy from random import randint ''' Algoritmo genético O problema proposto foi movimentar animais, mais especificamente formigas, dentro de um espaço delimitado. No qual o movimento seria gerado aleatoriamente, tendo como intervalo inicial um valor menor, de forma a limitar o espaço e aumentando gradativamen...
#!/usr/bin/python #-*- Coding: utf8 -*- var=raw_input() login=var.split("&")[0].split("=")[1] senha=var.split("&")[1].split("=")[1] if login=="lucas" and senha=="123" : print("content-type: text/html") print"" f = open("site/menu.html","r") arquivo=f.read() f.close print(arquivo) else: prin...
# sql1.py """Volume 3: SQL 1 (Introduction). <Name> Natalie Larsen <Class> 001 <Date> 11-14-2018 """ import sqlite3 as sql import csv import numpy as np from matplotlib import pyplot as plt # Problems 1, 2, and 4 def student_db(db_file="students.db", student_info="student_info.csv", ...
'''Contains Hand class''' class Hand: """ Creates a player or dealer hand, the hand can contain cards and has a score count and aces count. Upon construction 2 cards are immediately added. """ def __init__(self,name,deck): self.is_dealer = name == 'dealer' self.cards = [] s...
import cx_Oracle username = 'MYONLINEEDU' password = 'RV-81-19-14f' database = 'localhost/xe' connection = cx_Oracle.connect(username, password, database) cursor = connection.cursor() print("Castle - gold") query1 = """ SELECT CASTLE.CASTLE, SUM(UNITS.GOLD) AS TOTAL_GOLD FROM CASTLE JOIN UNITS ON CASTLE...
#!/usr/bin/python # The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)2 = 552 = 3025 # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum...
import os import platform import sys import time from datetime import datetime from pytz import timezone """ Simple proof of concept python application """ def looper(): """ Simple proof of concept function. Loops indefinitely, prints to stdout and writes to file. :return: """ while True: ...
''' Study Drills 1. Go online an find out what Python'a input does. it asks for data from the user and stores it as a varaible 2. Can you find other ways to use it? Try some samples you find. ask the prompt in the input. line 16 3. Write another "form" like this to ask some questions. line 16 ''' print("How old are you...
while True: display = input('Press enter to continue ----- pre entret fo kontino') print('-------------------- Welcome to the main menu Aliens and Humans -------------------- \n\ Enter an option of your choice ---- echer nu topion fo rou kois\n\ 1. English to Aliench ---- English tre Aliench...
count = 1 while count < 11 : print(count) count = count + 1 if count == 11 : print('Counting complete.') myvar = 3 myvar += 2 mystring = "Hello" mystring += " world" print(myvar) print(mystring) myvar, mystring = mystring, myvar print(myvar) print(mystring) rangelist = range(10) print(rangelist) for number in ra...
import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import numpy as np from matplotlib.colors import LinearSegmentedColormap def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.c...
#------------------------------------------------------------------------------- # Name: agentframework_final_180204 # Purpose: # # Author: Michael Iseli # # Created: 23/01/2018 # Copyright: (c) iseli 2018 #------------------------------------------------------------------------------- ''' Coding for...
text = """Lattice paths Problem 15 Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20x20 grid? """ print(text) import time # create the permutations leaving out the unal...