text stringlengths 37 1.41M |
|---|
# Standard library imports.
import optparse
import shlex
def magic_fwrite(interpreter, parameter_s=''):
""" Write the string representation of a variable out to a file.
%fwrite myvar myfile.txt
Usually, simply str(myvar) will be the string that gets written out. Unicode
strings will be encoded to... |
"""A queue that works on a ticketing system.
Classes:
TicktedQueue -- A FIFO queue with a ticketing system
"""
#*****************************************************************************
# Copyright (C) 2005 Brian Granger, <bgranger@scu.edu>
# Fernando Perez. <fperez@colorado.edu>
... |
def fib(num):
arr = [0,1]
for x in range(2,num+1):
arr.append(arr[x-1]+arr[x-2])
return arr
if __name__ == "__main__":
print(fib(int(input("Put any num bigger than 1: ")))) |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties as FP
from ..postprocessors.units import get_unit_converter
def plot_convergence(dataframe, units=None, final_error=None, ax=None):
"""Plot the forward and backward convergence.
The input could be the resu... |
import sys
import pandas as pd
SPLITTER = "!!!"
'''
Read the questions from the given filename
:param: (str) filename: the given filename
'''
def readQuestions(filename):
try:
# Reading the file
with open(f'../questions_from_books/{filename}', 'r') as readFile:
... |
import nltk
MAX_TITLE_LENGTH = 50
'''
Generating title from a given text
:param: (str) text: the given text
:return: (str) title: generated title
'''
def generateTitleFromText(text):
# Splitting into the sentences
sentences = nltk.sent_tokenize(text)
# TODO: Later it can be u... |
## This solution provides the longest length achievable as well as subsequence itself
## Example--- list = [5,7,4,-3,9,1,10,4,5,8,9,3]
## LIS is -3,1,4,5,8,9
## maximum LIS length is 6
list = [5,7,4,-3,9,1,10,4,5,8,9,3]
length = []
nums = []
def LIS(list):
for i in range (0,len(list)):
## Length of one... |
# Expressão Lógica
num = float(input("Digite um número: "))
exp = 1 <= num or num >=10
print(exp)
|
#Operações com numeros inteiros
num = 0
i = 1
cont_par = 0
cont_impar = 0
somapar = 0
somarimpar = 0
for i in range(10):
num = int(input("Digite um número inteiro:"))
resto = num % 2
if resto == 0:
cont_par = cont_par+1
somapar = somapar+num
else:
cont_impar = cont_impar+1
... |
def main():
import sys
import random
import time
from faker import Faker
import names
import gender_guesser.detector as gender
fake = Faker()
print("\n>>Created by SOD<<")
userdefined_file_name=input("\nEnter your desired file name \t")
file_txt=userde... |
import sqlite3
creation_table_str = """
CREATE TABLE IF NOT EXISTS TEMPERATURE (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sensor_id TEXT,
temperature REAL,
datetime TEXT,
location TEXT
);
"""
check_if_table = """
SELECT count(name) FROM sqlite_master WHERE type='table'... |
import unittest
from errors import InvalidInvoiceError, MaximumNumberOfInvoicesReached
from invoice import Invoice
from invoice_stats import InvoiceStats
class TestInvoiceStats(unittest.TestCase):
def test_add_invoice_ok(self):
"""
It should add an invoice to the `InvoiceStats` storage.
... |
import random
import os
import json
def read_settings(filename):
if os.path.isfile(filename):
file = open(filename, 'r')
line = file.readline()
file.close()
if line:
return line.split(';')
return False
def save_settings(filename, user):
file = open(filename, 'w'... |
import numpy as np
import random
import matplotlib.pyplot as plt
n = int(input('Motion number: '))
x, y = 0, 0
history = [(x, y)]
for i in range(0, n):
rad = float(random.randint(0, 360)) * np.pi / 180
x = x + np.cos(rad)
y = y + np.sin(rad)
history.append((x, y))
print(history)
xs = list(map(lam... |
"""
Sort a list in ascending order
Return a new sorted list
- 3 steps:
# Divide: Find midpoint of the list and divide into sublists
# Conquer: Recursively sort the sublists created in previous step
# Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time
"""
# example 1 (Imr... |
# example 1
'''
A
/ \
B C
/ \ \
D E ---> F
'''
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': [],
}
visited = set() # sets don't allow repeated elements
def dfs(visited, graph, node):
if node... |
class Edge(object):
def __init__(self, source, target, data = None):
self._source, self._target, self.data = source, target, data
def __repr__(self):
return "Edge<%s <-> %s>" % (repr(self.source), repr(self.target))
@property
def source(self): return self._source
@property
de... |
def is_matched(e):
l = len(e);
if l%2 == 1:
return False
#l = l/2
#e = list(e)
a = []
b = ['{', '(', '[']
val = ['}', ')', ']']
for i in range(l):
#print 'hi'
#print a, e[i]
if e[i] in b:
a.append(e[i])
elif e[i] in val:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 14 11:42:00 2019
@author: pacew
"""
# A bubble sort app
import numpy as np
import random
def bubblesort(array):
lenght = len(array) - 1
for i in range(lenght):
for j in range(lenght):
if array[j] > array[j + 1]:
array[j], a... |
#!/usr/bin/env python
#codiing=utf-8
import random
import time,threading
'''
线程从threading.Thread继承创建线程
,重写__init__和run()方法
'''
class MyThread(threading.Thread):
def __init__(self,name,urls):
threading.Thread.__init__(self,name=name)
self.urls =urls
def run(self):
print('Current %s is r... |
#! /usr/bin/env python
"""
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no isl... |
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You co... |
"""
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
"""
class Solution:
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:r... |
"""
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();... |
""" This file defines the class Device, which
is basically the type of anything that
attempts to connect to our network
"""
class Device:
def __init__(self, macAddress, name):
self.macAddress = macAddress
self.name = name
def __str__(self):
return "<%s, %s>" % (self.macAddress,... |
# ICS483 Group Project
# Authors: Kekeli D Akouete, Vang Uni A
# Implementing encryption in an application
from tkinter import filedialog
from tkinter import *
from tkinter import messagebox
import os
from MyCipher import MyCipher
# Callbacks to entry fields
def key_callback(event):
ivEntry.focus_set()
def fil... |
a = input()
if (int(a[0])+int(a[1])+int(a[2])) == (int(a[3])+int(a[4])+int(a[5])):
print("молодец")
else:
print("НЕмолодец") |
# Microsoft
# Print the nodes in a binary tree level-wise. For example, the following should
# print 1, 2, 3, 4, 5.
# 1
# / \
# 2 3
# / \
# 4 5
# Tree Traversal
# Pseudocode:
# create class Node function
class Node:
def__init__(self, data):
self.left = None
self.right = None
self.data = dat... |
import time
import sys
def Phone(phone_option):
try:
if phone_option == 1:
s = '''
1. Do you answer the phone in hopes of confronting the root cause of everything happening?
2. Do you send the caller to voicemail and try to reach "911"?'''
for character i... |
# A string is considered to be valid if all characters of the string appear the same number of times.
# It is also valid if he can remove just 1 character at any 1 index in the string, and the remaining characters
# will occur the same number of times. Given a string , determine if it is valid.
# If so, return YES, oth... |
n = int(input())
cnt = 0
for i in range (n):
cnt = cnt + int(int(input()) == 0)
print(cnt) |
import random
rucksack = ['Water flask', 'Cheese', 'Gold coins', 'Handkercheif', 'Tinderbox',
'Scrolls', 'Dagger','Rope','Nuts','Pipe','Tobacco','Wine skin',
'Herbs','Axe']
##function to sort inventory, printout and print number of items
def rucksackupdate():
rucksack.sort()
print(ruc... |
##I wanted to simplify entering it so i print a menu and get them choose coorrsponing number
print ("Choose your type of Pokemon")
print ("For Fire press 1")
print ("For Water press 2")
print ("For Grass press 3")
print ("For Electric press 4")
type = int(input("Make your selection:"))
letter = str(input("Whats the... |
##asking questions to get data
creditScore = int(input("Please enter creditscore 1 -10:"))
addressTerm = int(input("How many months at current address"))
income = int(input("What is the income level (£)"))
loanRequest = int(input("Borrowing amount requested (£)"))
##this is a variable that would go to true if loan ap... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
# 2018-05-23
# Personal Tax Calculator
import sys # 导入系统模块
print(sys.argv) # 打印命令参数
# 异常处理:用户输入的参数必须为单个、正确的薪水!参数的数量不正确、输入小于或等于0、无法转换成整数,都需要打印参数错误提示。
try:
len(sys.argv) == 2 # 参数的个数必须为2(包括参数名词在内)
salary = int(sys.argv[1]) # 薪水等于传入的第一个参数
assert salary > 0 # 输入薪... |
km = int(input('Qual a velocidade de seu carro? em km/h: '))
if km >= 80:
print('Você ultrapassou a velocidade de 80 km/h e foi multado.')
acd = km - 80
mult = (acd * 7)
print('O valor da multa é R$ {} reais.'.format(mult))
|
cont = soma = maior = menor = 0
resp = 'S'
while resp in 'Ss':
num = int(input('Digite um valor: '))
soma += num
cont += 1
if cont == 1:
maior = menor = num
else:
if num > maior:
maior = num
if num < menor:
menor = num
resp = str(input('Quer contin... |
total = 0
num = int(input('Digite um numero: '))
for c in range(1, num +1):
if num % c == 0:# vai ser testado se é divisivel de 1 até a num digitado.
total += 1 #soma a quantidade de vezes que foi dividido com resposta 0
if total == 2: # apenas quando dividido 2 vezes é considerado um numero primo
print... |
print('¨*¨' * 10)
print(f' BANCO NOEMI ')
print('¨*¨' * 10)
while True:
valor = int(input('\nDigite o valor que quer sacar: '))
notas50 = valor // 50
rest = valor - notas50 * 50
notas20 = rest // 20
rest2 = rest - notas20 * 20
notas10 = rest2 // 10
rest3 = rest2 - notas10 * 10
nota... |
#Condição if e else
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 +n2)/2
print('Sua média final é {:.1f}.'.format(m))
if m >= 6:
print('Você foi aprovado, parabéns!')
else:
print('Você foi reprovado, estude para a recuperação.')
#Maneira simplificada
print('... |
print('Você sabe quais são so números pares entre 1 e 50 ?Veja abaixo: ')
for c in range(1+1, 50, 2):
print(c, end=' ')
print('Esses são os números pares.')
|
#Reajuste salarial
sal = float(input('Digite o seu sálario: R$ '))
new = sal * 1.15
print('O seu salário de R${:.2f} reais, com o reajuste de 15% passa a ser de R$ {:.2f} reais.'.format(sal, new))
|
#Calculo da hipotesuna
from math import hypot
cat_op = float(input('Digite o comprimento do cateto oposto: '))
cat_adj = float(input('Digite o comprimento do cateto adjacente: '))
hip = hypot(cat_op, cat_adj)
print('A sua hipotenusa é de {:.2f}'.format(hip))
#Forma mais simples de fazer sem importar bibliotecas
co = f... |
soma = 0
idademaior = 0
nomemaisve = ''
qntmulheres = 0
for c in range(1, 4 +1 ):
nome = str(input('Digite o nome da {}º pessoa: '.format(c))).strip()
idade = int(input('Digite a idade da {}º pessoa: '.format(c)))
sexo = str(input('Qual o sexo biológico da {}º pessoa [M/F]: '.format(c))).strip().upper()
... |
#Analisador de textos
nome = str(input('Escreva seu nome completo: ')).strip()
print(nome.upper())
print(nome.lower())
nome = (nome.split())
Nc = (''.join(nome))
print('O seu nome completo tem {} letras.'.format(len(Nc)))
#print('Seu nome completo tem {} letras'.format(len(nome) - nome.count(' '))) subtraindo os espaço... |
# Devolução de numero inteiro por biblioteca ou de forma simples
from math import floor
num = float(input('Digite um numero: '))
inteiro = floor(num)
print('O número {} tem a parte inteira {}. '. format(num, inteiro))
#Outro metodo
import math
num = float(input('Digite um numero: '))
print('O número {} tem a parte int... |
#!/bin/python3
"""
list: 是python 内置的一种数据类型。list是一种有序集合,可以随时添加或删除其中元素。
"""
# 定义一个空list
list1 = []
print(list1)
classmates = ['Michael', 'Bob', 'Jim']
print(classmates)
# 获取list元素个数
print(len(classmates))
print("classmates[0] is %s" % classmates[0])
print("classmates[1] is %s" % classmates[1])
print("classmates[2] i... |
#!/bin/python3
"""
列表生成式:List Comprehensions
"""
import os
# 求 1-10 的平方
# 循环迭代方式
L = []
for i in range(1, 11):
L.append(i * i)
print(L)
# 列表生成式
[print(x * x, end=" ") for x in range(1, 11)]
print()
# 想获取平方数为偶数的结果
[print(x * x, end=" ") for x in range(1, 11) if x % 2 == 0]
# 使用两层循环
[print(m + n ) for m in 'A... |
"""
Class for background image
"""
import pygame
class Background:
"""
Background for Mario Kart 2D game!
"""
def __init__(self, path: str, x_cor, y_cor) -> None:
"""
Initializes a background.
"""
self.img = pygame.image.load(path)
self.x_cor, self.y_cor = x_co... |
# import nltk
import numpy as np
import matplotlib.pyplot as plt
import operator
import math
# function to read a giveb file and return a sorted list of words and their frequencies
def read_file(filename):
word_dict = {}
fp = open(filename, 'rb')
print('Reading ' + filename)
# count the frequencies of each uniqu... |
def get_guests():
guests = []
name = "something"
while True:
name = raw_input("Who's coming? ")
if name == "":
break
guests.append(name)
return guests
def say(what, guests):
for x in guests:
# print "Hi, {0}".format(x)
print what + ", " + x
d... |
# 스레드를 생성해서 1초마다 "Thread is running!" 문자열을 출력한다
#
# 작성자: 강민석
# 작성날짜: 2017년 3월 19일 (version 1.0)
import time
import threading
class ThreadClass(threading.Thread):
def run(self):
while True:
print("Thread is running!")
time.sleep(1)
workThread = ThreadClass()
workThread.start() |
# 정수 입력 확인 프로그램
# 입력받은 값이 정수인지를 계산해주는 프로그램
#
# 입력: 임의의 숫자 - 정수만 허용
# 출력: 입력받은 숫자
#
# 1. 정수를 입력받을 때까지 계속 입력받음
# 2. 가장 앞에 '+'혹은 '-'기호가 있어도 정수로 취급
# 3. 입력받은 값이 정수일 경우 입력받은 값을 출력하고 종료
#
# 작성자: 강민석
# 작성날짜: 2017년 3월 23일 (version 1.0)
def is_number(str) :
result=False
try :
float(str)
result=2
int(str)
result=1
e... |
#what is faster list or tuple?
#Tuples are allocated in the single block and are immutable and does not require extra storage
#Lists are allocated in double block, one is of fixed length and storage and other is of variable length and storage
tuple1 = (1,2,3,4,5)
print(tuple1)
list1 = [1,2,3,4,5]
print(list1)
list1.a... |
#This is used to write the contents to the file
try:
f = open("E:/Python_Latest_Besant_Technologies/write_example4.txt",'w')
f.write('hello everyone !')
except IOError:
print('can\'t find the file or read')
else:
print('Written the contents to the file')
try:
f = open("E:/Python_Latest_Besant_Te... |
#Constructors are of two types
#Creating Multiple Objects
class Employee:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print("name %s ange age %d"%(self.name,self.age))
emp1=Employee("John",101)
emp2=Employee("David",102)
emp3=Employee("Krithika",900)
... |
#How we remove values from the array
from array import array
a = array('i', [1,2,3,4,5])
print(a)
a.remove(3)
print(a)
|
#Printing the Class Name
class Myclass:
x=5
print(Myclass)
class Myclass:
x=5
obj1=Myclass()
print(obj1.x)
#Usage of the init constructor
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def myfunction(self):
print(self.name)
print(self.age)
p1... |
#-*- coding:utf-8 -*-
#求两个三位数乘积的最大的回文数
def palindrome(n):
temp=str(n)
l=len(temp)
for i in range(0,l/2):
if temp[i] != temp[l-1-i]: # 不能写成if true else false的形式,
return False #因为return一出现就意味着整个函数的
else: #结束,当然循环也只会执行一次
pass
return... |
from math import sqrt
def isPrime(x):
if x==1:
return 0
if x==2:
return 1
if x>2:
for i in range(2,int(sqrt(x))+2):
if x%i==0:
return 0
elif i ==int(sqrt(x)+1):
return 1
def main():
s=0
for i in range(1,1000001):
... |
import csv
def set_menu(x):
with open('menu.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
item=[None]*20
price=[None]*20
i=0
for row in readCSV:
item[i] = row[1]
price[i] = row[2]
i=i+1
return item[x],pri... |
# Find who wins the tournament
# Input array is of the form:[ [homeTeam,awayTeam] ]
# results=[0,0,1] where 0 means home team lost and vice versa
# Print who wins that tournament
def tournamentWinner(competitions, results):
# Write your code here.
winner = ""
tourny_score = {winner: 0}
for i, arr in enume... |
## Dimensionality Reduction
**PCA**
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('Wine.csv')
x = data.iloc[:,0:13].values
y = data.iloc[:,13]
**Splitting the dataset**
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_sp... |
import random
count = 0
heads = 0
tails = 0
while count < 100 :
count += 1
rand = random.randint(1,2)
if rand == 1 :
heads += 1
else:
tails += 1
print("Heads = " + str(heads))
print("Tails = " + str(tails)) |
#Бутолин Александр ИУ7-12
# Для ф-ции Х составить программу вычесления Y
# 0 при x<=-1
# 1 при -1<=x<0
# -1 при 0<=x<2
# 1 при x<=2
try:
x=float(input('Введите значение X: '))
if x<-1:
y=0
if -1<=x<0:
y=1
if 0<=x<2:
y=-1
if x>2:
y=1
print(y)
except ValueError:
... |
from math import *
c1=float(input('Введите начальное значение функции: '))
c2=float(input('Введите конечное значение функции: '))
h=float(input('Введите шаг: '))
n=c1
min=9999999999999
max=-999999999999
while round(n,7)<=c2:
s=n*n*n+n-1
if s<min:
min=s
if s>max:
max=s
n+=h
print()
print... |
# Бутолин Александр ИУ7-12
# Посчитать сумму ряда
from math import *
try:
x=float(input('Ведите значение X: '))
if abs(x)>1:
print('Неправильное значение X')
else:
e=float(input('Введите значение эпсилон: '))
n=int(input('Введите начальное значение для вывода: '))
if n<=... |
#Бутолин Александр ИУ7-12
#Метод парабол для заданного количества разбиений
from math import *
try:
def f(y):
return y*y
a,b=map(float,input('Введите интервал для подсчёта интеграла: ').split())
n=int(input('Введите количество разбиений n: '))
if n%2==0:
h=(b-a)/n
s1=s2=0
... |
# Largest Number formed from an Array
# http://practice.geeksforgeeks.org/problems/largest-number-formed-from-an-array/0
import functools
def comparator(x, y):
xy = x + y
yx = y + x
return int(xy) - int(yx)
if __name__ == "__main__":
# num_cases = int(1)
num_cases = int(input())
results = []
... |
import pandas as pd
structure_number = "Structure Number"
parent_index = "_parent_index"
def reviser(xl_file_name):
df = pd.read_excel(xl_file_name, index_col=0)
df = df[df.groupby(structure_number)[parent_index].transform('max') == df[parent_index]]
df.to_excel("Revised " + xl_file_name)
print("Rev... |
def anagrams(word):
result = []
length = len(word)
anagram = ''
if length <= 1:
result.append(word)
return result
else:
for char in anagrams(word[1:]) :
for element in range (length):
anagram = char[:element]+ word[0:1]+ char[element... |
# Leetcode # 121 : Best Time to Buy and Sell Stock
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
leng = len(prices)
profit = 0
min_price = prices[0]
for i in range(1,leng):
profit = max(profi... |
import numpy
import math
# This function implements an infinite series formula for e, 1/n!
def calculate_e(terms):
array = numpy.arange(terms) # Create a numpy array automatically filled with the terms
e = 0
for term in array:
e += 1/math.factorial(term)
return e
num_terms = ... |
import string
def check_string(file_name, string_to_search):
with open(file_name, 'r') as read_obj:
for line in read_obj:
if string_to_search in line:
return True
return False
def score_word(file_name, string_to_search):
"""Search for the given string in file ... |
def main():
string = input('Enter a string for the program to capitalize sentences: ')
result = capitalize(string)
print(result)
# The capitalize method return a opy of the string
# with the first character of each sentence capitalized.
def capitalize(string):
result = ''
new_sentence = ... |
#!/usr/bin/env python3
import csv
from datetime import date
import datetime
from datetime import timedelta
import pandas as pd
from yahoofinancials import YahooFinancials
"""
Obtain yahoo stock prices and email to nominated email addresses
Program takes stocks as an input and returns prices. Some light analysis
do... |
def printPascal(testVariable) :
# Base Case
if testVariable == 0:
return [1]
else:
line = [1]
# Recursive Case
previousLine = printPascal(testVariable - 1)
for i in range(len(previousLine) - 1):
line.append(previousLine[i] + previousLine[i+1])
line += [1]
return line
testVariable = 5
print(printPasca... |
## O(N*lgN + M*LgM) Time | O(1) Space
def smallestDifference(arrayOne, arrayTwo):
# Ask you interviewer if it's okay to sort the array in place.
# Sometimes, you can't hamper the data.
arrayOne.sort()
arrayTwo.sort()
idxOne = 0
idxTwo = 0
smallest = float("inf")
current = float("inf")... |
#import modules
import os
import csv
#set path for file
pypoll_csv = os.path.join('.','election_data.csv')
#set initial values and list
votes = 0
dict = {}
#open the csv to read
with open (pypoll_csv, newline='') as csvfile:
#specify delimiter and variable that holds contents
csvreader = csv.reader(csvf... |
num = int (input("Enter Number to find its prime or not: "))
for i in range(2, num):
if(num%i) == 0:
print("Its not a prime number")
break
else:
print("Its a prime number")
break
|
#!/usr/bin/env python3
'''
Functions used for loading and finding files for brain analysis.
Authors: Sydney C. Weiser
Date: 2017-07-28
'''
import os
import re
import sys
import time
from subprocess import call
import yaml
from typing import List
def find_files(folder_path: str,
match_string: str,
... |
def read_input():
res = []
with open("input.txt") as inf:
for line in inf:
res.append(line.strip())
return res
def get_num(name):
if name in dict_num:
res = dict_num[name]
else:
res = len(dict_num)
dict_num[name] = res
return res
def Dijkstra(N, S,... |
def fibonacci(n):
b = []
for i in range(n+1):
if i == 0:
b.append(0)
elif i == 1:
b.append(1)
else:
b.append(b[i - 1] + b[i - 2])
# fibonacci(n - 1) + fibonacci(n - 2)
return b
a = int(raw_input(">>> "))
print fib... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# 17 list comprehension problems in python
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# In[2]:
# Example for loop solution to add 1 to each nu... |
# Search for identical data in two dictionaries
dict1 = {
'a' : 'dog',
'b' : 'cat',
'c' : 'guinea pig'
}
dict2 = {
'a' : 'giraffe',
'd' : 'leopard',
'c' : 'guinea pig'
}
# searching for the same keys
k = dict1.keys() & dict2.keys()
print(k)
# searching for the same pairs of keys&values
i = d... |
# The code in week 2 lectur e3 of the MITx 6.00.1x to find the cube root
# of a given number does not work due to syntax and symantic errors.
# Here is how I fixed it. :)
x = int(raw_input("Enter an integer: "))
for ans in range(0, abs(x)+1):
if ans**3 ==abs(x):
if x < 0:
ans = -ans
pri... |
def search(mid):
conv = 0
max_len = len(board)-1
# mid 만큼 휴개소 갯수 탐색
for i in range(max_len):
conv += (board[i+1] - board[i]-1)//mid
return conv
n, m, l = map(int, input().split())
board = list(map(int, input().split()))
left, right = 0, l
board += [left, right]
board.sort()
while left... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
################################################
####### THE CHEATSHEET OF LETTER CODES: ########
# ś (si) = \xc5\x9b
#ą = \xc4\x85
# ź (zi)
#ć (ci) = \xc4\x87
#dź (dzi) =\xc5\xba
################################################
####### THE FUNCTION KASHUBY: #############... |
##
num = [5,9,13,18,23]
num1 = [9,5,18,13,23]
#num
#num1
print(num)
print(num1)
##### Indexes of a list #####
### ###
### 0 1 2 3 4 ###
### 5 9 13 18 23 ###
### -5 -4 -3 -2 -1 ###
### ###
#############################
print(num[2])
print(num1[2])
print(num[0])... |
# Recursion - Calling a function itself
import sys
# By default, the recursive function can be executed only 1000 times
print(sys.getrecursionlimit()) # This will give recursion limit
print(sys.setrecursionlimit(2000)) # Using this, we can overwrite recursion limit
print(sys.getrecursionlimit()) # Checking the r... |
# Example 1
def search(list, n):
i = 0
while i < len(list):
if list[i] == n:
return True
i = i + 1
return False
# This is list
list = [2, 5, 9, 13, 18]
# This is what we need to search
n = 20
if search(list, n):
print("Found the number")
else:
print("Number not fou... |
# Functions - Functions are objects in Python
# defining a function
def greet(): # simple function
print("Hello")
print("Good Morning")
def add(x, y): # argument based function
z = x + y
print(z)
def add1(x, y): # argument based function with return
z = x + y
return z
def add_sub(x, y)... |
a = 5
b = 0
# Example 1
try:
print(a/b)
except Exception:
print("A number cannot be divided by zero")
# Example 2
try:
print(a/b)
except Exception as e:
print("A number cannot be divided by zero:", e)
# Example 3
a = 5
b = 2
try:
print(a/b)
k = int(input("Enter the value: "))
except Exception... |
"""
The main purpose of having modules is to split the code into multiple files or multiple blocks depends upon
the need instead of maintaining in a single file which eventually leads to confusion
"""
def add_new(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, ... |
import os
# Open a file
#fo = open(r"D:\Installations\python-workspace\files_learn\foo.txt", "r+")
os.remove("foo.txt")
os.remove("oof.txt")
fo = open("foo.txt", "w+")
fo.write("Amazing.. \nZing Zing\n")
str = fo.read(10)
print ("Read string is:", str)
# Check current position
position = fo.tell()
print ("Current fi... |
file = open('mydata.txt', 'r')
file1 = open('newfile.txt', 'w')
# writes data to the file (ensure the file is created)
file1.write("Something ")
file1.write("good gonna happen. ")
# a - indicates append to existing file
file1 = open('newfile.txt', 'a')
file1.write("Good for every one")
|
n = int(input("Ingresa un numero: "))
acc = 1
i = 1
while i <= n:
acc = acc*i
i += 1
print("El factorial es: " + str(acc))
# Alternative: recursion |
##Dado un monto en soles, conviértelo a dólares y a euros.
monto = input('Ingresa un monto \n')
monto = float(monto)
monto_dol = monto*3.30
monto_eur = monto*3.88
print("El monto ingresado en dolares es: "+str(monto_dol) +" \n")
print("El monto ingresado en euros es: "+str(monto_eur)) |
n = int(input("Ingresa el primer numero: "))
m = int(input("Ingresa el segundo numero: "))
while n <= m:
if n%2 == 0:
print(n)
n += 1 |
monto = input("Ingresa el monto: ")
cambio_dolares = 3.2
cambio_euros = 4.7
a_dolares = cambio_dolares * float(monto)
a_euros = cambio_euros * float(monto)
print("Tu monto en dolares es: {0}".format(a_dolares))
print("Tu monto en euros es: {0}".format(a_euros))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.