text stringlengths 37 1.41M |
|---|
# WAP to accept lower limit and upper limit and print the even and odd numbers between those
def oddEven(ll,ul):
odd =[]
even = []
for x in range (ll,ul):
if (x % 2==0):
even.append(x)
else:
odd.append(x)
return even,odd
ll = int(input("enter the lower limit"))
... |
import json
class PingPong:
"""
This class is for get the person who lose the second game
and get the information about his games losed
Params
**partidos: is dictionary with the games
return
Print results who lose the second game and json with the game losed in order
"""
def __init... |
import unittest
def binary(num):
arr=[0,0,0,0,0,0,0,0]
count=7
while num!=0:
r=num%2
num=num//2
arr[count]=arr[count]+r
count=count-1
# print(arr)
return arr
def hamming_distance(x,y):
x_binary=binary(x)
y_binary=binary(y)
count=0
# print(x_binary)
# print(y_binary)
for i in r... |
import unittest
def is_valid(string):
# Determine if the input code is valid
brackets = []
bracket_map = {
'(': 0,
'{': 0,
'[': 0,
')': '(',
'}': '{',
']': '[',
}
for ch in string:
if ch in bracket_map:
brack = b... |
import operator
def GetCount(List,Map,num):
Count=[0]*num
temp=0
for val,id in List:
if id==1:
temp+=1
elif id==3:
temp-=1
else:
Count[Map[val]]=temp
return Count
def points_cover(starts, ends, points):
Map = {}
for i... |
# Fractional Knapsack, Greedy Approach
def maximum_loot_value(capacity, weights, prices):
value=0
temp={}
for i in range(len(prices)):
temp[i] = (prices[i]/weights[i]) # Per unit value of each item
while capacity>0:
x = max(temp, key=temp.get) # Choose Item of Max per un... |
import json
import random
import time
from sort_algorithms import selection_sort, insertion_sort, shell_sort, start_merge_sort
def generate_array(numbers_array, n_experiment, len_array):
"""
:param numbers_array: a list of numbers from 0 to pow(2, 15) to save time on creating random lists,
instead every... |
#Unix/Linux操作系统提供了一个fork()系统调用
#它非常特殊。普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次
#因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程)
#然后,分别在父进程和子进程内返回
import os
print('Process (%s) start...' % os.getpid())
# Only works on Unix/Linux/Mac:
pid = os.fork()
if pid == 0:#如果返回0(子进程永远返回0,而父进程返回子进程的ID)
print('I am child process (%s) and... |
#在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们。
#正确关闭文件资源的一个方法是使用try...finally:
try:
f = open('/path/to/file', 'r')
f.read()
finally:
if f:
f.close()
#写try...finally非常繁琐。
#Python的with语句允许我们非常方便地使用资源,而不必担心资源没有关闭,
#所以上面的代码可以简化为:
with open('/path/to/file', 'r') as f:
f.read()
|
#Python的标准库提供了两个模块:_thread和threading,
#_thread是低级模块,threading是高级模块,对_thread进行了封装。
#绝大多数情况下,我们只需要使用threading这个高级模块
#启动线程
import time, threading
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('threa... |
#允许对Student实例添加name和age属性
class Student(object):
__slots__ = ('name', 'age')
>>> s = Student() # 创建新的实例
>>> s.name = 'Michael' # 绑定属性'name'
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object h... |
#filter,和map类似,也接受一个函数和一个序列
#把传入的函数依次作用于每个元素,根据返回值是True还是False决定保留还是丢弃
#保留奇数,过滤掉偶数
def must_odd(n):
return n % 2 == 1
print(list(filter(must_odd,[1,2,3,4,5,6,7,8,9])
)
)
#1%2 的意思是求1除以2得到的余数,而1除以2 = 0 余1 所以 1%2是1
#把list中的元素代入must_odd中,1,3,5,7,9 %2都余1,返回值为True,保留
#2,4,6,8 %2余0,返回值为Fales,丢弃
#... |
#Class responsible recording the video and storing it in a specified location.
import cv2;
import numpy as np;
from videocamera import CameraClass;
'''
# setDriveLocation: set the path where video will be stored.
# getDriveLocation: get the path where video will be stored.
# setpreferedFormat: format in which video i... |
# Reference: https://leetcode.com/problems/palindrome-number/
# Sequence = 9. Palindrome Number
# Prepared by - Maddy Rai
import time
class Solution:
def isPalindrome(self, x):
if x not in range(-2**31, 2**31):
raise Exception("Input number is out of range.")
return str(x) ... |
# Reference: https://leetcode.com/problems/shuffle-the-array/
# Sequence = 1470. Shuffle the Array
# Prepared by - Maddy Rai
import time
class Solution:
def shuffle(self, nums, n):
if n not in range(1, 501):
raise Exception("n is out of range.")
if len(nums) != 2*n:
... |
# Reference: https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/
# Sequence = 1880. Check if Word Equals Summation of Two Words
# Prepared by - Maddy Rai
import time
class Solution:
def isSumEqual(self, firstWord, secondWord, targetWord):
if len(firstWord) not in range(1, 9)... |
import ctypes
from time import time
class DynamicArray:
def __init__(self):
self._n = 0
self._capacity = 1
self._A = self._make_array(self._capacity)
def __len__(self):
return self._n
def __getitem__(self,k):
if not 0 <= k < self._n:
raise IndexError('... |
import requests
from bs4 import BeautifulSoup
import smtplib
# This program looks at a raspberry pi camera and
# emails me if the price has fallen below a certain amount
# https://www.youtube.com/watch?v=Bg9r_yLk7VY&t=330s&ab_channel=DevEd
URL = 'https://www.amazon.com/Raspberry-Camera-Vision-IR-Cut-Longruner/dp/B07R... |
# Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On,
# Donder and Blitzen! That's the order Santa wanted his reindeer...right?
# What do you mean he wants them in order by their last names!? Looks like we need your help!
# Write a function that accepts a sequence of Reindeer names,
# and retu... |
# The function is not returning the correct values. Can you figure out why?
# def get_planet_name(id):
# This doesn't work; Fix it!
# name=""
# switch id:
# case 1: name = "Mercury"
# case 2: name = "Venus"
# case 3: name = "Earth"
# case 4: name = "Mars"
# case 5: na... |
#Python orbital visualizer. By M. Ewers, P. Brabant, I. Laurent, P. Jermann and F. Meyer. 2021.
# Our goal is to draw a 3D representation of a few orbitals
# we import packages we need for our program
import numpy # we use numpy in order to use mathematical tools depending on x, y, z
from mayavi import mlab # we ... |
import sys
print(sys.maxsize)
print(sys.float_info.max)
#Guys this is way of max limit of any float or int value
cn1 = 7 + 3j
cn2 = 8 + 2j
cn = (cn1 + cn2)*(- 1)
print(cn)
# ya guys the above example was for operation of complex numbers
|
def allowed_dating_age(my_age):
girls_age = my_age/2 + 10
return girls_age
Buckys_limit = allowed_dating_age(27)
print("Bucky can date girls",Buckys_limit,"or older")
# now we gonna do some multiple exampples
Rahuls_limit = allowed_dating_age(15)
print("Rahul can date girls",Rahuls_limit,"or older"... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
charlotte = {
"id": 6,
"name": "Charlotte",
"children": []
}
harrison = {
"id": 5,
"name": "Harrison",
"children": []
}
harry = {
"id": 4,
"name": "Harry",
"children": [harrison]
}
william = {
"id" : 3,
"name" : "... |
# USE RANGE
def fizz_buzz(numbers):
# I think that you need to use range and len here so that when it iterates through it keeps the list. if you just use for i in numbers, it will return the values as individuals
for i in range(len(numbers)):
num=numbers[i]
if num %3 ==0:
numbers[i]=... |
## USE PARAMETERIZED QUERIES TO INSERT DATA - NAMED PLACEHOLDERS
# New data is stored in variables and is inserted into the query strings using parameters
# Results are gethered by the row and are printed by using list locations
import sqlite3 as lite
import sys
uId = 4
con = lite.connect('test.db')
with con:
cu... |
## CREATES AND INSERTS DATA INTO DATABASE
# Assigns all data to be inserted into a list of tuples
# Table is destroyed if already exists and new one created
# executemany is used to insert all data from 'cars' list by using a parameterized string
import sqlite3 as lite
import sys
cars = (
(1, 'Audi', 52642),
... |
## RETRIEVE DATA FROM DATABASE - DICTIONARY
# Sets cursor to a dictionary style cursor
# Grabs data in all rows at once and prints row by row using the column id's (dictionary keys) through for loop
import sqlite3 as lite
con = lite.connect('test.db')
with con:
con.row_factory = lite.Row
cur = con.cursor()
c... |
class BankAccount(object):
def __init__(self, object):
self.name = object
self.balance = 0
def make_deposit(self, amount):
self.balance = (self.balance + amount)
def make_withdrawal(self, amount):
if self.balance > amount:
self.balance -= amount
else:
... |
#Escreva um programa que receba notas de um aluno (0 - 10), caso
#a nota digitada esteja fora dessa intervalo peça para o professor digitar
#novamente.
while True:
nota_aluno = int(input('Digite a nota do aluno: '))
if nota_aluno >= 0 and nota_aluno <= 10:
print(f'Nota armazenada com sucesso {nota_alun... |
class Block:
def __init__(self):
self.block = [None]*800 #each element will be either 0 or 1
class DiskA:
def __init__(self):
self.disk = [Block() for i in range(200)]
class DiskB:
def __init__(self):
self.disk = [Block() for i in range(300)]
def API_for_write(block_No, data):
... |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
import random
# public symbols
__all__ = ['Perceptron']
class Perceptron(object):
"""
Perceptron class
"""
def __init__(self):
self.N = None
self.d = None
self.w = None
self.rho = 0.5
def fit(self,... |
# 1. Получите текст из файла.
import re
with open('text.txt', 'r', encoding='UTF-8') as f:
text = f.read()
print(text)
# 2. Разбейте текст на предложения.
#разбиваем текст на предложения и записываем в файл text2.txt (эксперимент)
pattern2 = re.compile('(?<=\w[.!?])( |\n)')
text_list = pattern2.split(text)
for ... |
import math as m
num=int(input(""))
r=0
sum=0
temp=num
for i in range(1,num+1):
r=num%10
sum+=m.pow(r,3)
num=num//10
#print(r)
#s=m.pow(r,3)
#print(s)
#sum=sum+s
#print(int(sum))
if(temp==sum):
print("Arom Strong Number")
else:
print("no... |
shoes = ['nike', 'reebok', 'adidas', 'puma']
print(shoes)
print(shoes[0])
print(shoes[0].title())
print(shoes[-1])
message = f"My first shoe brand was {shoes[0].title()}."
print(message)
# Adding to a list
shoes.append('fila')
print(shoes)
shoes = [] # Adding elements to an empty list
shoes.append('nike')
shoes.appen... |
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
print("\n")
# Reading line by line
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
print("\n")
# Making a list of lines from a File
filename = ... |
# 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate
# for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay()
# and u... |
# print('hi')
# x = 2
# print(x)
# x = x + 2
# print(x)
# Using conditional statement
# x = 2
# if x < 5:
# print('smaller')
# else:
# print('bigger')
# # While loop
# # i = 10
# # while( i > 0):
# # print(i)
# # i = i-1
# # print('Boom')
# # array
# a = [ 10, 20 ]
# i = 0
# while( i < len(... |
# cook your dish here
#Solved by ROSHAN-RAUT in PYTHON ON 9-8-2020
from copy import deepcopy
for test in range(int(input())):
str = list(input())
pat = list(input())
for i in pat:
str.remove(i)
str.sort()
deep = deepcopy(str)
deep.append(pat[0])
deep = sorted(deep,reverse=True)
i... |
sample1 = [x**x for x in range(10)]
sample2 = [[x*n for n in range(5)] for x in range(10)]
sample3 = {x: x**x for x in range(5)}
if __name__ == '__main__':
print('sample 1:', sample1)
print('sample 2:', sample2)
print('sample 3:', sample3)
|
print('Hello World')
class FileName(object):
def __init__(self, filename):
self.filename = filename
self._get_file_name_info()
def _get_file_name_info(self):
file_str = ''.join(self.filename.split('.')[0:-1])
self._file_type = self.filename.split('.')[-1]
self._file_n... |
#This is to use argument
from sys import argv
#This explains the components
script, filename = argv
#This gives open command to open the sample file
txt = open(filename)
#These prints the words in sanple file
print "Here's your file %r:" % filename
print txt.read()
#This uses raw input to open file again
print "Typ... |
import math, random
from collections import Counter
import matplotlib.pyplot as plt
def bucketize(point,bucket_size):
return bucket_size*math.floor(point/bucket_size)
def make_histogram (points, bucket_size):
return Counter(bucketize(point,bucket_size) for point in points)
def plot_histogram(points,bucket_si... |
def rotate_string(s,rotateBy):
# we calculate the displacement
# required for the string and then
# slice and join the string
if len(s)==0:
return
x=len(s)-rotateBy
s=s[x:]+s[0:x]
print "Rotated String is"
print s
if __name__=="__main__":
s = input("Enter the string\n")
... |
import sys
import collections
def check_palindrome(s):
odd_count = 0
freq = collections.Counter()
for c in s:
if c != ' ':
freq[c] += 1
odd_count += -1 if freq[c]%2==0 else 1
return odd_count < 2
if __name__ == '__main__':
for line in sys.stdin.readlines():
... |
import queue
class Edge:
def __init__(self, p, n, c=0):
self.previous = p
self.next = n
self.cost = c
class Graph:
def __init__(self, size):
self.num_nodes = size
self.adjacency_list = [list() for x in range(size)]
def add_edge(self, p, n, c=0):
self.adjace... |
import sys
import collections
def check_permutation_hash(s1, s2):
if len(s1) is not len(s2):
return False
hashmap = collections.Counter(s1)
for c in s2:
if hashmap[c] < 1:
return False
hashmap[c] -= 1
return True
def check_permutation_sort(s1, s2):
if len(s1) is... |
def mergesort(lst):
if len(lst) <= 1:
return lst
lst_1 = mergesort(lst[:len(lst)//2])
lst_2 = mergesort(lst[len(lst)//2:])
lst_sorted = []
ptr_1 = 0
ptr_2 = 0
while ptr_1 < len(lst_1) or ptr_2 < len(lst_2):
if ptr_1 == len(lst_1):
lst_sorted.append(lst_2[ptr_2])
... |
"""
Module defines basic logical building blocks for writing rules
"""
#boolean logic
def implies(a,b):
return (not a) or b
def xor(a,b):
return (a and not b) or (not a and b)
def iff(a,b):
return implies(a,b) and implies(b,a)
#tuple logic
def eq(a,b, attr):
return _op( a, b, attr, lambda s,t: ... |
#!usr/bin/env python
#-*- coding: utf-8 -*-
funcionario = input()
horas = input()
valor_hora = input()
print "NUMBER = " + str(funcionario)
print "SALARY = U$ {:0.2f}".format(valor_hora * horas) |
# Merge sort algorithm
#
# This merge sort uses naturally sorted fragments and merges each of two following fragments
# It is done iteratively
def next_fragment(A, i):
j = i+1
while j < len(A) and A[j-1] <= A[j]: j += 1
return A[i:j]
def merge(B, C):
i = j = k = 0
M = [None] * (len(B) + len(C))
... |
import random
class Node:
def __init__ (self, val):
self.val = val
self.next = None
def add_number (self, val): # test function
temp = self.next
self.next = Node(val)
self.next.next = temp
class TwoLists:
def __init__ (self, even, odd):
self.even = even
... |
def insertion_sort(A):
for i in range(len(A)):
key = A[i]
k = i-1
while k >= 0 and A[k] > key:
A[k+1] = A[k]
k -= 1
A[k+1] = key
def bucket_sort(A):
n = len(A)
m = len(A) // 2 # should be propotional to len(A)
max_value = max(A)
buckets = [[] ... |
import math
n = int(input('n = '))
b = 2
while n > 1 and b <= math.sqrt(n) :
if n %b == 0 :
print (b, end = ' ')
n = n // b
else :
b += 1
if n > 1 : print(n)
|
def count_unique(list):
"""Count the number of distinct elements in a list.
The list can contain any kind of elements, including duplicates and nulls in any order.
:param list: list of elements to find distinct elements of
:return: the number of distinct elements in list
Examples:
>>> count_... |
__author__ = 'Mike'
import abc
class AbstractConnection(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def send_obj(self, message_obj):
"""
Serializes the provided message, and sends it along the connection.
"""
return
@abc.abstractmethod
def recv_obj(se... |
from mpmath import *
from sympy import degree
from sympy import *
from sympy.abc import x
import numpy as np
import cmath
print("Entere the polynomial whose roots you want to find\n")
print("if you want to find roots of a(x^2) + b(x) + c then enter ' a*(x**2) + b*x + c '\n\n")
fun= raw_input("polynomial--> ").stri... |
import random
import characters
import time
import string
class BattlePrep():
def __init__(self): # take int for total enemies
begin = 1
end = random.randint(2,10)
suspense = range(begin, end)
timeString = '.'*end
print (timeString)
for i in suspense:
time.sleep(0.5)
end = end-1
timeString = '.'... |
import json
# example dictionary to save as JSON
data = {
"first_name": "John",
"last_name": "Doe",
"email": "john@doe.com",
"salary": 1499.9, # just to demonstrate we can use floats as well
"age": 17,
"is_real": False, # also booleans!
"titles": ["The Unknown", "Anonymous"] # also lists!
}... |
#import plt and np
from matplotlib import pyplot as plt
import numpy as np
#load file located in data/sunspots.txt and call it `data` with float data type
data = np.loadtxt('data/sunspots.txt', dtype= float)
#assign first column as t
t = data[:,0]
#convert t into month that starts from Jan, 1749; use timed... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# class Solution(object):
# def findSubstring(self, s, words):
# """
# :type s: str
# :type words: List[str]
# :rtype: List[int]
# """
# nw = len(words[0]) * len(words)
# if len(s) < nw: return []
# ... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def recoverTree(self, root):
"""
:type root: ... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = matrix
n = len(matrix)
for i in range(0... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root:... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
def f(idx, r):
if len(r) == k:
res.append(r[:])
... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
(s, e) = (0, len(nums) - 1)
while s <= e:
m = (s + e) / 2
... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def fullJustify(self, words, maxWidth):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
gp = []
r = []
wc = 0
for w in words:
#... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
p = self.locate_pivot(nums)
a = self.bs_locate(nums, 0, p, target)
if a != -... |
import csv
import os
budgetpath = os.path.join('AMELIA-budget_data.csv')
with open(budgetpath, newline = '') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
rowCount = 0
header = next(csv_reader)
monthCount = 0 #for counting how many months
netTotal = 0 #to hold the total of all t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a basic calculator that can do four operations; addition, subtraction, summation and division.
"""
def addition(a, b):
""" Addition Operator """
return a + b
def subtraction(a, b):
""" Subtraction Operator """
return a - b
def summation(a, b)... |
# Print an introduction. Mention typing q to quit.
# Get some user input
# In each round (until the user types q to quit):
# Generate the computer's move. Make use of some kind of random behavior.
# Use some logic to determine who wins.
# Let the player know who wins.
# Any long term score ke... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score
from sklearn.linear_model import LinearRegression, LassoLars, TweedieRegressor
from sklearn.feature_selection import ... |
"""
Resources represent attributes that can be used or consumed as a resource, such
as health, mana, rocket power, etc.
"""
from attribute import Attribute
from resource_constants import AttributeType
from save_wrapper import save_attr
class Resource(object):
"""
Properties:
name (string) - name of the at... |
import sys
sys.path.insert(0, 'D:\github-projects\data-structures\shared')
from node import Node
# Binary heap: implementation of a max heap
# Definition:
# Parent node: must be greater than each of its children
# Insert: insert a new node at the leftmost available leaf
# and percolateUp() until the new no... |
__author__ = "Charles Engen"
class WordWizard:
def __init__(self):
self.name = "Word Wizard"
def _remove_vowels_spell(self, word):
return "".join([letter for letter in word if letter.lower() not in "aeiou"])
def _cast_spell(self, *spell):
words = []
for word in spell:
... |
documents = [
{"type": "passport", "number": "2207 876234", "name": "Василий Гупкин"},
{"type": "invoice", "number": "11-2", "name": "Геннадий Покемонов"},
{"type": "insurance", "number": "10006", "name": "Аристарх Павлов"}
]
directories = {
'1': ['2207 876234', '11-2'],
'2': ['10006'],
'3': []
... |
import pandas as pd
import plotly.express as px
df = pd.read_csv("line_chart.csv")
fig = px.line(df,x ='Year',y = 'Per capita income', color = "Country" )
fig.show() |
import random
import time
no_of_rolls = int(input("How many dice? "))
min = 1
max = 6
# a = random.randint(min,max)
# b = random.randint(min,max)
# c = a + b
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dices...")
time.sleep(1)
print("The values are..."... |
'''
Created on 28 dec. 2016
@author: radi961
'''
from _functools import reduce
from src import test
def combine(*args):
combinedList = []
inputLists = []
for list in args:
inputLists.append(list)
while not lists_empty(inputLists):
pop_lists(inputLists, combinedList)... |
"""
Contains the Cube class.
"""
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from cfop.algorithms.tools import alg_to_code
from cfop.algorithms.alg_dicts import PARAM_DICT, TURN_DICT
class Cube:
"""
Cube class which creates an objec... |
import numpy as np
def cubic(shape, spacing=1, connectivity=6, node_prefix='node', edge_prefix='edge'):
r"""
Generate a simple cubic lattice
Parameters
----------
shape : array_like
The number of unit cells in each direction. A unit cell has 1 vertex
at its center.
spacing : ... |
"""
Basic Math
==========
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
__all__ = [
'blank',
'clip',
'constant',
'difference',
'fraction',
'invert',
'normalize',
'scaled',
'summation',
'product',
]
def blank(target):
"""Blank model used in PN... |
#! /usr/bin/env python3
# vendredi 15 février 2019, 08:21:33 (UTC+0100)
# Écrivez un programme qui affiche la température la plus proche de 0 parmi les données d'entrée. Si deux nombres sont aussi proches de zéro, alors l'entier positif sera considéré comme étant le plus proche de zéro (par exemple, si les températur... |
import shutil
import os.path
import os
def augmented_move(target_folder, *filenames, verbose=False, **specific):
"""The first argument is a target folder,
and the default behavior is to move all remaining non-keyword argument files into
that folder. Then there is a keyword-only argument, verbose, which te... |
# // Time Complexity : O(n)
# // Space Complexity : O(1)
# // Did this code successfully run on Leetcode : Yes
# // Three line explanation of solution in plain english
# first iterate through the array and generate a product from the left hand side of the element
# next, generate the product from right hand side and ke... |
import math
class Primes:
"""Class that generates primes up to specified number
Uses Sieve of Eratosthenes to generate the list of primes
>>> primes = Primes(20)
>>> [prime for prime in primes]
[2, 3, 5, 7, 11, 13, 17, 19]
"""
def __init__(self, up_to: int):
"""Generates a list ... |
n = int(input('Insira o número o qual você queira ver o fatorial: '))
c = n-1
f = n
while c != 1:
f = f*c
c = c-1
print('O fatorial de {} é igual a {}'.format(n, f))
|
import random
n = int(input("""========JOKENPÔ========
Escolha a sua opção:
[1]Pedra
[2]Papel
[3]Tesoura
"""))
ncp = random.randrange(1,3)
if n == ncp:
print('Empate!')
elif n == 1 and ncp == 2:
print('Jogador perdeu para o computador: Pedra vs Papel!')
elif n == 1 and ncp == 3:
print('Jogad... |
s = 0
for c in range(0, 6):
si = int(input('Digite um valor: ' ))
if (si%2) == 0:
s += si
print('A soma de todos os valores pares é: {}'.format(s))
|
def leiaInt(n):
num = (input(n))
while num.isdigit() != True:
print('ERRO! Digite um número inteiro válido')
num = input('Digite um número: ')
if num.isdigit() == True:
break
return(num)
#Programa Principal
n = leiaInt('Digite um número: ')
print(f'Você acabou de digit... |
import math
while True:
print("""--------------------
--CAIXA ELETRÔNICO--
--------------------""")
v = int(input('Qual é o valor que você quer sacar? '))
vr = v
if (v/50) >= 1:
print(f'Total de {math.floor((v)/50)} cédulas de R$50')
vr = v%50
if ((vr)/20) >= 1:
print(f'Total... |
n1 = float(input('Insira a primeira nota: '))
n2 = float(input('Insira a segunda nota: '))
m = (n1+n2)/2
if m < 5.0:
print('Reprovado')
elif m >= 5 and m < 7:
print ('Recuperação')
else:
print('Aprovado')
|
gols = []
total = 0
jogador = {}
jogador['nome'] = str(input('Nome do Jogador: '))
partidas = int(input('Quantas partidas Joelson jogou? '))
for c in range(0, partidas):
gols.append(int(input(f'Quantos gols na partida {c}? ')))
total += gols[c]
jogador['gols'] = gols
jogador['total'] = total
print('-='*30)
pri... |
pilha = []
conte = 0
contf = 0
exp = str(input('Digite a expressão: '))
for c, v in enumerate(exp):
if v == ('('):
pilha.append(v)
elif v == (')'):
pilha.append(v)
pa = pilha.count('(')
pf = pilha.count(')')
for c, v in enumerate(pilha):
if c == 0 and v!= ('('):
conte += 1
pr... |
cont = ()
lista = []
while True:
valor = int(input('Insira um valor: '))
lista.append(valor)
cont = str(input('Quer continuar [S]/[N]'))
if cont in ('Nn'):
break
lista.sort(reverse=True)
print(f'Foram inseridos {len(lista)} valores \n A lista em ordem decrescente: \n {lista}')
if 5 in lista:
... |
#Sanjidah Abdullah
#sabdull002@citymail.cuny.edu
template = "If it VERB1 like a NOUN and VERB2 like a NOUN, it probably is a NOUN."
noun = input("Enter a noun: ")
template = template.replace("NOUN", noun)
verb1 = input("Enter a verb: ")
template = template.replace("VERB1", verb1)
verb2 = input("Enter another verb: "... |
#Sanjidah Abdullah
#sabdull002@citymail.cuny.edu
import folium
import pandas as pd
inFile = input('Enter CSV file name: ')
outputFile = input('Enter output file: ')
#Read in the CSV file into a dataframe:
fileName = pd.read_csv(inFile)
print(fileName["TIME"])
#Set up a new map object, centered at Hunter College,
#... |
#Sanjidah Abdullah
#sabdull002@citymail.cuny.edu
insulin = input("Enter a DNA string: ")
#Compute the length
length = len(insulin)
print("Length is", length)
#Compute the GC-content:
numC = insulin.count('C')
numG = insulin.count('G')
gc = (numC + numG) / length
print("GC-content is", gc)
#Compute the position of f... |
#Sanjidah Abdullah
#sabdull002@citymail.cuny.edu
import matplotlib.pyplot as plt
import numpy as np
pic = input("Enter file name: ")
ca = plt.imread(pic) #Read in image
countSnow = 0 #Number of pixels that are almost white
t = 0.75 #Threshold for almost white-- can adjust between 0.0 an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.