text stringlengths 37 1.41M |
|---|
asd = ['5','3','2','4','1']
x = 0
for i in asd:
if type(i) == int:
if int(i) > x:
x = i
print(x) |
'''
838. Push Dominoes
https://leetcode.com/problems/push-dominoes
Hi, here's your problem today. This problem was recently asked by Twitter:
Given a string with the initial condition of dominoes, where:
. represents that the domino is standing still
L represents that the domino is falling to the left side
R represe... |
'''
349. Intersection of Two Arrays
https://leetcode.com/problems/intersection-of-two-arrays/
Hi, here's your problem today. This problem was recently asked by Amazon:
Given two arrays, write a function to compute their intersection -
the intersection means the numbers that are in both arrays.
Example 1:
... |
def insertion_sort(A):
for idx in range(1,len(A)):#1...len(A)-1
key = A[idx]
cmp_idx = idx-1
while cmp_idx>=0 and A[cmp_idx]>key:
A[cmp_idx+1]=A[cmp_idx]
cmp_idx -= 1
A[cmp_idx+1] = key
def partition(A, start, end):
pivot_idx = end-1
mid_idx = start
... |
'''
56. Merge Intervals
https://leetcode.com/problems/merge-intervals/
Given a collection of intervals,
merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps,
merge them into [1,6].
Example 2... |
'''
242. Valid Anagram
https://leetcode.com/problems/valid-anagram/
Given two strings s and t,
write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
'''
from typing import *
import colle... |
'''
42. Trapping Rain Water
https://leetcode.com/problems/trapping-rain-water/
Hi, here's your problem today. This problem was recently asked by Uber:
You have a landscape, in which puddles can form.
You are given an array of non-negative integers representing
the elevation at each location.
Return the am... |
def dfs(graph, vertex, visited = set()):
visited.add(vertex)
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
def bfs(graph, vertex):
import collections
q = collections.deque()
q.append(vertex)
visited = { ve... |
'''
1233. Remove Sub-Folders from the Filesystem
https://leetcode.com/contest/weekly-contest-159/problems/remove-sub-folders-from-the-filesystem/
Given a list of folders,
remove all sub-folders in those folders and
return in any order the folders after removing.
If a folder[i] is located within another folder... |
'''
160. Intersection of Two Linked Lists
https://leetcode.com/problems/intersection-of-two-linked-lists/
Hi, here's your problem today. This problem was recently asked by Apple:
You are given two singly linked lists. The lists intersect at some node.
Find, and return the node. Note: the lists are non-cyclical.
Exa... |
'''
98. Validate Binary Search Tree
https://leetcode.com/problems/validate-binary-search-tree/
Given a binary tree,
determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
*The left subtree of a node contains only
nodes with keys less than the node's key.
*The right subtree... |
#!/usr/bin/env python
# encoding: utf-8
from euler import proper_divisor_sum
def main():
result = 0
for num in range(2, 10001):
proper_sum = proper_divisor_sum(num)
if num != proper_sum and proper_divisor_sum(proper_sum) == num:
result += proper_sum
print(result)
if __name_... |
#!/usr/bin/env python
# encoding: utf-8
from euler import primes
def main():
prime_numbers = primes(1000)
num, num_of_div, num_of_div_sofar = 3, 2, 0
while num_of_div_sofar <= 500:
num += 1
next_num = num
if next_num % 2 == 0:
next_num /= 2
tmp_num_of_div = 1... |
from math import factorial
def perms(N, rem):
rem_idx = rem - 1
remainingdigits = list(range(N))
digits = []
for i in range(N):
idx = N - 1 - i
f = factorial(idx)
digit_idx = rem_idx // f
dg = remainingdigits.pop(digit_idx)
digits.append(str(dg))
rem_idx =... |
CACHE = {}
CACHE_SQ = {}
def square_digit_sum(i):
if i in CACHE_SQ:
return CACHE_SQ[i]
out = 0
for j in str(i):
out += int(j) ** 2
CACHE_SQ[i] = out
return out
def arrives_at_89(i):
if i in CACHE:
return CACHE[i]
next_value = square_digit_sum(i)
if next_value =... |
'''
next is n/2 if even
next is 3n+1 if odd
'''
def next(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
def max_collatz_chain(under):
chain_length = {1: 0}
maxlen_n = 0
maxlen = 0
for n in range(1, under + 1):
seq = []
nxt = n
while chain_length.... |
'''
This is very slow but techincally works.
Could be improved by genreating pythagrean triples
'''
def square(x):
return int(x ** .5) ** 2 == x
def opt1(s):
right = (s // 2) ** 2
l1 = (s + 1) ** 2
if square(l1 - right):
p = 2 * (s + 1) + s
if p > 10 ** 9:
return
... |
'''
Brute force method, takes a few seconds.
There'a a cooler method that uses diophantine equations
'''
def slope(p, q):
'''returns None if div by zero
'''
d = q[0] - p[0]
if d == 0:
return
else:
return (q[1] - p[1]) / d
def two_slopes_prependicular(m1, m2):
if m1 is None and ... |
#!/usr/bin/python3.4
import argparse
import random
""" vars """
min_per_day = int()
max_per_day = int()
weekends = bool()
def generate_week(nworkdays, nhours):
weekdays = []
for i in range(nworkdays):
weekdays.append(-1)
for i in range((7 if weekends else 5)-nworkdays):
weekdays.append(0... |
from enum import Enum
class Commands(Enum):
NORTH = "N"
SOUTH = "S"
EAST = "E"
WEST = "W"
LEFT = "L"
RIGHT = "R"
FORWARD = "F"
class Instruction:
def __init__(self, instruction_str):
self.command = Commands(instruction_str[0])
self.value = int(instruction_str[1:])
... |
# Nousheen Siddiqui
# Edited on 02/25/21
# Use the following chunk of code as a base to produce the image shown below.
import turtle
def drawSquare(t, sz):
for i in range(4):
t.forward(sz)
t.left(90)
wn = turtle.Screen()
alex = turtle.Turtle()
alex.color("blue")
drawSquare(alex,... |
# CIRCULE OF SQUARES 2º método
import turtle
turtle.speed(0)
def square(l, a):
for i in range(4):
turtle.forward(l)
turtle.left(a)
for i in range(36):
square(100, 90)
turtle.left(10)
# recomeça uma nova série
for i in range(200):
square(100, 90)
turtl.left(11)
... |
def menu():
# print what options you have
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print
print ("3) Multiplication")
print ("4) Division")
print ("5) Quit calculator.py")
print (" ")
return int(input("Choose... |
# CIRCULE OF SQUARES
import turtle
turtle.speed(0)
def square():
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
square()
turtle.left(100)
for i in range(35):
square()
... |
def translate(message):
translation = { "A" : ".-", "B" : "-...", "C" : "-.-.", "D" : "-..", "E" : ".",
"F" : "..-.", "G" : "--.", "H" : "....", "I" : "..", "J" : ".---",
"K" : "-.-", "L" : ".-..", "M" : "--", "N" : "-.", "O" : "---",
"P" : ".--.", "Q" : "--.-", "R" : ".-.", "S" : "...", "T" : "-",
... |
input = [3, 1, 4, 6, 5]
def my_triplet(input):
squared_list = []
for i in input:
squared_list.append(i * i)
print (squared_list)
res_list = []
for i in range(len(squared_list) -1):
for j in range(len(squared_list) -1):
if (squared_list[i] + squared_list[j+1]) in s... |
list_of_friends=[]
friends=input("Enter no of friends you want to insert in list" )
ch=-1
choise=-1
print("Enter your friends names :")
for i in range(int(friends)):
list_of_friends.append(input())
while choise!=0:
print("select your choise")
print("press 1 to print your friend list")
print("press 2 to... |
# Напишите простой калькулятор, который считывает с пользовательского ввода три
# строки: первое число, второе число и операцию, после чего применяет операцию
# к введённым числам ("первое число" "операция" "второе число") и выводит результат на экран.
# Поддерживаемые операции: +, -, /, *, mod, pow, div, где
# mod — э... |
# Напишите программу, принимающую на вход целое число, которая выводит True,
# если переданное значение попадает в интервал (−15,12]∪(14,17)∪[19,+∞)
# и False в противном случае (регистр символов имеет значение).
# Обратите внимание на разные скобки, используемые для обозначения интервалов.
# В задании используются пол... |
#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
import psycopg2
import random
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match record... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 16:23:12 2017
@author: Andreea Aniculaesei
"""
#asks the user to type a number and continue to run until the type-in is not a number
def inputNumber(prompt):
while True:
try:
num = float(input(prompt))
break
excep... |
"""
Methods for printing fancy text
"""
from Color_Console import *
class Console:
colors = {
"black": 0,
"red": 1
}
attributes = {
"bold": 1,
"dim": 2
}
def __init__(self):
print("")
def print(text, attributes, foreground, background):
print ... |
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("{0} is running".format(self.name))
def print_age(self):
print("{0}'s age is {1} years old.".format(self.name, self.age))
def age_add(self):
self.age = sel... |
"""生成器,生成从 3 开始的无限奇数序列"""
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
"""筛选函数"""
def __not_divisible(n):
return lambda x: x % n > 0
"""生成器,不断返回下一个素数"""
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
... |
import numpy as np
import unicodedata
def calculate(numbers):
if len(numbers) != 9:
raise ValueError('List must contain nine numbers.')
matrix = np.array(numbers, dtype='float64').reshape((3, 3))
calculations = {}
calculations['mean'] = [list(matrix.mean(axis=0)),
... |
import string
def print_grid(grid):
#print(grid)
for row in grid:
print(*row, sep=' ')
def get_code(index):
if index < 26:
return string.ascii_uppercase[index]
if index < 2*26:
return 'A' + get_code(index % 26)
raise SystemError("unhandled index" + i)
coords = [list(map(int, line.split(', ')... |
#!/usr/bin/Python3
# -*- coding: utf-8 -*-
# =================================================================
# File : Scan_dir_full.py
# Author : LinXpy
# Time : 2018/12/21 21:29
# Function Description :
# 1) Scan the specified whole directory, calculate each subdir and
# file size, list all the subdir a... |
'''
. Create a class cal5 that will calculate area of a rectangle. Create
constructor method which has two parameters .Create calArea()
method that will calculate area of a rectangle. Create display() method
that will display area of a rectangle
'''
class Cal5:
def __init__(self,height,width):
sel... |
# check num is 0 or +ve or -ve
num = int(input("enter number"))
if num == 0:
print("num is 0")
elif num<0:
print("num is -ve")
else:
print("num is +ve") |
# PROJECT 1 --- ES2
# Theoretical Pendulum Periods
# FILL THESE COMMENTS IN
#*****************************************
# NAMES: Ryan Hankins and Aedan Brown
# NUMBER OF HOURS TO COMPLETE: 0.5
# YOUR COLLABORATION STATEMENT(s): We worked alone on this assignment
#
#
#*****************************************
import nu... |
#Takes a value in a list, multiplies the value by 2, and adds the product to a variable total
numbers = [2,4,6,8]
def times_two(values):
total=0
for num in numbers:
total += num*2
return total
print(times_two(numbers)) |
"""
Inheritance: You have 2 classes where the parent class:Employee has a basic template.
Now you wrote another class Programmer.
Now a programmer is also an employee but it has some additional qualities/features etc.
Keeping in mind the best coding practice DRY:DO NOT REPEAT, since there is a template similarity b... |
"""
Inheritance: You have 2 classes where the parent class:Employee has a basic template.
Now you wrote another class Programmer.
Now a programmer is also an employee but it has some additional qualities/features etc.
Keeping in mind the best coding practice DRY:DO NOT REPEAT, since there is a template similarity b... |
class Dad:
history_knowledge="Expert" #This is a public variable
_person="Good" #This is a protected variable
__property="Nothing" #This is a private variable.
def print_dad_details(self):
print(f"Madan Mohan Ganguly had {self.history_knowledge} level of knowledge in ... |
"""This is a python mini project- Health Management System.
This app maintains the food habits and exercises performed by 3 people-Souvik, Atanu and Abhijit
along with time-stamp.
You can either add their activities or retrieve their activities till now as per your requirement.
It involves: dynamic programming, fun... |
def TwoDArray(size):
arr = []
for _ in range(size):
arr.append(list(map(str, input().strip().split())))
return arr
def printMatrix(array):
for row in array:`
for element in ''.join(row):
print(element, end=" ")
print("")
matrix_size = int(input())
printMatrix(TwoDAr... |
#!/usr/bin/env python3
import argparse
import csv
import json
import os.path
# Reads the variants.csv file and outputs a tuple of 3 dictionaries: (variants, languages, packs)
def readVariants(varCsv):
with open(varCsv, newline='', encoding='utf-8') as csvVariants:
variantsReader = csv.reader(csvVariants)
... |
# Assignment 1
# Part 3
# Robert Garza, Jheovanny Camacho, Robert Hovanesian
# 03-05-2019
class Hamburger:
def __init__(self, **kwargs):
"""
initialization of Hamburger class,
arbitrary number of keyword arguments accepted
"""
# object attributes are mapped to the keyword a... |
# Mr Miyagi trainee
# make a Mr Miyagi virtual assistant
# put main body of code in a function
def miyagi_response(user_input):
response_count = 0
# Evaluate each input and print the appropriate responses
if user_input == "sensei, i am at peace":
end_code = True
print("[Mr Miyagi] Sometim... |
# Write a bizz and zzuu game ##project
# as a user I should be able prompted for a number, as the program will print all the number up to and inclusing said number while following the constraints / specs. (bizz and buzz for multiples or 3 and 5)
# As a user I should be able to keep giving the program different number... |
# INTRO TO PYTHON - VARIABLES, INPUTS AND PRINTING
# box_variable = "Books and Stuff" # Store string as variable
# print(box_variable) # #Print variable
# box_variable = 3 # Reassign as an int
# print(box_variable) # Re-print
# print(type(box_variable)) # Print data type of variable
# Other variables include;
# ... |
import PyPDF2 as PP
def cut(file1,initpage,finalpage):
'''This function cuts pages from a pdf'''
# creating a shell for the new file
cutpdfobj = PP.PdfFileWriter()
# opening the pdf
pdf1File = open(file1, 'rb')
# reading the pdf
pdf1Reader = PP.PdfFileReader(pdf1File)
... |
import osa
import math
def read_lines_from_file(input_path):
with open(input_path) as input_file:
return input_file.readlines()
def count_exp(input_path):
url = 'http://fx.currencysystem.com/webservices/CurrencyServer4.asmx?WSDL'
client = osa.client.Client(url)
sum_rub = 0
file_lines = re... |
#!/usr/bin/env python
import struct, string, math, copy
class SudokuBoard:
"""This will be the sudoku board game object your player will manipulate."""
def __init__(self, size, board):
"""the constructor for the SudokuBoard"""
self.BoardSize = size #the size of the board
self.CurrentGameBoar... |
myNumber = 42
if myNumber == 42:
print("Matched")
else:
print("Not a match")
myNumber = 412
if myNumber > 42:
print(" The number " + str(myNumber) + " is greater than 42")
else:
print(" The number " + str(myNumber) + " is less than or equal 42")
myValue = 23
if myValue > 20 and myValue != 33:
pr... |
for num in range(1, 25):
print("")
print(str(num) + ": ", end="")
if num % 3 == 0:
print("Fizz", end="")
if num % 5 == 0:
print("Buzz", end="")
|
a = 1
b = "A"
print(str(a)+b)
a = "a"
b = "x"
print(a+b)
a = 8
b = 9
print(str(a) + str(b))
a = "8"
b = "9"
print(int(a)+int(b))
|
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of t... |
# Open Sublime text editor, create a new Python file, copy the following code in it and save it as 'census_main.py'.
# Import modules
import streamlit as st
st.set_page_config(page_title = "Census Visualisation Web App",page_icon = "💥",layout = "centered", initial_sidebar_state = "auto")
import numpy as np
impo... |
class Solution:
def climbStairs(self, n: int) -> int:
if n==1 or n==0: return 1
list = [1, 1]
for i in range(n-1):
list[0], list[1] = list[1], list[0]+list[1]
return list[1]
|
class Puzzle:
curr = []
width = 3
height = 3
def __init__(self, state):
self.first_state = state
self.curr = state
def move_zero(self, direction):
i = [x for x in self.curr if 0 in x][0]
row = self.curr.index(i)
col = i.index(0)
if direction == Dir.DOWN:
if row + 1 < self.height:
self... |
#!/usr/bin/env python
PKG = 'numpy'
import numpy as np
import numpy.matlib as npm
import numpy.linalg as npl
import matplotlib.pyplot as plt
def get_anchor_pos(anchors):
anchor_pos = np.zeros((2, np.size(anchors)))
for i in range(0, np.size(anchors)):
if anchors[i].get_pos() is not None:
a... |
#Sreeti Ravi
#11/8/2020
#Question 1
#Reading data file and drawing two histograms
import matplotlib.pyplot as plt
import pandas as pd
def main():
#read Excel file with heights_weights into pandas dataframe
xls_file = pd.ExcelFile("heights_weights.xlsx")
#parse through the file
file ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 23:52:10 2020
@author: sreet
"""
#Exercise 4.1
#Write a program that inputs an integer n from the user and prints n lines,
#such that there are i stars in line i = 1, 2, ... n .
# def main():
# print("The program prints a triangle of stars with n li... |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 00:34:26 2020
@author: sreet
"""
#Sreeti Ravi
#9-3-2020
#Question 2
#Write a program that prompts the user for the mileage of a vehicle, calculates
#and prints the fuel consumption of the vehicle in liters per 100 km. Assume
#that 1 mile is 1.6 km and 1 ga... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 15:31:40 2020
@author: sreet
"""
#Sreeti Ravi
#9/19/2020
#Question 2
#Write a program that takes a positive integer number from the user and prints
#the number in words
def main():
print("The program spells the input number.")
number = in... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 10 01:12:55 2020
@author: sreet
"""
#Sreeti Ravi
#10/10/2020
#Question 3
#Program prints prime numbers in a range
def is_prime(number):
#returns True if number is a prime number and otherwise False
if number > 1:
for i in range(2, number):... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 17:11:10 2020
@author: sreet
"""
#Sreeti Ravi
#10/17/2020
#Question 3
#Write a program that creates a window with a circle that bounces from the
#window walls.
#I used code from Exercise 8.7 from this question
from graphics import *
#delay
def de... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 22:05:08 2020
@author: sreet
"""
#Sreeti Ravi
#10/31/2020
#Question 4
#Finds the maximum period in which the close value of the stock was up each day
from pandas_datareader import data as web
def max_up(stock):
#initializing variables
days_up... |
import pandas as pd
import matplotlib.pyplot as plt
import pylab
#making a boxplot with data from Human Biology 2 Course
#importing data from a csv file
data = pd.read_csv('/Users/lidiaerrico/Downloads/exercise.csv')
r_ow = data['R_0_W']
#imputting x and y values and giving a title and axis labels
fig7, ax7 = plt.sub... |
#! /usr/bin/env python
import sys
text = open(sys.argv[1]).read()
import re
matches = re.compile("throughput=\s+(\d+[.]\d+)").findall(text)
sum = 0
for m in matches:
sum += float(m)
avg = sum / len(matches)
print avg
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# Para los calculos
import numpy as np
import math
import scipy # http://scipy.org/
from scipy import constants
def dButoV(dBu):
v = 10**(dBu/20)
print('\nV = {:.2f} uV\n\n'.format(v))
while 1:
dBu = float(input("Enter dBu: "))
dBut... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 18:21:00 2019
@author: CEC
"""
#import math
#x=float(input("Ingrese x: "))
#y=math.sqrt(x)
#print("Resultado raiz cuadrada de x: ", y)
try:
print("1")
x=1/0
print("2")
except:
print("Oh rayos! esta mal!!")
print("3") |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 20:25:40 2019
@author: CEC
"""
def es_primo(numero):
for i in range(2,numero):
if (numero%i)==0:
return False
return True
numero = int(input("inserta un numero: "))
if numero==0 or numero==1:
print ("\nEl numero NO ... |
i = 1
a = raw_input("Please enter an number greater than 2:")
while not a.isdigit() or not float(a) > 2:
a = raw_input("Please enter an number greater than 2:")
while float(a) > 2 :
print i, ':' , '%.3f' %float(a)**0.5
i += 1
a = float(a)**0.5
if a < 2 :
break
|
import sqlite3
import json
from sqlite3 import Error
#crear la conexion
def sql_connection():
try:
con = sqlite3.connect('SQLite/test.sqlite3')
return con
except Error:
print(Error)
#codigo crear tabla
def sql_table(con):
cursorObj = con.cursor()
cursorObj.execute("CREATE TABLE... |
name = 'Mandy'
yourName = input('What is your name?\n')
while len(yourName):
if yourName == name:
print('Hello, Mandy!')
else:
print('I do not know you.')
yourName = input('What is your name?\n')
|
n = input("input a postive integer: ")
def function(n):
if n == 0: return 0
elif n == 1: return 1
else: return (function(n-1)+ function(n-2))
x = function(n)
print(x)
|
# Ссылка на схемы
# https://drive.google.com/file/d/14vLKzw007Cj8Ld8VYsGee5cxRGMk5lHL/view?usp=sharing
a, b, c = map(float, input("введите три разных числа через пробел: ").split())
if a > b:
if b > c:
print(f"Среднее число {b}")
elif a > c:
print(f"Среднее число {c}")
else:
print(... |
# Ссылка на схемы
# https://drive.google.com/file/d/14vLKzw007Cj8Ld8VYsGee5cxRGMk5lHL/view?usp=sharing
a, b = input("Введите две заглавные буквы английского алфавита, разделенные пробелом: ").split()
a = ord(a) - ord('A') + 1
b = ord(b) - ord('A') + 1
c = abs(a - b)
print(f"Это {a} и {b} буквы алфавита. Между ними {c}... |
import random
SIZE = 10
MIN_ITEM = -100
MAX_ITEM = 100
array = [random.randint(MIN_ITEM,MAX_ITEM) for _ in range(SIZE)]
print(array)
max_elem = MIN_ITEM
max_index = SIZE + 1
i = 0
for el in array:
if (el < 0) and (el >= max_elem):
max_elem = el
max_index = i
i = i + 1
if max_index <= SIZE:
... |
"""
7. Find Armstrong Numbers in the given range.
"""
import math
def is_armstrong(val):
num = val
n = int(math.log10(num)) + 1
sum = 0
for _ in range(n):
digit = num % 10
sum += digit ** n
num //= 10
if val == sum:
return True
else:
return Fals... |
"""
10. Find the first 10 numbers from geometric series
"""
a = float(input("Enter the first term of the Geometric Series: "))
r = float(input("Enter the Common Ratio of the Geometric Series: "))
print("First 10 numbers of Geometric Series are:")
for i in range(10):
print(a * (r ** i), end=", ")
|
# Radiactive Decay
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radiationExposure(start, stop, step):
'''
Computes and returns the amount of radiation exposed
to between the start and stop times. Calls the
function f (defined for you in the grading script)
to obtain... |
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
result = number1 + number2
print("The result is %d. " % result)
|
def count_spaces(userInput):
spaces = 0
for char in userInput :
if char == " " :
spaces = spaces + 1
return spaces
def main():
userInput = input("Please, enter a sentence:")
print (count_spaces(userInput))
main()
|
richter = float(input("What was the earthquake's magnitude?"))
if richter >= 8.0:
print("Most structures fall")
elif richter >= 7.0:
print("Many buildings destroyed")
elif richter >= 6.0:
print("Many buildings considerably damaged, some collapse")
elif richter >= 4.5:
print("Damage to poorly c... |
x = int(input())
x = x*2
x = x*2
print(x)
#0.052 / 31.05.2021 / 1
|
x = int(input())
ano = x // 365
x = x - ano*365
mes = x // 30
x = x - mes*30
dia = x
print(f"{ano} ano(s)")
print(f"{mes} mes(es)")
print(f"{dia} dia(s)")
#0.177 / 31.05.2021 / 4
|
Primeiro = int(input("informe o Primeiro do intervalo: "))
Ultimo = int(input("informe o ultimo do intervalo: "))
SOMA=0
while (primeiro < ultimo - 1):
primeiro = primeiro+ 1
print(primeiro)
soma = (Primeiro+SOMA)
print("a soma dos intervalos intervalos é = {}".format(SOMA))
|
"""Testing module for Linked List clss."""
from linked_list import LinkedList
import pytest
@pytest.fixture
def empty_list():
"""Create empty LinkedList."""
return LinkedList()
@pytest.fixture
def filled_list():
"""Create a populated LinkedList."""
x = LinkedList([12, 34, 2, 67, 43, 98, 76])
ret... |
import math
class Interpreter(object):
"""Class to build the command string for the modem"""
SEPARATOR = ","
END_COMMAND = "\r\n"
START_COMMAND = ""
def __init__(self):
"""
Constructor, initialize the iterpreter.
@param self pointer to the class object
"""
... |
# -*- coding: utf-8 -*-
# Algorithm function:
# Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
... |
#!/user/bin/env python
# Student: Duy Nguyen
# Solution to question 1, homework 1
#
# Read FASTA file
# You should be able to run the program as of the folloing commands
# python HW01_Code.py yeast_chrom.fasta chr01 20 30 +
import sys
import io
import getopt
def read_FASTA_sequence(file):
"Read the sequence give... |
import sys
number = int(sys.argv[1])
print(number)
#Counting number of bits in a number
def counting_bits(number):
max_bit_value = 1
bits = 1
while max_bit_value < number:
bits +=1
max_bit_value = (2 ** bits ) - 1
return bits
bits_in_number = counting_bits(number)
output = "There are ... |
def mensagem_boas_vindas():
print('\tSeja bem vindo ao fantástico mundo de Python!!')
mensagem_boas_vindas2()
def mensagem_boas_vindas2():
print('\tSeja bem vindo ao fantástico mundo de Python!!, NOVAMENTE...')
def mensagem_custom(nome):
mensagem = 'Olá {} seja bem vindo'.format(nome)
return men... |
import random
randomlist1 = [] #two random lists, and one for storing overlapping numbers
randomlist2 = []
random_overlap = []
for i in range(0,5): #creating two random list with 5 numbers in range 1-30
n = random.randint(1,30)
randomlist1.append(n)
m = random.... |
#Nama : Efraim
#NRP: 1572048
#_TB_C_1572048_Efraim
#from __future__ import print_function <-- untuk mendapatkan variabel dari python 3 karena interpreter ini python 2
from __future__ import print_function
#####Fungsi print matriks######
#Kamus lokal
#i,j : var.counter(int)
#Baris: wadah banyak baris(int)
#K... |
BASE_COLOR = (0, 0, 0)
class ImageModel:
"""Representa una imagen a guardar
Atributos
---------
w - ancho de la imagen
h - alto de la imagen
_img - matriz de colores de la imagen"""
_img = []
def __init__(self, w=640, h=480):
self.create(w, h)
... |
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4,7):
if not text[i].isdecimal():
return False
for i in range(8,12):
if not text[i].isdecimal():
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.