text
stringlengths
37
1.41M
# import collections unsorted_list = [-199, 1, 4, 2, 6, -900, 3] sorted_list = [0, 1, 3, 5, 9, 14] def minimum(lst): min_val = lst[0] for e in lst[1:]: if e < min_val: min_val = e return min_val def sort_it(lst): sorted_lst = [] while len(lst) > 0: min_item = minimum...
class BinHeap: """ a balanced binary tree has each node with two children. Exception could be the last level where only one child can be there. It has methods to insert elements into the tree (which will automatically adjust the elements in correct position. Similarly, elements removed will cause the t...
""" A binary search tree relies on the property that the keys less than parent are found in the left subtree and keys greater than parent are found in the right subtree. This property holds true for each parent and a child. All keys in the left of the root are less than the root. While all keys on the right of the root...
from course import Course import csv from util import * class Reader: """Process files to get courses""" def __init__(self, file_name, delimiter=",", comment="#"): self.file_name = file_name self.delimiter = delimiter self.comment = comment self.courses = [] self.__pro...
#!/usr/bin/env python # encoding: utf-8 p1 = [0,1,2,3,4] p2 = [5,6,7,8,9] p3 = [10, 11, 12] class Pref: def __init__(self, day, time): """每门课排课时候的要求。TODO:是否可以把start_time归到这里里面? Attributes: time: 时间, (listof int), 从 0 开始 day : 周数,int, 从 0 开始 """ self.day = d...
# The Dutch Flag Partition is used to kind of teach how a quick sort works # You're a given a array of 0's, 1's and 2's and a pivot # Then you must build a function to rearrange this array such that: # All numbers smaller than the pivot must be to it's left # All numbers bigger than the pivot must be to it's right # S...
#Calculate the maxDepth of an N-ary Tree import collections class Solution: def maxDepth(self, root): if(not root): return 0 q = collections.deque() depth = 1 q.append([root, depth]) #Depth keeps the state of which depth we are while(q): node = q.pop(...
a=str(input()) opening= "[{(" closing = "]})" def isCorrectMatching(str:str)-> bool: l = [] for i in str: if i in opening: l.append(i) if i in closing: if not len(l): return False c = l.pop() if closing.index(i) != opening.index(c...
# # | 1 | 2 | 3 | 4 | # | 12 | 13 | 14 | 5 | # | 11 | 16 | 15 | 6 | # | 10 | 9 | 8 | 7 | # # This is the spiral order of an array 4x4 # Write a function that receives an array NxN and returns the spiral form of this array from typing import List A = [[1,2,3,4], [5,6,7,8], [9,10,11,1...
def main(): num=int(input('Ingrese numeros enteros positivos (finalice con 0):\n')) while num<0: print('Error. Ingrese numero mayor a 0:') num=int(input()) if num>0: max=num min=num while num!=0: if max<num: max=num elif num<0: ...
print('Ejercicio n5') print('') num1=int(input('Ingrese numero: ')) n0=str((num1//1%10)**2) n1=str((num1//10%10)**2) n2=str((num1//100%10)**2) n3=str((num1//1000%10)**2) n4=str((num1//10000%10)**2) print(n4+'-'+n3+'-'+n2+'-'+n1+'-'+n0)
def triangulo(catetos): for f in range (catetos): for c in range (catetos): if c<=f: print('*',end='') print('') #Debe ir fuera del 'for c' (columna) def main(): catetos=int(input('Ingrese base: ')) while catetos<3: #VALIDACION print('ERROR. Ingrese numero...
def estaEnLista(numero,lista): if numero in lista: return True else: return False def cargarLista(): print('Ingresar numeros,o 0 (cero ) para terminar: ') n=int(input()) lista=[] while n!=0: while n<0 and n!=0: print('Error, numero NO positivo.') ...
def res(a,b): if a>=b: return a-b elif b>=a: return b-a def condicion(a,b): if a>=b and res(a,b)>=b and res(a,b)<=a: return 'SI cumple condicion' elif b>=a and res(a,b)<=b and res(a,b)>=a: return 'SI cumple condicion' else: return 'NO cumple condicion' def ma...
print('Ejercicio 10') b=int(input('Ingrese numero binario (5 bits max): ')) n=len(str(b)) z=b//10000%10*2**4 x=b//1000%10*2**3 c=b//100%10*2**2 v=b//10%10*2**1 n=b%10*2**0 t=x+c+v+n+z print('Número en decimal: '+str(t))
def inserOrd(lst,num): pos=0 while pos<len(lst) and num!='': if num>=lst[pos] and num<=lst[pos+1]: lst.insert(pos+1,num) num='' else: pos+=1 return lst def main(): print('Ingresar numeros,o 0 (cero ) para terminar: ') n=int(input()) lista=[] ...
def aBinario(n): binario=0 potencia=0 while n!=0: r=n%2 n=n//2 binario=binario+(r*10**potencia) potencia=potencia+1 return binario def main(): num=int(input('Ingrese un numero decimal: ')) cifras=len(str(num)) ##validacion while not ((num>0 and num<100...
# Write a function to combine two lists of equal length into one, alternating elements. # combine(['a','b','c'],[1,2,3]) → ['a', 1, 'b', 2, 'c', 3] def combine(nums1, nums2): """ returns list of list1 and list2 elements alternating >>> combine(['a','b','c'],[1,2,3]) ['a', 1, 'b', 2, 'c', 3] """ ...
# Write a function that takes n as a parameter, and returns a list containing the first n Fibonacci Numbers. # fibonacci(8) → [1, 1, 2, 3, 5, 8, 13, 21] def fibonacci(n): """ >>> fibonacci(8) [1, 1, 2, 3, 5, 8, 13, 21] """ if n >= len(fibonacci_cache): fib = fibonacci(n-1) + fibonacci(n-2...
# Lab 17: Palindrome and Anagram from string import punctuation def check_palindrome(input): for symbols in punctuation: input = input.replace(symbols, '').lower().replace(' ', '') return input == input[::-1] def check_anagram(input1, input2): for symbols in punctuation: input1 = input1...
#this code was from my intro course, but I have added lists and commented out old code that I have changed # The quote “Through dangers untold and hardships unnumbered I have fought my way here to the castle beyond the Goblin City to take back the child you have stolen, for my will is as strong as yours and my kingdom...
import random import string password_upper_letters = int(input("How many upper case letters should our password have?\n> ")) password_lower_letters = int(input("How many lower case letters should our password have?\n> ")) password_numbers = int(input("How many numbers should our password have?\n> ")) password_special_...
a = float(input('\033[1;35m''Qual a quantidade de Kms percorridos: Km: ')) b = float(input('\033[1;35m''Qual a quantidade de dias alugados: Dias: ')) aa = a*0.15 bb = b*60 print('\033[1;31m''_'*45) print('O valor total a pagar é de: ''\033[4;32m''R$ {:.2f}''\033[m'.format(aa+bb)) print('\033[1;31m''_'*45)
n = soma = cont = 0 while n != 999: n = int(input('Digite um numero ou 999 para parar: ')) if n == 999: break cont += 1 soma += n print(f'O programa foi encerrado e a soma dos {cont} valores digitados é de {soma}')
largura = float(input('Qual a largura da sua parede? ')) altura = float(input('Qual a altura da sua parede? ')) area = largura*altura print('Sua parede tem a dimenção de {}x{} e sua área é de {:.2f}'.format(largura,altura,area)) print('Para pintar sua parede, serão necessários {:.2F} litros de tinta.'.format(area/2))
n = 0 cont = 0 while n != 999: n = int(input('Digite um numero ou 999 para parar: ')) cont += n print(f'O número escolhido foi {n} e a soma até agora é de {cont}') if n == 999: cont - cont - 999 print(f'O programa foi encerrado e a soma até agora é de {cont}')
#media de idade #homem mais velho #mulheres com menos de 20 anos # Passo 1: Criar variáveis e importar libs from statistics import mean #pegando a média from time import sleep nomem , nomef = [],[] #separando nomes em listas por sexo idadem , idadef = [],[] #separando idades em listas por sexo sexo_marculino , sexo_...
# Mark Tarakai # CS5400: Introduction to Artificial Intelligence -- Section 1A # Puzzle Assignment Series: Mechanical Match -- Segment II # Iterative-deepening Depth-limiting Search # Necessary libraries from copy import deepcopy import time import sys # Read in the puzzle file to instantiate the puzzle. The puzzle f...
print "raw_input returns a string" raw = raw_input("Enter a string: ") print type(raw) print "input preserves type (used for int or float)" a = input("Enter a number: ") print type(a)
#this program recieves personal information from users print("Personal Information") name=input("What is your name?") age=input("How old are you?") d_o_b=input("When were you born?") home_address=input("Where do you live?") school_name=input("What school do you attend?") sex=input("Are you male or female?") pr...
#this file is making the main code run import tictactoeiteration1lvl a = tictactoeiteration1lvl.Game() print("X or O") x=input() if x == "X": a.user_sign = "X" else: a.user_sign = "O" print("Wanna play first.. (type \'yes\' or \'no\')") get_input = input() if get_input == "yes": a.display() ...
class driver(): @staticmethod def age(x): if x>=18: print("you are free to drive a car in india.") else: print("you are not alowed to drive a car in India") driving = driver() x = int(input("what is your age: ")) driving.age(x)
class Employee: raise_amount = 1.04 def __init__(self, firstName, lastName, salary): self.first = firstName self.last = lastName self.pay = salary def fullName(self): return ('{} {}' .format(self.first, self.last)) def currentSalary(self): self.pay = int(self.pay*...
#EXAMPLES OF TUPLES tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5 ) tup3 = "a", "b", "c", "d" #empty tuple tup1 = () #one value tuple (needs a comma after) tup1 = (50,) #Accessing Values in Tuples tup4 = ('physics', 'chemistry', 1997, 2000) tup5 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup4[0]: ", tup1[0]) ...
""" We have a list of Annual rainfall recordings of cities. Each element in the list is of the form (c, r) where c is the city and r is the annual rainfall for a particular year. The list may have multiple entries for the same city, corresponding to rainfall recordings in different years. Write a Python function raina...
# First, import the fractions module and extract the class Fraction from fractions import Fraction #You can use the fraction (entered as (numerator, denominator)) in any context as any other integer or floating point number f = Fraction(3, 4) print (f) y= 3 def sum (f, y): return f+y print (sum(f, y))
numbers = [1,2,3,4,5] def square(x): return x**2 print(list(map(square,numbers))) print(list(map(lambda x: x**2,numbers)))
import numpy as np #Input array X=np.array([[1,0,1,0],[1,0,1,1],[0,1,0,1]]) #Output y=np.array([[1],[1],[0]]) #Sigmoid Function def sigmoid (x): return 1/(1 + np.exp(-x)) #Derivative of Sigmoid Function def derivatives_sigmoid(x): return x * (1 - x) #Variable initialization epoch=5000 #Setting training iteratio...
wakeup_times = [16, 49, 3, 12, 56, 49, 55, 22, 13, 46, 19, 55, 46, 13, 25, 56, 9, 48, 45,0] def bubble_sort_1(l): # TODO: Implement bubble sort solution for i in range(len(l)-1): for j in range(len(l)-1): if l[j]>l[j+1]: l[j],l[j+1] =l[j+1], l[j] bubble_sort_1(wakeup_ti...
# action.py: The Action class! # # Some Documentation: # # Actions have different types, and these different types have different attributes to go with them # (Sort of like pygame events) # # The constructor format is as follows: # Action(type (string), description (string), start (datetime), duration (timedelta), para...
# 不定長度參數 def sum01(*m,**n): # *可變的參數串列 , **可變的字典列表 涵義不同,順序不可對調 print(m) print(n) sum01(1,2,3) sum01(a=10,b=20,c=30) sum01(1,2,3,a=10,b=20,c=30) # sum01(a=10,b=20,c=30,1,2,3) # 格式不符合無法執行 print(sum([10,20])) # 原始sum函數用法 # 一級函式可修改名稱 print(type(sum01)) s = sum01 print(s(5,6,7))
# list (append,insert,remove), set (add), """ s = [10,20,30] print(s) print(type(s)) print(s[0]) print(s[1]) print(s[2]) s.append(40) print(s) s.insert(2,10) print(s) s.remove(20) print(s) """ t = {10,30,20} # set 用大括弧 (類似dict但沒有key跟冒號 dict01 = {id_01 : apple}) print(t) print(type(t)) t.add(25) # set加入元素必須用add(不可...
# type的練習 + 參數格式化( %() 與 .format )用在print的練習 ''' name = "Maud" health = 746.567 nstr = 20 nint = 18 nluk = 44 #參數格式化 by %() print("%s is your character\'s name. \t %s will start their travel." %(name, name)) # %() 參數格式化,一個蘿蔔一個坑的概念 print("%s is your character\'s name. \t %s will start their travel." %(name, name), en...
l1=['a','b'] l2=['c','d'] l3=[] for i in l2: l=[j+i for j in l1] l3.append(l) print l3
def fine(d1,m1,y1,d2,m2,y2): return_date = d1 due_date = d2 fine = 0 #check year if(y1>y2): fine = 10000 print(fine) return fine #check month elif(m1>m2 and y1==y2): fine = 500*(m1-m2) print(fine) return fine #check da...
def reduceString(str): stringList = list(str) answer = [] joined = '' i = 0 while i < len(stringList): if i == len(stringList)-1: answer.append(stringList[i]) print 'trig' i = i+1 if i < len(stringList): if stringList[i] != stri...
Squares = int(input("Enter a value:")) i = 1 sum = 0 while(i<=Squares): sum = sum+(i**2) i = i+1 if i>= Squares: print ("Sum of square is:",sum)
print("LUTFEN AKLINIZDA 0-100 ARASI BIR SAYI TUTUNUZ... ") tahmin = 50 yuksek =[100] dusuk = [0] while True: if not tahmin==99: tahmin = (max(dusuk) + min(yuksek))/2 tahmin = int(tahmin) else: tahmin = tahmin + 1 print("PC' nin tahmini = " , tahmin) sonuc = inpu...
import datetime import time class Timer: def __init__(self): self.dictStartTime = {'__init__': time.time()} self.dictEndTime = {} def startTimer(self, desc): self.dictStartTime[desc] = time.time() def endTimer(self, desc): self.dictEndTime[desc] = time.time() return self.dictEndTime[desc] -...
word=input("enter a word") list=[ord(x) for x in word] print(list)
def longestword(word): final = [] for i in word: final.append((len(i), i)) final.sort() print("The longest word in the list is:", final[-1][1], " and its length is:", len(final[-1][1])) a = [] n = int(input("Enter the no of words:")) for i in range(0, n): w = input("Enter the word:") a.app...
class Publisher: "information about books" def __init__(self, pubname): self.pubname = pubname def display(self): print("Publisher Name:", self.pubname) class Book(Publisher): def __init__(self, pubname, title, author): Publisher.__init__(self, pubname) self.title = title s...
class Bank: accountNo = "no.txt" name = "name.txt" typeOfAccount = "acc.txt" balance = 0 def __init__(self,accountNo,name,typeOfAccount,balance): self.accountNo = accountNo self.name = name self.typeOfAccount = typeOfAccount self.balance = balance def deposit(self,amount)...
""" Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês. """ valor_hora = float(input("Valor da hora trabalhada: ")) horas_mes = int(input("Quantos horas trabalha por mes? ")) salario = valor_hora*horas_mes print("O ...
#function for checking if a number is prime def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True #function for XORing two strings def XOR(a,b): a,b = str(a),str(b) assert(len(a) <= len(b)) ...
##LC 1180. Count Substrings with Only One Distinct Letter #Solution class Solution(object): def countLetters(self, S): """ :type S: str :rtype: int """ rep = ans = 0 cur = '' S += '/' for s in S: if s == cur: rep +...
##LC 1213. Intersection of Three Sorted Arrays #Solution class Solution(object): def arraysIntersection(self, arr1, arr2, arr3): """ :type arr1: List[int] :type arr2: List[int] :type arr3: List[int] :rtype: List[int] """ read1 = read2 = read3 = 0 ints...
dic1={1:'nikhi',2:'bijit'} key1=2 def solution(dic1, key1): if dic1.has_key(key1): return True else: return False solution(dic1,key1)
'''THE FUNCTION TAKE ALTERNATIVE LETTERS FROM EACH AND FORM A NEW WORD''' def interlock(word1,word2): res=[] if len(word1)==len(word2): list1=list(word1) list2=list(word2) for i in range(len(list1)): res.append(list1[i]) res.append(list2[i]) return "".join(res) else: return None print inte...
''' FUNCTION TAKE A LIST OF WORDS AND SORT THEM FROM LONGEST TO SHORTEST ''' import random def sort_by_length(lst): res=[] for i in lst: res.append((len(i),i)) # res.sort(len(i)) res.sort(reverse=True) res1=[] for length,word in res: res1.append(word) print 'The sorted list is:', re...
def pal(word1,word2): if len(word1)==len(word2): if word1[:]==word2[::-1]: return 'given two are palindrome:',word1,word2 else: return 'they are NOT' else: return 'not in same length' print pal('sonu','unos') print pal('sonu','sasi') print pal('sonu','ssssssss')
def avoids(word,str): for letter in word: if letter in str: return False return True avoids('sonu','ejjhdsklcjjb')
''' FIND ANGRAMS IN A WORD LIST ''' def anagram(): dict1={} with open('word.txt')as f: for i in f: i=i.strip() key=sortd(i) if key in dict1: value=dict1.get(key)+","+i print value dict1[key]=value else: dict1[key]=i return dict1 def sortd(i): char=[x for x in i] char.s...
def gcd(m,n): if m<n: m,n=n,m while True: r=m%n if r==0: print n else: m=n n=r gcd(4,18)
''' THIS FUNCTION TAKE ANY NO.OF ARGUMENTS AND RETURNS THEIR SUM ''' def sumall(*arg): sum=0 for i in arg: sum=sum+i print 'The sum is:', return sum print sumall(55,66,44,2,8,63,22,58)
def sequence(n): while n!= 1: print n, if n%2==0: n=n/2 else: n=n*3+1 sequence(7)
'''FUNCTION TAKE TWO STRINGS AND RETURN TRUE IF THEY ARE ANAGRAMS''' def is_anagram(str1,str2): lst1=sorted(list(str1)) lst2=sorted(list(str2)) if lst1==lst2: return True else: return False print is_anagram('arundhathi','anirudh') print is_anagram('amaze','eamza')
"""各列の組から新しい特徴量を作成する""" import pandas as pd import numpy as np import itertools def plus(x): """ Args: x (DataFrame): 説明変数 Returns: DataFrame: xのすべての列の要素が2の組それぞれの和 """ print("plus...") df = pd.DataFrame(np.zeros((x.shape[0], 1))) df.columns = ["to_delete"] name_li...
#Zahlenraten.py Versuch = False import random zufallszahl = random.randint(1,5) #Benutzer soll die Zahl dews COmpzuetrs erraten while(Versuch == False): v = input ("Geben sie eine zufällige Zahl zwischen 1 und 5 ein!") if(int(v) == zufallszahl): Versuch = True print ("Sehr gut") else: ...
#!/usr/bin/env python3 """ List documents """ import pymongo def list_all(mongo_collection) -> list: """ Lists all documents in a collection Args: mongo_collection: Collection of object Return: List with documents, otherwise [] """ documents: list = [] for doc...
''' def my_func(i): if i == 0: return print("hi world") my_func(i-1) my_func(10) ''' def fib_numbers(i): if i <= 1: return 1 else: return fib_numbers(i-1) + fib_numbers(i-2) print(fib_numbers(100)) # creating a list of fibonacci numbers using a generator print([fib_numbe...
from data_structures.stack import Stack class QueueStack: def __init__(self): self._stack1 = Stack() self._stack2 = Stack() def enqueue(self, item): """Add item to the enqueue stack. Parameters: item: item to add to the queue """ while len(self._stack...
import sqlalchemy from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # define how to connect to the database engine = create_engine( # TODO: change this to point to your MySQL instance! 'postgresql+psyco...
import unittest from data_structures.doubly_linked_list import DoublyLinkedList class TestLinkedlist(unittest.TestCase): def test_first_item(self): test_list = DoublyLinkedList() test_list.insert_front(5) test_list.insert_front(9) pop = test_list.pop_front() self.assertEq...
import time def decorator_time(func): def wrapper(x): #this is a new version of timed function, with additional functionality print('Executing the wrapper') start = time.time() func(x) end = time.time() print(f'Time elapsed: {end - start}') return wrapper #@decorato...
class Stack(): def __init__(self): self._data = list() #push complexity: O(1) def push(self, item): self._data.append(item) # pop complexity: O(1) if implemented as a python list. Because we can directly access the index def pop(self): item = self._data[len(self._data) -1]...
from math import * x = float(input("Введіть х =")) e = 2.71828 y = atan(x) + ((pow(e,0.6*x-1)-pow(x+6.1,3/2))/(log(x)+pow(log10(x),2))) print (y)
# funcao fatorial def fatorial(n): if n < 0: return 0 fat = 1 while (n > 1): fat = (fat * n) n -= 1 return fat def test_fatorial0(): assert fatorial(0) == 1 def test_fatorial1(): assert fatorial(1) == 1 def test_fatorial2(): assert fatorial(2) == 2 def test_f...
 valor = int(input("Digite o valor de n: ")) aux = 1 while (valor > 1): aux *= valor valor -= 1 print(aux)
import random from blackjackart import logo from os import system def screen_clear(): _=system('cls') def deal_card(): cards=[11,2,3,4,5,6,7,8,9,10,10,10,10] card=random.choice(cards) return card def calculate_score(cards): if sum(cards)==21 and len(cards)==2: return 0 if 11...
#!/usrbin/env python3 # -*- coding:utf-8 -*- import json,time goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ] def login(): #登录模块 for i in range(3): username = input('please input yuor name:') if user_dict.get(...
#MIT 6.00 2008 OCW #Problem Set 2 #ps2a.py #This program calculates the largest number of chicken McNuggets that cannot be purchased #by using combinations of 6, 9, and 20 packs of McNuggets #Function tests if there exists non-negative integers a,b,c such that 6a+9b+20c=n #precondition: n is a non-negative integer t...
# 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. def length_of_longest_substring(s): len_longest_substring = 0 unique_list = [] for element in s: if...
# Given an array of integers nums and an integer target, # return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, # and you may not use the same element twice. # You can return the answer in any order. # Constraints: # 2 <= nums.length <= 10^...
# Given a non-negative integer x, compute and return the square root of x. # Since the return type is an integer, the decimal digits are truncated, # and only the integer part of the result is returned. # # Example 1: # Input: x = 4 # Output: 2 # # Example 2: # Input: x = 8 # Output: 2 # Explanation: The square root of...
# -*- coding: utf-8 -*- """ Created on Tue May 12 21:29:57 2020 @author: Ayush Singh """ #!/bin/python3 import math import os import random import re import sys # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as p...
""" 7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the ...
#!/usr/bin/env python from random import * import binascii def randomlist(n = 0): lst = [] for i in range(0,n): lst.append(randint(1,1000)) return lst #bubble sort def bubble(lst): for i in range(0, len(lst)): for j in range(i, len(lst)): if lst[i] > lst[j]: lst[j],lst[i] = lst[i], lst[j] return lst #...
#This python script simply creates a postgresqsl table import psycopg2 def create_tables(): """ create tables in the PostgreSQL database""" command ="CREATE TABLE geo_table (Town VARCHAR ,latitude FLOAT(45),longitude FLOAT(45))" conn = None try: # connect to the PostgreSQL server conn = ...
__author__ = 'Binh Le' def ValConve(c): if(c=="C"): return 12 if(c=="O"): return 16 if(c=="H"): return 1 return 0 def IsVal(Arg): if((Arg=='(')or(Arg==')')or(Arg=='C')or(Arg=='O')or(Arg=='H')): return 0 return 1 def IsLetter(Arg): if((Arg=='C')or(Arg=='O')o...
import sys import os from database import Database from table import Table currentDb = "NA" DIRECTORY = "PA2/" def main(): try: #runs through the input and processes all of the commands sqlInput = input().rstrip("\r\n") while sqlInput.lower() != ".exit": while sqlInput[:2] != "--" and len(sqlInput) != 0 and...
arr = [17,18,5,4,6,1] arr[len(arr)-1] = -1 for i in range(len(arr)-1): arr[i] = max(arr[i+1:]) print(arr)
""" 4)Given an array with many numbers, display as output the total number of numbers having even number of digits """ mylist = list(map(int, input("Please enter the List(with spaces) Sharvari: ").split())) print(mylist) def sharvari(mylist): count,count1 = 0,0 for i in mylist: while i!=0: ...
def estimatinge(x): a = x b = (1+1/a)**a return float(b) c = int(input("Number of decimal points of accuracy: ")) ans = estimatinge(x) print("The estimate of the constant e is:",ans)
#Paulina Romo Villalobos def gcd(n,m): if(n == m): answer = n elif(n > m): answer = gcd((n-m), m) else: answer = gcd(n, (m-n)) return answer x = int(input("First number: ")) y = int(input("Second number ")) gcdiv = gcd(n, m) print("GCD of", x , "and", y, ": ", gcdiv)
import sys import os import enum import re import socket class HttpRequestInfo(object): """ Represents a HTTP request information Since you'll need to standardize all requests you get as specified by the document, after you parse the request from the TCP packet put the information you get in t...
#!/usr/bin/env python3 import os def format_history_statistics(dictionary): """Output dictionary in specific format: <value key>. Parameters: ---------- dictionary : dict Dictionary to print in specified format. """ for key in dictionary.keys(): print(str(dict...
# Sales by Match # # There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. # # Example # There is one pair of color and one of color . There are three odd socks left, one of each col...
#!/usr/bin/python3 """Minimum copy and paste operations""" import itertools def minOperations(n): """Find the minimum number of "copy all" and "pastes" needed to get n""" if n < 2: return 0 dividend = n ret = 0 for divisor in itertools.count(2): while dividend % divisor == 0: ...
############### Transforming Data # Print the head of the homelessness data print(homelessness.head()) # Import pandas using the alias pd import pandas as pd # Print the values of homelessness print(homelessness.values) # Print the column index of homelessness print(homelessness.columns) # Print the row index of h...