text
stringlengths
37
1.41M
#!/usr/bin/python3 # Filename: super.py class Bird(object): def chirp(self): print("make sound") class Chicken(Bird): def chirp(self): super().chirp() print("ji") bird = Bird() bird.chirp() summer = Chicken() summer.chirp()
#!/usr/bin/python3 # Filename: residual.py i = 0 residual = 500000.0 interest_tuple = (0.01, 0.02, 0.03, 0.035) repay = 30000.0 while residual> 0: i = i + 1 print("The ",i , "year need to pay debt") if i <= 4: interest = interest_tuple[i - 1] else: interest = 0.05 residual = resi...
#!/usr/bin/python3 # Filename: inheritance.py class Bird(object): feather = True reproduction = "egg" def chirp(self, sound): print(sound) class Chicken(Bird): how_to_move = "walk" edible = True class Swan(Bird): how_to_move = "swim" edible = False summer = Chic...
#!/usr/bin/python3 # Filename: function_timer.py import time def function_timer(old_function): def new_function(*arg, **dict_arg): t1 = time.time() result = old_function(*arg, **dict_arg) t2 = time.time() print("The run time is:" + t + "s.") return result return new_fun...
# 함수 funtions 간략하고 보기쉽게 짜는 기법, 여러개를 수정해야할때 중복을 단순하게 바꿔준다 # 입력값 parameters, 반환값 return def hello_friends(name): print("hello, {}".format(name)) name1 = "marco" name2 = "jane" name3 = "john" name4 = "tom" name5 = "marco" name6 = "jane" name7 = "john" name8 = "tom" # print("hi, {}".format(name1)) # print("hi, {}"...
# Enter your code here. Read input from STDIN. Print output to STDOUT a=int(input()) b=int(input()) m=int(input()) power=pow(a,b) print power module=pow(a,b,m) print module
#有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。 ''' #!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == ' __main__ ' # 方法一 : 0 作为加入数字的占位符 a = [ 1 , 4 , 6 , 9 , 13 , 16 , 19 , 28 , 40 , 100 , 0 ] print ' 原始列表: ' for i in range ( len ( a ) ) print a [ i ] number = int ( raw_input ( &quot; \n 插入一个数字: \...
#打印出杨辉三角形(要求打印出10行如下图)。   ''' #!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == ' __main__ ' a = [ ] for i in range ( 10 ) a . append ( [ ] ) for j in range ( 10 ) a [ i ] . append ( 0 ) for i in range ( 10 ) a [ i ] [ 0 ] = 1 a [ i ] [ i ] = 1 for i in range ( 2 , 10...
#判断101-200之间有多少个素数,并输出所有素数。 ''' #!/usr/bin/python # -*- coding: UTF-8 -*- h = 0 leap = 1 from math import sqrt from sys import stdout for m in range ( 101 , 201 ) k = int ( sqrt ( m + 1 ) ) for i in range ( 2 , k + 1 ) if m % i == 0 leap = 0 break if leap == 1 print ' %-4...
print("hello world") print(2 + 2) num1 = 2 num2 = 4 print(num1 * num2) name = "Mj" print(name) name1, name2, name3 = "Mj", "Jm", "MJJM" print(name1, name2, name3) s = "123456" print(s[1]) print(s[1:5]) print(s * 2) print(s + "789") print(s[1:5:2]) list = ['runoob', 786, 2.23, 'john', 70.2] print(list) print(list...
#有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 a = [2, 3] b = [1, 2] for i in range(18): a.append(a[-2] + a[-1]) b.append(b[-2] + b[-1]) c = 0 for i in range(len(a)): c = c + a[i] / b[i] print(c)
#统计 1 到 100 之和。 ''' #!/usr/bin/python # -*- coding: UTF-8 -*- tmp = 0 for i in range ( 1 , 101 ) tmp += i print ' The sum is %d ' % tmp '''
num=int(input("Enter a number: ")) a = 0 while(num > 0): a=a+num num=num-1 print("The sum of number is",a)
# Sum square difference ''' 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 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is ...
#!/usr/bin/env python3 # encoding: utf-8 nums = [x for x in range(30) ] for num in nums: print(num) strs = [m + n for m in "ABC" for n in "XYZ"] for str in strs: print(str)
# -*- coding: utf-8 -*- ''' This file containing utilities to assist in processing the xml file. ''' import codecs import re import urllib ''' Following is the regular expression match differenct kinds of strings. ''' two_colons_reg = re.compile(r'^([a-z]|_|[0-9])*:([a-z]|_|[0-9])*:([a-z]|_|[0-9])*$') lower_reg = re....
def listSum(numList): theSum = 0 for i in numList: theSum += i return theSum def listSumRecursion(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listSumRecursion(numList[1:]) if __name__ == '__main__': a = [1, 3, 5, 7, 9] print("Loop: {}...
#lists subba = [216, "Reddy", True, False] print(subba[0]) print(type(subba)) print(subba[-1]) # syntax to retuurn multiple values from list #list[start:end:step] print(subba[1:3]) #list can have a list inside the list reddy = ["Garem",subba,"kanna"] print(reddy[1]) #syntax to return values list withing the list is lis...
let = input("Please enter the wor") vowels = 0 consonants = 0 for letter in let: if letter.lower() in "aeiou": vowels = vowels+1 elif letter =="": pass else: consonants = consonants+1 print("there are {} vowels".format(vowels)) print("there are {} consonants".format(consonants)) fri...
""" Recalls the method or class property used as an input parameter by the calling frame""" import inspect import re def arcane_recall(calling_frame, target_argument_pos=0): """ This is some super sneaky shit. And I know! I know! "You're not supposed to mess with the stack, it's a bad idea, there be dr...
# https://www.hackerrank.com/challenges/python-arithmetic-operators/problem # cambiar a f"{}" - f-string #Opcion 1 - Con funcion def run(a,b): print("""{} {} {}""".format(a+b,a-b,a*b)) if __name__ == '__main__': a = int(input()) b = int(input()) run(a,b) #opcion 2 ******* a = 4 b = 2 print(a + b) p...
def repitiendo(text, n): if n == 0: return print(n, text) repitiendo(text, n-1) text = "recursividad" n = 10 repitiendo(text, n)
#Opcion 1 name = input("Cual es tu nombre: ") print("Hola ", name) #Opcion 2 name = input("Cual es tu nombre: ") saludo = "Hola " print(saludo, name) """ Instrucciones: Pregunta el nombre a tu usuario y muestra en pantalla su nombre con un saludo Ejemplo Cual es tu nombre llamas: Juan Resultado "hola, juan!!!"...
n=int(input("enter a number")) if(n%4==0): print("leap year:") else: print("not leap year:")
''' Exceptions are the errors which being break by the program or user. We have to handle the exception to excecute our program or software smoothly. In exception handling we have 3 main blocks. 1. Try block 2. Except block / Catch block 3. Finally block Keywords to use in Exceptional Handling. try, exc...
#factorial #using for loop n=int(input("enter a number:")) total = 1 for i in range(n,0,-1): total += total*i print("factorial of",n,"is",total) #using while loop n=int(input("enter a number:")) total=1 i=1 while i<=n-1: total += total*i i += 1 print("factorail of",n,"is",total)
import pandas as pd import numpy as np ddf=pd.read_excel(open('k-nnalgo.xlsx','rb')) x=ddf.iloc[:,0:-1] y=ddf.iloc[:,-1] x=np.array(x) y=np.array(y) i=int() j=int() result=[] us=[] z=[] a=int(input("enter the quality of cottan-")) b=int(input("enter the price of cottan-")) #for getting list only for distance elements ...
import sqlite3 conn = sqlite3.connect('employee.db') cur = conn.cursor() ##query = 'create table employee (id integer primary key, first_name varchar(20),last_name varchar(20))' ## ##cur.execute(query) ##insert_query = 'insert into employee (id, first_name, last_name) values (?, ?, ?)' ##cur.execute(insert_query, ...
from typing import TypeVar, Generic, Callable, Optional T = TypeVar('T') U = TypeVar('U') class ImmutableList(Generic[T]): """ Immutable list is data structure that doesn't allow to mutate instances """ def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> N...
import re """ parsed data structure 0 => first number 1 => operator 2 => second number 3 => answers (None if display_answers=False) 4 => length of the largest number """ def arithmetic_arranger(problems, display_answers=False): parsed = parse_data(problems) if type(parsed) != list: return parsed parsed = c...
def elefantes(n): if n <= 0: return "" if n == 1: return "1 elefante incomoda muita gente" return elefantes(n - 1) + str(n) + " elefantes " + incomodam(n) + ("muita gente" if n % 2 > 0 else "muito mais") def incomodam(n): if n <= 0: return "" if n == 1: return "incomodam " return "inco...
class Employee: def __init__(self, first,last, pay): self.first = first self.last = last self.email = first + '.' + last + '@company.com' self.pay = pay def full_name(self): return '{} {}'.format(self.first,self.last) emp1= Employee('Corey','Schafer',500000) emp2 =...
#!/usr/bin/python3 def uniq_add(my_list=[]): if my_list: summ = 0 uniq_list = list(set(my_list)) for x in uniq_list: summ += x return summ else: return 0
#!/usr/bin/python3 """ Write an empty class BaseGeometry """ class MyInt(int): """a class as subclass of int""" def __eq__(self, other): if int(self) == int(other): return False else: return True def __ne__(self, other): if int(self) != int(other): ...
import unittest from movies import Movies class MoviesTest(unittest.TestCase): def setUp(self): self.m = Movies() def test_movies_sort_by_one_column_year(self): sql = """SELECT TITLE, YEAR FROM MOVIES ORDER BY YEAR DESC """ query = self.m.query_db(sql) self.assertEqual(self....
from random import randint, choice, choices from tile import Tile from copy import deepcopy from gridStack import GridStack class Grid: def __init__(self, arrays=None, cols=4, rows=4): """ Creates the Grid object :arrays: 2d array that will populate the grid :cols: number of colum...
#!/usr/bin/python3 # to concatenate strings and numbers s = 'aaa' + 'bbb' + 'ccc' print(s) s1 = 'aaa' s2 = 'bbb' s3 = 'ccc' s4 = 'ddd' s = s1 + s2 + s3 + s4 print(s) s = s1 + '.' + s2 + '.' + s3 + '.' + s4 print(s)
#!C:\Python3\python.exe import nourrisson_normes # Fonction pour valider que la valeur val est un entier def isInteger(val): try: int(val) return True except ValueError: return False # Fonction pour valider que la valeur val est un décimal def isFloat(val): try: float(val) ...
import sqlite3, hashlib def buildDB(): #builds a database with three tables data="data.db" db=sqlite3.connect(data) c=db.cursor() command="CREATE TABLE if not EXISTS Story_List(ID INTEGER PRIMARY KEY, Title TEXT, Story TEXT)" c.execute(command) command="CREATE TABLE if not EXISTS Edits(...
# -*- coding: utf-8 -*- """Exercise 3. Split the dataset based on the given ratio. """ import numpy as np def split_data(x, y, ratio, seed=1): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # *************************************************** # INSERT YOUR CO...
""" 재귀 용법(Recursive Call, 재귀호출) - 함수 안에서 동일한 함수를 호출하는 형태 """ """ 예제) 팩토리얼 2! = 1 x 2 3! = 1 x 2 x 3 4! = 1 x 2 x 3 x 4 ... n! = 1 x 2 x 3 x ... x n ~> 규칙 if n > 1: return n * function(n-1) else: return n >> 시간 복잡도 & 공간 복잡도 = factorial(n) 함수는 n-1번의 factorial() 함수를 호출한다. - 일종의 n-1번 반복문을 호출한 것과 동일 - ...
import numpy as np def CalculatePearson(x, y): mean_of_x = np.mean(x) mean_of_y = np.mean(y) x_n = x - mean_of_x y_n = y - mean_of_y return np.mean(x_n * y_n)/(np.std(x) * np.std(y)) def test(): x = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3] y = [10, 25, 17, 11, 13, 1...
''' Created on Jan 6, 2017 @author: stephenkoh ''' import mingus.core.intervals as intervals key = str(input('Please enter a key: ')) note = str(input('Please enter a note: ')) third = intervals.third(note, key) fifth = intervals.fifth(note, key) print(note, third, fifth)
x = str(input("enter the value:")) x =x.casefold() rev = x[::-1] print (rev) if rev==x: print("this is palindrome") else: print("this is not palindrome")
def allFibs(n): fibs = [None] * n for i in range(n): print "{}th fib {}".format(i+1, fib(i, fibs)) def fib(n, fibs): if n == 0: return 0 elif n == 1: return 1 elif fibs[n] is not None: return fibs[n] fibs[n] = fib(n-1, fibs) + fib(n-2, fibs) return fibs[n]...
#! /usr/bin/env python def fib(n): a, b = 0, 1 while a<n: print a, a, b=b, a+b fib(2000) def fib2(n): result = [] a, b = 0, 1 while a<n: result.append(a) a, b= b, a+b return result print 'next line: ' for x in fib2(1000): print x def parrot(voltage, state='a stiff', action='voom', type='Norwegian...
#! /usr/bin/env python def fib(n): result=[] a, b=0, 1 while a<n: result.append(a) a, b=b, a+b return result def fib2(n): result = [] a, b=0, 1 while b<n: result.append(b) a, b=b, a+b return result
import tweepy # best Twitter API (in my opinion!) import random # for selecting a random sentence from nltk.corpus import wordnet # wordnet is a word database and has so many capabilities! We use it for finding if a word a usually a noun, adjective, verb # wordnet does not have some words, including swear words :( fr...
import sys class AugmentationType: def __init__(self, aug_type, sigma=0.1): self.type = aug_type self.sigma = 0 self.noise=False if aug_type == 0: self.type_text = "Augmentation Type: No Augmentation" elif aug_type == 1: self.type_text = "Augmentation ...
# read the input char = input() List = ["a","e","i","o","u","A","E","I","O","U"] # solve the problem count = 0 for i in char: if i in List: count += 1 # output the result print(count)
import sys import random def read_restaurant(restaurants): """Restaurant rating lister.""" # restaurant_roster = open(filename) # for each line # right strip # split @ colon # put right into dictionary # index[0] will be key # index[1] will be value! for establishment, rating i...
#!/usr/bin/python import sys; import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np samples = [] for line in sys.stdin: fields = line.split( ' ' ) delay, throughput = float(fields[ 0 ]), float(fields[ 1 ]) samples.append( [ delay, throughput ] ) samples = np.matrix( s...
import random class TheVote: def __init__(self): pass def findMajority(self, voteLyst): '''returns eliminated person based on votes''' votes = {} highestVotes = [] highestVoteCount = 0 for vote in voteLyst: votes[vote] = votes.get(vote, 0) + 1 ...
def func(n, A, B, C): if n == 1: print(A + " -- >" + B) else: func(n - 1, A, C, B) print(A + " -- >" + B) func(n - 1, C, B, A) func(3, A='A', B='B', C='C')
def check_0_max(value, max_value): """ Check if the value in range(0, max_value) and if it is not change to closest(0 or max_value) :param value: integer or float :param max_value: integer or float :return: 0 or max_value or value """ if value not in range(0, max_value): if value <= ...
#Organizza con un dizionario la rubrica con i nomi delle persone e i rispettivi numeri telefonici. #Fornito poi il nome della persona, il programma visualizza il suo numero di telefono oppure un messaggio nel caso la persona non sia presente nella rubrica. rubrica = {"Marco":"343 897 3922", "Filippo":"375 542 9054", "...
a=10 b=20 m=15 y=a+b print(y) m +=10 print(m) m -=10 print(m) m *=10 print(m) m /=10 print(m) m %=10 print(m) m **=10 print(m) m //=10 print(m)
# Accessing 2D Array using While Loop from numpy import * a = array([[10, 20, 30, 40], [50, 60, 70, 80]]) n = len(a) i = 0 while i<n: j=0 while j<len(a[i]): print('index',i,j,"=",a[i][j]) j+=1 i+=1 print()
#!/bin/python3 # go to https://trinket.io/embed/python/33e5c3b81b#.W56BiV5KjIV alphabet = 'abcdefghijklmnopqrstuvwxyz' key = int(input('Please enter a key number: ')) #you can use negative numbers to go in reverse newmessage = '' message = input('Please enter a message: ') #the message that is created for character...
fruit_list = ["apple", "orange", "grape", "banana", "avocado"] if "grape" in fruit_list: print("Yes, grape is in the fruit list.") else: print("No, grape is not in the fruit list.") if "strawberry" in fruit_list: print("strawberry is in the fruit list.") elif "orange" in fruit_list: print("orange is i...
a = 23 b = -23 def abs(n): if n < 0: n = -n return n if abs(a) == abs(b): print("The absolute value of", a, "and", b, "are equal") else: print("The absolute value of", a, "and", b, "are not equal")
username = input("Username: ") password = input("Password: ") command = str() name = str() code = str() while command != "lock": command = input("Command: ") while name != username: name = input("Username: ") while code != password: code = input("Password: ") print("Unlocked")
# Import os and cvs import csv import os import numpy as np budget_csv = os.path.join("Resources", "budget_data.csv") # Open and read csv with open(budget_csv, "r") as csv_file: csv_reader = csv.reader(csv_file, delimiter = ",") # Skip the header csv_header = next(csv_reader) # Find the total number of ...
class Problem(object): """Representation of a problem""" def __init__(self, initial, goal): self.initial = list(initial) self.goal = list(goal) def actions(self, state): """Returns possible actions on current state""" actions_list = [] index_of_blank_space = state.i...
def fibbo(n): a = 0 b = 1 for i in range(n): a = b b = b + a print(a, '/n') return b num = int(input('enter the number value-->') print(fibbo(num))
import sys from sys import stdout as std """ Minimax algorithm to build an tic tac toe AI ----------------------------------------------- computer represents X and the player is O so, we are maximiser and the player is minimiser """ class board: def __init__(self): self.positions = [] self.movesL...
def Main(): print "\nFor loop counting up" for x in range(1,5): print "%d" % (x) print "\nWhile loop counting down" while x != 0: print "%d" % (x) x -= 1 if __name__ == "__main__": Main()
f=open('form1.txt','a') f.write("\t\t\t\t\tWelcome To Form Registration\n") f.write("\t\t\t\t\t----------------------------\n") f.write("\t\t\t\t\t----------------------------\n\n\n") n=int(input("Enter no of Students :")) for i in range(1,n+1) : print("Enter The student Detail : ",i) f.write("Student Details :");...
class Test: def __init__(self,a,b): self.a=a self.b=b def add(self,a,b): c=self.a+self.b return c p=Test(10,20) print(p.a) print(p.b) q=p.add(p.a,p.b) print("sum =" ,q)
'''n=int(input()) for i in range(n): s=input() for i in range(s): p=set(s) print(p) ''' d= int(input()) a=[] for i in range(d): b=input().split() a.append(b) for i in range(d): print(set(a[i]))
with open('abc.txt','w') as f: f.write("\nAnji\n") f.write("Aj\n") f.write("AWS") # print(10/0) if exception occurs then also file is closed automatically; print("Is Closed :",f.closed) print("Is Closed :",f.closed) """ o/p: Using With Statement: Is Closed : False Is Closed : True """
p1=int(input("enter a no 1\n")) p2=int(input("enter a no 2\n")) p3=int(input("enter a no 3\n")) p4=int(input("enter a no 4\n")) p5=int(input("enter a no 5\n")) i=(p1+p2+p3+p4+p5)/5 if(i>=60): print("first division\n") elif(i>45 and i<60): print("second division") elif(i<45 and i>33): print("thrid division\n") ...
from collections import defaultdict d=defaultdict(str) d['e']=1 d['b']=2 d['c']=3 d['d']=4 print(d) ''' o/p: defaultdict(<class 'float'>, {'a': 1, 'b': 2, 'c': 3, 'd': 4}) '''
d= int(input()) a=[] for i in range(d): b=input().split() a.append(b) for i in range(d): print(a[i]) ''' d= int(input()) a=[] b=input().split() #a.append(b) print(b) 0/p:-= 1 2 3 4 1 2 3 5 132 4 4 4 5 5 6 ['1', '2', '3', '4'] ['1', '2', '3', '5'] ['132', '4', '4'] ['4', '5', '5', '6'] anji ''' print("{}".fo...
print("Enter an age not less tha 10") a=int(input("")) if a>=10 : raise NameError("Not Valid") #//Error hai pta nahi
from collections import deque q=int(input()) d=deque() for i in range(q): m,n=input().split() if(m=='append'): d.append(int(n)) print(d[i]) elif(m=='pop'): d.pop(int(n)) print(d[i]) elif(m=='appendleft'): d.appendleft(int(n)) print(d[i]) ...
'''def swap_case(s): l=len(s) for i in range(l) : if(s[i]>='a' and s[i]<='z'): s[i]=chr(ord(s[i]) - 32); elif(s[i]>='A' and s[i]<='Z'): s[i]=chr(ord(s[i])+32); str = ''.join(s) return str if __name__ == '__main__': s = input() result = swap_case(s) ...
str1=input("Enter a string ") n=len(str1); # string lenght= lenght(string) str=list(str1) for i in range(n) : if(str[i]>='a' and str[i]<='z'): str[i]=chr(ord(str[i]) - 32); elif(str[i]>='A' and str[i]<='Z'): str[i]=chr(ord(str[i])+32); str = ''.join(str) print(str)
''' def print_formatted(n): for i in range(1,n+1): print(i,end=' ') print(oct(i).lstrip('0o'),end=' ') print(hex(i).lstrip('0x'),end=' ') print(bin(i).lstrip('0b'),end='\n') if __name__ == '__main__': n = int(input()) print_formatted(n) ''' #DCS hai def print_formatted(n): ...
class ArrayQueue: DEFAULT_CAPACITY = 10 def __init__ (self): self._data = [None] * ArrayQueue.DEFAULT_CAPACITY self._size = 0 self._front = 0 self._back = 0 def len (self): return self._size def is_empt...
import abc from itertools import chain class RollingObject(metaclass=abc.ABCMeta): """ Baseclass for rolling iterator objects. The __new__ method here sets appropriate magic methods for the class (__iter__ and __init__) depending on window_type. All iteration logic is handled in this class. ...
#count of number of words and letters wc ={} ltr = {} '''this code list the count of number words and letters in the goven text file''' with open("test.txt", 'r') as fout: output = fout.read().lower() #print(output) new = output.split() def wl_count(): #number of words for words in new: ...
def PigLatin(s): vowels = ['a', 'e', 'i', 'o', 'u'] output = [] count = 1 new = s.lower().split() print(new) for word in new: if word[0] not in vowels: #case 1: remove first letter and add "ma" word = word[1:] new_word = word + "ma" else: ...
import pygame #se crea la clase para los button para los botones class button(pygame.sprite.Sprite):#se crea la clase para los botones def __init__(self,pic1,pic2,x,y):#se define cada boton con dos imagenes y las coordenadas self.unselected_pic=pic1#se define como se vera la imagen sin seleccionar self.selected_p...
# -*- coding: utf-8 -*- """ Created on Sun Dec 6 18:42:31 2015 @author: zhihuixie """ import pandas as pd def ranks(rate_dict): """ input as a dictornary, key as movie id and name, values as calculated parameters of rating """ sorted_dict = sorted(rate_dict, key = lambda x: rate_dict[x], reverse...
#import smbus for i2c communications import smbus import time #import the chip library import bme280 # Get I2C bus, this is I2C Bus 1 bus = smbus.SMBus(1) #kwargs is a Python set that contains the address of your device as well as desired range and bandwidth #refer to the chip's datasheet to determine what values you ...
# -*- coding: utf-8 -*- """ Created on Thu Apr 23 21:42:35 2020 @author: Siddharth """ import pandas as pd import numpy as np from matplotlib import pyplot as plt from math import sqrt #import os #x=os.getcwd() rf_data=pd.read_csv(r'C:\Users\Siddharth\Desktop\BITS\3 2\DM\project\Sub_Division_IMD_2017.csv...
## Question 1 ## What would be the output of the following code? my_dict = {'a':[0, 1, 2, 3], 'b':[0, 1, 2, 3], 'c':[0, 1, 2, 3], 'd':[0, 1, 2, 3]} i = 0 output = [] for key in my_dict: output.append(my_dict[key][i]) i += 1 print(output) # [0,1,2,3] ## Practice Exercise 1 Solution def smallest_positive(in_li...
#!/usr/bin/env jython """ This script is a helper tool for taking a group of ciphertexts, guessing what the plaintext is, and checking to see if any of the ciphertexts match that plaintext. """ import argparse import vigenere def main(): # Get arguments from the command-line. parser = argparse.ArgumentParser( ...
# SORT function sorts the data permanently cars =['bmw','audi','toyota','subaru','Audi','BMW'] cars.sort() print(cars) cars.sort(reverse = True) print(cars) # Sorting a List Temporarily with sorted() Function cars =['bmw','audi','toyota','subaru','Audi','BMW'] print("Here is the original list:") print(cars) print("\n...
# -*- coding: utf-8 -*- import numpy as np class Punto(): """Almacena la posicion (x,y,z) en un tiempo t de una particula. """ def __init__(self,x,y,z,t): self.x=x self.y=y self.z=z self.t=t def imprimir(self): print(int(self.t)+' ('+str(self.x)+','+str(self.y)+'...
from collections import Counter def count_words_fast(text): #counts word frequency using Counter from collections text = text.lower() skips = [".", ", ", ":", ";", "'", '"'] for ch in skips: text = text.replace(ch, "") word_counts = Counter(text.split(" ")) return word_counts # >...
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.start = None def insertLast(self,value): newNode = Node(value) if self.start == None: self.start = newNode else: tem...
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): cur_node = self.head while cur_node != None : print(cur_node.data) cur_node = cur_node.next ...
# -*- coding: utf-8 -*- ## THESE PROGRAMS ALLOW YOU TO CALCULATE ## THE ENERGY OF A LIQUID, PARTICULE ## AND MAYBE SOME OTHERS THINGS NOT CODED YET ##LICENSE : DO WHAT THE FUCK YOU WANT ## ./particle.py argv1 argv2 --> argv1: speed particle && argv2: particle's mass import sys,math args=len(sys.argv) if args != 3: ...
# -*-coding:utf-8-*- import sys #για την επανάληψη του προγράμματος play = True while play == True: import math num = 1000001 #πλήθος φορών που ο αριθμός διαιρείται με το 2: pl2 = 0 #έλεγχος while num > 1000000 or num < 1: num = int(raw_input("Δώστε έναν αριθμό απο το 1 μέχρι το 1000000:...
class LoanCaculator(): def __init__( loan, time): self.loan = loan if time = "1": self.time = 3 elif time = "2": self.time = 5 else time = "3": self.time = 20 def get_total_interests(): total_interests = self.loan * self.get_interests_r...
Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:18:16) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> a=int(input("Enter integer 1:")) b=int(input("ENTER INTEGER 2 :")) print("Addition of integers : ",a+b) print("Subtraction of integers : ",a-b)...
#!/usr/bin/env python3 import sys import os # prvo sistemskite i se ostava 2 mesta megju import od razlicen tip def main(): if len(sys.argv) > 1: for filename in sys.argv[1:]: text_stats = stats(filename) try: print(" {} {} {} {}".format(*text_stats)) ...
#!/usr/bin/env python3 import sys import os for i in range(1,len(sys.argv)): filename = sys.argv[i] with open(filename, "r") as file: book = file.read() lines = book.splitlines() words = book.split() chars = os.path.getsize(filename) print(len(lines), len(words), chars, ...