text stringlengths 37 1.41M |
|---|
position = -1
def search(list,n):
i = 0
while i < len(list):
if list[i] == n:
globals()['position'] = i
return True
i = i + 1
return False
list = [5, 8, 4, 6, 9, 2]
n = 9
if search(list,n):
print("I Found", n, "in the List at Position", position+1)
else:
print... |
# We need install numpy in order to import it
import numpy as np
# input two matrices
mat1 = ([1, 2, 3],[4, 5, 6])
mat2 = ([7, 8],[9, 10],[11, 12])
# This will return dot product
res = np.dot(mat1,mat2)
# print resulted matrix
print(res)
|
class Student():
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __sub__(self, other):
m1 = self.m1 - other.m1
m2 = self.m2 - other.m2
s3 = Student(m1, m2)
return s3
feed = Student(
m1=int(input("Enter the first value :")),
m2=int(input("Enter... |
a = int(input("Enter a number to find the square..."))
f = lambda a : a * a
result = f(a)
print(result) |
#! /usr/bin/python
import os
import sys
def tree(depth,dir):
files = sorted(os.listdir(dir))
cnt = 0
for file in files:
fullpath = dir + "/" + file
cnt = cnt + 1
if os.path.isdir(fullpath):
if len(files) == cnt:
print "%s`-- %s"%(depth,file)
tree(depth + " " ,fullpath)
... |
"""
This module implements a multi-layer perceptron (MLP) in NumPy.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from modules import *
class MLP(object):
"""
This class implements a Multi-layer Pe... |
class A1Z26:
# Protected:
def _A1Z26_decrypt(cistring):
string = ""
# Split string at " "
data = cistring.split()
for char in data:
if(ord(char) > ord('z')):
raise ValueError("Larger than 26")
break
char = chr(int(char) + ... |
my_set = {1, 2, 3, 4, 5} # type: set
print(my_set)
my_set2 = {1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 1}
print(my_set2)
cond1 = my_set is my_set2
print(cond1) # False
cond2 = 10 in my_set
print(cond2)
print(len(my_set)) # 5
print(len(my_set2)) # 5
|
dct = {
'key1': "val1",
'key2': "val2",
'key3': "val3",
'key4': "val4",
'key5': "val5"
}
print(dct.keys())
print(dct.values())
for k in dct:
print(k, dct[k])
for v in dct.values(): # default is dct.keys
print(v)
for ke, va in dct.items():
print(k, v)
|
res1 = range(10000)
res2 = list(res1)
print(res1)
print(res2)
print(res1.__sizeof__())
print(res2.__sizeof__())
lst = [1, 2, 3]
x = iter(lst)
print(next(x))
print(next(x))
print(next(x))
for value in range(5, 10, 2): # from 5 to 10, 2 by 2
print("*", value)
# another example
start = 0
stop = 100
step = 20
fo... |
#List comprehension exercise
#Use a list comprehension to make a list containing tuples (i, j) where `i`
#goes from 1 to 10 and `j` is corresponding to `i` squared.
#for i in range (1, 11):
# j = i * i
# print(i,'*', i, '=', j)
w = [(i, i * i) for i in range (1, 11)]
print(w) |
name = 'Artem'
day = 'Saturday'
last_name = 'Selivanov'
str = 'Good day {}! {} is a perfect day to learn some python.'
print(str.format(name,day))
print(f'Good day {name}! {day} is a perfect day to learn some python.')
print(name,last_name, sep=' ')
a = 6
b = 2
print(a + b)
print(a - b)
print(a / b)
print(a * b)
print(... |
# Doggy age
# Create a class Dog with class attribute `age_factor` equals to 7. Make __init__() which takes values for a dog’s age.
# Then create a method `human_age` which returns the dog’s age in human equivalent.
class Dog:
age_factor = 7
def __init__(self, DogsAge):
self.Dogs_Age = DogsAge
d... |
# Task 1
# A Person class
# Make a class called Person. Make the __init__() method take firstname,
# lastname, and age as parameters and add them as attributes.
# Make another method called talk() which makes prints a greeting from the person containing,
# for example like this: “Hello, my name is Carl Johnson and I’m ... |
kilometres = float(input("Enter Kilometres to be converted to miles: "))
miles = (kilometres/1.609)
print("Kilometres converted to miles are", miles)
|
"""
Part 1: Discussion
1. What are the three main design advantages that object orientation
can provide? Explain each concept.
Abstraction -
Encapsulation -
Polymorphism -
2. What is a class?
3. What is an instance attribute?
4. What is a method?
5. What is an instance in object orientation?
6. How... |
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
from sys import argv
def read_fl... |
# Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
input_str = input("Введите список: ")
input_list = [int(el) for el in input_str.split() if el.isdigit()]
result = [input_list[index] for index in range(1, len(input_list)) if input_list[index] > inpu... |
# Реализовать функцию, принимающую несколько параметров,
# описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон.
# Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой.
def data_represent(**kwargs):
"""
Функ... |
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв
# и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в... |
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369
multiplier = 3
number_str = ""
while not number_str.isdigit():
number_str = input("Введите число: ")
number = int(number_str)
numbers = []
numbers.append(number)
while len(numbers) ... |
def brute_force_twoSum(A, target):
for i in range(len(A)-1):
for j in range(i+1, len(A)):
if A[i] + A[j] == target:
print(A[i], A[j])
return True
return False
def hash_table(A:list, target:int):
ht = dict()
for i in range(len(A)):
if A[i] in... |
"""so there is a trik/theorem to fast way to find how many divisors
1. find prime factors
2. add to powers +1
3. multiply powers = answer
"""
def is_prime(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return True
# This is checked so that we can skip
# mid... |
def k_i_j(i, j):
i += 1
j += 1
GRID = [[1 for x in range(0, j)] for x in range(0, i)]
for n in range(1, len(GRID)):
for k in range(1, len(GRID[0])):
GRID[n][k] = GRID[n-1][k] + GRID[n][k-1]
print(GRID[i-1][j-1])
k_i_j(20, 20)
# another answer
from math import fa... |
import unittest
from Calculator import Calculator
class MyTestCase(unittest.TestCase):
def test_instantiate_calculator(self):
calculator = Calculator()
self.assertIsInstance(calculator, Calculator)
def test_results_property_calculator(self):
calculator = Calculator()
self.ass... |
#!/usr/bin/env pypy
import sys
# clean = lexicographically the smallest, and the shortest
# OR no possible moves can be made
# thus, if the string cant be cleaned when theres no possible actions left
# for every pairing of s_i = "1" and s_i+1 = "0", there are 2n actions possible
def main():
n = int(input())
fo... |
from collections import defaultdict
def addEdge(graph, u, v):
graph[u].append(v)
def generate_edges(graph):
edges = []
for node in graph:
for neighbour in graph[node]:
edges.append((node, neighbour))
return edges
def find_path(graph, start, end, path =[]):
path += [star... |
import random
class Code:
"""The secret code to be guessed in the game. The responsibility of Code is to
generate the new code and do guess checking against player guesses.
Stereotype:
Service Provider, Information Holder
Attributes:
_code (int): The Games Secret Code
_ga... |
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(1, 1, 1, polar=True)
def mapr(r):
"""Remap the radial axis."""
return 90 - r
r = np.arange(0, 90, 0.01)
theta = 2 * np.pi * r / 90
ax.plot(theta, mapr(r))
ax.set_yticks(range(0, 90, 10)) # Define the yticks
ax.set_yticklabel... |
board = {'1h': 'bking', '6c': 'wqueen',
'2g': 'bbishop', '5h': 'bqueen', '3e': 'wking', '16g': 'wbishop'}
#this is the main function that checks if the chess field is valid
def is_valid_chess_board(board):
POSSIBLE_FIELDS = determine_possible_fields()
print(POSSIBLE_FIELDS)
used_fields = list(board.keys(... |
# def soma(a,b):
# c = a + b
# return c
# x = int(input("Digite: "))
# y = int(input("Digite: "))
# a = soma(x,y)
# print(a)
def maiorIdade(idade):
if idade >= 18:
return True
else:
return False
id = int(input("Digite sua idade: "))
a = maiorIdade(id)
if a == True:
... |
#num1 = int(input("Digite um número inteiro: "))
#num2 = int(input("Digite outro número inteiro: "))
#print("O primeiro número é ", num1, " e o outro é ", num2)
#num3 = int(input("Digite um número: "))
#print("Seu número é ",num3, ", seu antecessor é ",num3-1," e seu sucessor é ",num3+1)
#num4= float(input("Digi... |
''' Module that provides classes for use with lat lon coordinates.
module methods:
conversions to decimal and nmea formats
convertToDecimal()
convertToNmea()
classes:
LatLon - for defining lat/lon coordinates
'''
import numpy as N
import latlonUTM
# module methods.
def __convertToDecimal(x):
''' Converts a... |
#!/usr/bin/python3
import sqlite3
import os
from vars import db_name
if os.path.exists(db_name):
os.remove(db_name)
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("""
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
notification_label TEXT NOT NULL UNIQUE
);
""")
c.e... |
"""
O funcionário chamado Carlos tem um colega chamado João que recebe um salário que equivale a um terço do seu salário.
Carlos gosta de fazer aplicações na caderneta de poupança e vai aplicar seu salário integralmente nela, pois está
rendendo 2% ao mês. João aplicará seu salário integralmente no fundo de renda fix... |
"""
Faça um programa que some todos os números naturais abaixo de 1000 que são múltiplos de 3 e 5.
"""
soma = 0
for n in range(0, 1001):
if n % 3 == 0 and n % 5 == 0:
soma += n
print()
print(f'A soma dos números naturais abaixo de 1000 que são múltiplos de 3 e 5 é: {soma}')
|
"""
Faça um programa que calcule o terno pitagórico a, b, c, para o qual a + b + c = 1000.
Um terno pitagórico é um conjunto de três números naturais a, b, c, para qual:
a*a + b*b = c*c
Por exemplo:
3*3 + 4*4 = 9 + 16 = 25 = 5*5
"""
print('Os ternos pitagóricos cuja a soma é igual a 1000 são: ')
for a in rang... |
"""
Escreva um algoritmo qu eleia um número inteiro entre 100 e 999
e imprima na saída cada um dos algarismos que compõem o número.
"""
from time import sleep
num = input('Digete um número entre 100 e 999: ')
while int(num) < 100 or int(num) > 999:
print('Número inválido!')
num = input('Digete um nú... |
"""
Faça um programa que leia um número inteiro positivo par N
e imprima todos os números pares de 0 até N, em ordem decrescente.
"""
from time import sleep
num = int(input('Digite um número inteiro par positivo: '))
while num == 0 or num < 0 or num % 2 != 0:
print('Número inválido!')
print('Digit... |
"""
Se os números de 1 a 5 são escritos em palavras: um, dois, três, quatro, cinco, então há 2+4+4+6+5 = 22 letras
usadas no total.
Faça um programa que conte quantas letras seriam utilizadas se todos os números de 1 a 1000 fossem escritos em palavras.
OBS: Não conte espaços ou hífens.
"""
numeros = {0: 'zero... |
"""
Faça um programa que leia um número inteiro positivo N e calcule a soma dos n primeiros números naturais.
"""
num = int(input('Digite um número positivo:'))
soma = 0
c = 0
while num < 0:
num = int(input('Digite um número positivo:'))
print('A soma dos números:', end=' ')
for n in range(1, num):
... |
friends=['Andrey', 'Ilya', 'Vlad']
print('Hello',friends[0],'! Come to the meeting at 5.')
print('Hello',friends[1],'! Come to the meeting at 5.')
print('Hello',friends[2],'! Come to the meeting at 5.')
print(len(friends))
|
nums=[]
for i in range(1,11):
nums.append(i**3)
print(nums)
print("\nThe irst three items in the list are:")
print(nums[0:3])
print("\nThe items from the middle of the list are:")
print(nums[4:7])
print("\nThe last three items in the list are:")
print(nums[-3:])
|
#!/usr/bin/python
import time
keepRunning = True
updates=[]
def runLoop():
while(keepRunning):
for u in updates:
u()
class foo:
def __init__(self,x=0):
self.x=x
def update(self):
print self.x
self.x+=1
f=foo()
g=foo(2)
|
class Simple:
def __init__(self,str):
print "Inside the Simple constructor"
self.s = str
#two methods
def show(self):
print self.s
def showMsg(self,msg):
print msg+":",
self.show()
if __name__ == "__main__":
x = Simple("constructor argument")
# if there is no "()" behind show there is n... |
import math
def isPrime(num):
if num<=1:
return False
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
return False
return True
def factors(num):
# Assume minmum num is 1
if num <=1:
yield 1
for i in range(2,int(math.sqrt(num))+1):
if num %... |
#!/usr/bin/python
''' module showing how doctests can be included with source code
each '>>>' line is run as if in a python shell,and counts as a test.
the next line,if not '>>>'is the expected output of the previous line.
if anything doesn't match exactly (including trailing spaces),the test
fails'''
def multiply(a... |
class Solution:
# @param s,a string
# @param dict, a set of string
# @return a boolean
def wordBreak1(self,s,dict_):
if len(s) == 0:
# this judgement is only used when input string s is empty string
# assume there is no empty string '' in dict_
if s in dict_:
... |
class base(object):
"""base class """
def __init__(self,name):
self.name = name
def printest(self):
print "base class:",self.name
class subclass1(base):
"""sub class 1"""
def printest(self):
print "sub class 1",self.name
class subclass2(base):
"""sub class 2"""
def ... |
def divisors(n):
i = 1
result = 0
while (i * i)<n:
if (n%i)==0:
result += 2
i += 1
if (i * i) == n:
result += 1
return result
def test_divisors():
a = 36
print divisors(a)
if __name__ == '__main__':
test_divisors()
|
import random
def Guess_the_Number():
"""
Palyer must guess random number
:return: "You win!"
"""
random_number = random.randint(1, 100)
print("Guess number 1 - 100.")
while True:
user_number = input("Your number: ")
try:
# if input isn"t int() print exception
i... |
# This program will find the lowest, highest, total and average of 20 numbers
# Keymoni Sakil-Slack
# sakilslack_M3P1
# 02-26-2019
def getNums():
mylist = []
for i in range(20):
num = int(input("Enter number #" + str(i+1)+": "))
mylist.append(num)
return mylist
def getHigh(list... |
#!/usr/bin/python3.4
def main():
a, b = 1, 2
fib, even_fib = [], []
while(a < 4000000 and b < 4000000):
if(a not in fib):
fib.append(a)
if(a % 2 == 0):
even_fib.append(a)
if(b not in fib):
fib.append(b)
if(b % 2 == ... |
#!/usr/bin/env python
# coding: utf-8
# # Numpy_Assignment_2::
# ## Question:1
# ### Convert a 1D array to a 2D array with 2 rows?
# #### Desired output::
# array([[0, 1, 2, 3, 4],
# [5, 6, 7, 8, 9]])
# In[2]:
import numpy as np
array1 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
array1.reshape(2,5) # con... |
import math
def isString(x):
try:
y = str(x)
return True
except ValueError:
return False
def isInteger(x):
try:
y = int(x)
return True
except ValueError:
return False
def isFloat(x):
try:
y = float(x)
return True
except ValueError... |
# Disciplina: Probabilidade e Estatística
# Aluno: gabriel rodrigues da silva
# Lista 4
a = int (input('Digite o valor do primeiro ângulo: '))
b = int (input('Digite o valor do segundo ângulo: '))
c = int (input('Digite o valor do terceiro ângulo: '))
if a + b + c == 180: #checa se e um triangulo vendo a soma dos angu... |
# Disciplina: Probabilidade e Estatística
# Aluno: gabriel rodrigues da silva
# Lista 4
x=int(input("Digite um número entre 1 e 4: ")) #pega o numero e ja garante que e inteiro
while (x < 1 or x > 4): #checa se e 1 2 3 ou 4 se for sai direto se não for entra no while
print('Entrada inválida, digite o número novame... |
inv = ['Pano']
print('Você está andando na rua a noite, voce percebe um estranho se aproximando.')
choic = int(input('\n1.Da a volta e tenta despista-lo\n2.Continua seu caminho e o ignora\n'))
if choic == 1:
print('Ele começou a andar mais rápido ficando lado a lado com voce, ele tira um pano do bolso\ne colo... |
premium_shipping = 125
def ground_shipping(weight):
if weight <= 2:
return (weight * 1.5) + 20
elif (weight > 2) and (weight <= 6):
return (weight * 3) + 20
elif (weight > 6) and (weight <= 10):
return (weight * 4) + 20
else:
return (weight * 4.75) + 20
print(ground_shipping(8.4))
def drone_s... |
print("Приветствую выживший! Сообщи свои координаты, чтобы мы могли выслать за тобой помощь.")
print("Напомню, что сначала широту, а затем долготу.Для широты используй значения в диапазоне от 0 до 90. Долготу указывай в диапазоне от 0 до 180.")
coordinates = float(input("Укажи свои координаты через точку, это важно! ... |
operacao = input('''
Digite a operação matemática que você vai fazer:
+ Adição
- Subtração
/ Divisão
* Multiplicação
** Expoente
''')
num_1 = int(input('Digite seu primeiro numero: '))
num_2 = int(input('Digite seu segundo numero: '))
if operacao == '+':
print('{} + {} = '.format(num_1, num_2))
... |
# https://leetcode.com/problems/squares-of-a-sorted-array/
class Solution:
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
for ind,a in enumerate(A[::-1]):
if a >= 0:
A[ind] = a ** 2
else:
... |
# https://leetcode.com/problems/encode-and-decode-tinyurl/
class Codec:
i = {}
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
global i
crypto = ''.join(random.choice(string.ascii_uppercase + strin... |
# https://leetcode.com/problems/flip-equivalent-binary-trees/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flipEquiv(self, root1: 'TreeNode', root2: 'TreeNode') -> 'bool':
... |
# https://leetcode.com/problems/robot-return-to-origin/
class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
#horizontal position
h_pos = 0
#vertical position
v_pos = 0
for inp in moves:
... |
# https://leetcode.com/problems/pancake-sorting/
# this is not the most performant solution for this problem; but the first I came up with when solving this problem.
# A further analysis of this problem is done in https://people.eecs.berkeley.edu/~christos/papers/Bounds%20For%20Sorting%20By%20Prefix%20Reversal.pdf
cl... |
# https://leetcode.com/problems/distribute-candies/
from collections import Counter
class Solution:
def distributeCandies(self, candies: List[int]) -> int:
#count occurences and assign candy to sister to be as diverse as possible
counts = Counter(candies)
total_candy = len(candies... |
#!/usr/bin/env python3
import os
def main() :
#We expect the file path to be input as the first argument
os.system("xinput > temp.txt")
words = readAllStrings("temp.txt")
print(words)
nextVal = False
for w in words :
if nextVal == True :
mouseID = w.split("=")[1]
... |
#!/usr/bin/python
"""My second Data Structure, a Tuple!
Joseph Kern
"""
# A list and a Tuple are very similar, but the Tuple cannot be changed.
# More on this later.
MyFirstTuple = 66, 24, 88, "Hello"
print MyFirstTuple
# Again we can iterate over the tuple.
for Item in MyFirstTuple:
print Item
|
#!/usr/bin/python
""" A simple while loop example
Joseph Kern
"""
x = 5
# WHILE 'x' IS MORE THAN 0 print 'x' THEN subtract 1 from 'x'
while x > 0:
print x
x -= 1
|
#!/usr/bin/python
"""
An introduction to math operations
"""
x = 5 # Variables can store numbers too
y = 3
print x + y, "=",x,"+",y # Addition
print x - y, "=",x,"-",y # Subtraction
print x * y, "=",x,"*",y # Multiplication
print x / y, "=",x,"/",y # Division
print x % y, "=",x,"%",y # Mod, this is the remainde... |
#!/usr/bin/python
"""
An introduction to built in string operations, concatenation
"""
h = '' # First let's make an empty string called 'h'. This can be
# thought of as a container. Right now the container is empty.
h = "Hel" # Now we have filled our container with a value.
l = "lo" # Let's make another containe... |
import sqlite3
#! CRIAÇÃO DA TABELA
# Esta função irá criar uma tabela padrão para o banco de dados
# Ela terá um ID autoincrementado automaticamente
def defaultTable():
conn = sqlite3.connect("carros.db")
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS carros(
id INTEGER PRIMARY KEY... |
count = 0
def foo(n):
global count
count += 1
if n == 0 or n == 1 or n == 2:
return 1
return foo(n - 1) + 2 * foo(n - 3)
if __name__ == "__main__":
foo(6)
print(count) |
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < len(s) and right >= 0:
if s[left] == " ":
left += 1
continue
if s[right] == " ":
right -= 1
continue
if left < len(s) and right >= 0 and s[left] != s[right]:
return ... |
from base import Node, Tree
class BinaryTree(Tree):
def _recursive_populate(self, root, value):
if value > root.value:
if root.rchild is None:
root.rchild = Node(value)
else:
self._recursive_populate(root.rchild, value)
... |
"""Bubble sort, in-place (mutable list): O(n^2)"""
from base import SortABC
class BubbleSort(SortABC):
def perform(self):
top = len(self.unsorted) - 1
while top > 0:
low = 0
high = 1
while high <= top:
if self.unsorted[low] > self.unsorted[hig... |
import random
#Given a list, return the next item which value is zero
def nextEmpty(parent):
for i in range(0,len(parent)):
if parent[i]==0:
return i
#Given a list and number, returns the first ocurrence index
def findNumberIndex(parent,number):
return parent.index(number)
def cyclicCrossover(parent1,parent2,... |
import tkinter as tk
from tkinter import ttk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["tex... |
#Run The Program on CodeSkulptor
#CodeSkulptor NOT Run Properly in Internet Explorer Therefor Run in Other Browser like Google Chrome.
#This program is Simple Game
#When we press the UP Button the circle move down to up and attempt count is Increase
#The score is moving left to right
#If the circle touch the scor... |
numeros = ["cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce",
"trece", "catorce", "quince", "diezciseis", "diecisiete", "dieciocho", "diecinueve", "veinte"]
def palabra():
global texto
texto = (input("Ingrese Palabra"))
print("la Palabra I... |
import zipfile
import urllib
import tempfile
import re
import os
from globals import pych_url
def download_zipfile():
# get the zip resource from the web
web_res = urllib.urlopen('http://www.pythonchallenge.com/pc/def/channel.zip')
#save to file
f = tempfile.TemporaryFile()
f.write(web_res.read()... |
from pyperclip import copy, paste
from base64 import b64encode, b64decode
websitePasswords = {
'gmail': 'WmFoZWVyIEFiYmFz',
'github': 'eW91RG9udEtub3dNeVBhc3N3b3Jk',
'gitlab': 'WmFoZWVyIEFiYmFz'
}
def addPassword():
print("Enter Website Name:")
print("Example:\"gmail\" or \"github\"")
website... |
num=input("enter the no. make table")
for i in range(1,11):
print num,'x',i,'=',num*i |
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
start_at_this_number = 0
while start_at_this_number < 5:
print(my_list[start_at_this_number])
start_at_this_number += 1
if start_at_this_number == 5:
start_at_this_number -= 5
|
fruits = ["apples", "bananas", "pears", "apples"]
for f in fruits:
print("I like to eat " + f)
for fr in fruits:
if fr == "apples":
print("Apples are gross!")
elif fr == "bananas":
print("I like bananas!")
break
|
import folium
import itertools
import math
import numpy as np
def _degree_to_zoom_level(l1, l2, margin = 0.0):
degree = abs(l1 - l2) * (1 + margin)
zoom_level_int = 0
if degree != 0:
zoom_level_float = math.log(360/degree)/math.log(2)
zoom_level_int = int(zoom_level_float)
el... |
import xarray
import pandas as pd
def remove_empty_scenes(dataset, nodata=-9999, bands=['red'], dim=['x','y']):
"""Remove time steps containing only no data values
Description
----------
Takes an xarray dataset an drops all time steps which only contain no data values
Parameters
----------
... |
end = 1000
threes = list(range(3,end,3))
fives = list(range(5,end,5))
threesAndFives= threes + list(set(fives) - set(threes))
print(sum(threesAndFives)) |
def modify_team_statistic(goals_scored, goals_conceded, line):
line[0] += 1
if goals_scored > goals_conceded:
line[1] += 1
line[4] += 3
elif goals_scored == goals_conceded:
line[2] += 1
line[4] += 1
else:
line[3] += 1
def main():
n = int(input())
table ... |
numbers = []
for c in range(1, 6):
numbers.append(int(input(f'Insert the {c} number: ')))
h = max(numbers)
posH = numbers.index(h)
s = min(numbers)
posL = numbers.index(s)
print(f'The higher number is {h} that is on the {posH + 1} position,\n'
f'The smaller number is {s} that is on the {posL + 1} position')
|
import random
numbers = list()
def randomizing():
for c in range(0, 5):
n = random.randint(0, 10)
numbers.append(n)
print(f'The numbers are {numbers}')
def summing():
sm = 0
for i in numbers:
if i % 2 == 0:
sm = sm + i
print(f'The sum of even numbers is {sm}'... |
n1 = int(input('first number: '))
n2 = int(input('second number: '))
c = 0
while c != 5:
print('What do you want to do?\n'
'1 - sum\n'
'2 - multiply\n'
'3 - know the higher\n'
'4 - change the numbers\n'
'5 - exit')
c = int(input('- '))
if c == 1:
pr... |
# liczba = input('wprowadź litere: ')
# print(liczba)
# print(type(liczba))
# liczba = float(liczba)
# print(liczba)
#
# import sys as system
#
# system.stdout.write("wprowadz lietere")
# litera = system.stdin.readline()
# system.stdout.write(litera)
#
# wzór na if
# if warunek:
# instrukcje
# elif warunek1:
# ... |
#%%
# Assignment Day 6
# Question 1
# For this challenge,create a bank account class that has two attributes
#*ownerName
#*Balance
#And two methods
#*deposit
#*withdraw
#As an added requirement,withdrawals may not exceed the available balance.
#Instantiate your class,make several deposits and withdrawal... |
#Given an input file which contains list of names, phone numbers and email-ids separated by spaces in the following format:-
#Alex 80-23425525 alex234@yahoo.com
#Emily 322-56775342 em_44@gmail.com
#Grace 20-24564555 softech_grace@rediffmail.com
#Phone number contains 3 or 2 digit area code and a hyphen followed by 8 di... |
#Do the following using regular expressions:-
# Find all occurrences of a word in a multiline string. The search must be case insensitive. Also find and display the starting index of each matched word in the input string.
# Given a line of text find all characters other than vowels and space characters.
# Given a list ... |
list1 = ['Phan Thanh Thao']
list2 =['Female',1997]
list3=list1+list2
print("Person:")
print list3
index = 0
length = len(list3)
while index < length:
print(index, 'stands for', list3[index])
index += 1 |
count = 0
while (count < 8):
print 'So thu ba cua ban la:', count
count = count + 1
print "Good bye!" |
import os, sys
import pandas as pd
class Folders:
"""
This class is used to manage folder structures and appending paths to make workflow easier.
"""
@staticmethod
def read_json(fullpath):
"""
Reads json file and returns it.
Parameters:
- fullpath: the desired p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.