text stringlengths 37 1.41M |
|---|
s = n = 0
while True:
n = int(input('Digite um número: '))
if n == 999:
break
s += n
# print('A soma dos números é {}'.format(s))
print(f'A soma dos números é {s}')
|
from random import randint
from time import sleep
from math import factorial
# Exercicio 57
print('=' * 20, 'Primeiro exercicio', '=' * 20)
sexo = str(input('Digite seu sexo: [M/F] ')).upper().strip()[0] # O [0] serve para pegar apenas a primeira letra do que for digitado
while sexo not in 'MmFf':
sexo = str(input... |
import math
# Author: Parul
# get confidence bounds from operators
def isMod(element):
"""
A utility function to check if 'element' is mod function
:param element: expr_tree node
:return: bool
"""
if element == "abs":
return True
return False
def eval_math_bound(l_x, u_x, l_y=None,... |
import numpy as np
from inequalities import *
from get_bounds import *
# Author: Parul Gupta
####################
# Construct Parser #
####################
class expr_tree:
"""
An expression tree node
"""
def __init__(self, value):
"""
Constructor to create a node
:param value:... |
def merge_the_tools(string, k):
def Remove_the_common_elements(lst_aftr_devision): #function for removing common elements from list
final_list = []
for num in lst_aftr_devision:
if num not in final_list:
final_list.append(num)
return final_list
for ... |
###
#
# Pulls down and manages data.
#
# Right now I just want to be able to abstract downloading a historical CSV
# for a single company. Currently using Google finance.
#
###
import requests
import csv
class DataManager:
def __init__(self):
pass
def downloadData(self, symbol, range=None):
"""
Return a c... |
# Yedoh Kang <kang.yedoh@gmail.com> Period 06
# HW #24
# 1. encrypt and decrypt longer strings
sequence = 'abcdefghijklmnopqrstuvwxyz'
def encryptCaesar (plaintext):
plainAt = sequence.find (plaintext)
if plainAt == -1:
return plaintext
else:
cipherAt = (plainAt - 3) % len (sequence)
... |
###########################################################################
##### SET made using an dynamic array, called list in Python3
###########################################################################
class Set(object):
# When the set gets initialized with items,
def __init__(self, items = None):
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
if not temp:
print("Empty LinkedList")
while temp:
pri... |
"""
Algo List:
1- PivotBinarySearch : Searchs the the element in a Sorted Roated array in O(logn) time.
2- searchSortedRotated: Improved version of the above algo.
3- findMin:Finds the element in Sorted and roated array
"""
"""
Description: Search in sorted Rotated Array.
Method#1:
1- Find the pivot element
2- divi... |
'''
Description: Array/String Reversal.
'''
"""
Method#1: Iterative Method
Time complexity: O(n)
Space Complexity: O(1)
"""
def iterative_reversal(arr):
length = len(arr)
# Step-1: initialize variables start and end
start = 0
end = length -1
# Step-2: run loop with below condition and keep swappi... |
"""
Problem Description: Rearrange array in alternating positive & negative items with O(1) extra space
arrange Array in an alternate fashion such that every positive number is followed by negative and vice-versa.
URL-> https://ide.geeksforgeeks.org/index.php
Order of element doesn't matter
"""
'''
Approach1: Doesn... |
"""
任务调度器
可以实现定时任务
安装:
内置模块,无需安装
参考:
中文文档 https://docs.python.org/zh-cn/3/library/sched.html
"""
import time, sched, datetime
# 重试间隔(秒)
RETRY_INTERVAL = 200
# 新建调度器
s = sched.scheduler(time.time, time.sleep)
def get_task_interval():
"""获取现在到明天零点的秒间隔
Return:
number: 现在到明天零点的秒数
"""
# 获取现在的... |
"""
creat gamma distribution n(r)
author:ida
date:2021-10-26
"""
import numpy as np
from scipy.special import gamma,factorial
import matplotlib.pyplot as plt
import matplotlib as mpl
print(gamma(1.5))
N=5
x = np.linspace(0,N,50)
y= gamma(x+1)
plt.figure(facecolor='w')
plt.plot(x, y, 'r-', x, y, 'ro', ... |
"""A cache for indexing static data on the filesystem."""
import os
import json
import hashlib
from collections.abc import MutableMapping, Sequence
class AssetsCache(MutableMapping):
"""A cache for indexing static data on the filesystem."""
def __init__(self, cachefile, srcfile, *args, **kwargs):
"""... |
# 7-6. Three Exits: Write different versions of either Exercise 7-4 or Exercise 7-5 that do each of the following at least once:
#• Use a conditional test in the while statement to stop the loop.
#• Use an active variable to control how long the loop runs.
#• Use a break statement to exit the loop when the user ente... |
#5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list.
#• Make a list of your three favorite fruits and call it favorite_fruits.
#• Write five if statements. Each should check whether a certain kind of fruit is in you... |
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.
pet1 = {'pet_name':'g... |
# 3-10. Every Function: Think of something you could store in a list. For example, you could make a list of mountains, rivers, countries, cities, languages, or anything else you’d like. Write a program that creates a list containing these items and then uses each function introduced in this chapter at least once.
list... |
#6-5. Rivers: Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be 'nile': 'egypt'.
#• Use a loop to print a sentence about each river, such as Nile runs through Egypt.
#• Use a loop to print the name of each river included in the dictionary.
#• Use a l... |
# 2-9. Favorite Number: Store your favorite number in a variable. Then, using that variable, create a message that reveals your favorite number. Print that message.
number = 21
print("My favorite number is " + str(number) + ".") |
# 8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the function make_great() with a copy of the list of magicians’ names. Because the original list will be unchanged, return the new list and store it in a separate list. Call show_magicians() with each list to show that you have one list of the o... |
import urllib2
def translate(to_translate, to_langage="auto", langage="auto"):
'''Return the translation using google translate
you must shortcut the langage you define (French = fr, English = en, Spanish = es, etc...)
if you don't define anything it will detect it or use english by default
Example:
print(transla... |
'''
Interval Tree implementation in Python
Copyright (C) 2010 Tyler Kahn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This... |
class NameTooShortError(ValueError):
pass
def validate(name):
if len(name)<5:
raise NameTooShortError('name is too short')
username=input("Enter ur name:")
validate(username)
print(f"hii{username}") |
def common_element(l,k):
list1=[]
for i in l:
for j in k:
if i==j:
list1.append(i)
return list1
num=[1,2,5,8]
num1=[1,2,7,6,8]
print(common_element(num,num1))
|
sum=0
i=0
num=input("enter number containg more than one digit:")
num1=(len(num))
while i<=num1-1:
sum=sum+int(num[i])
i+=1
print(sum)
|
fruits=['apple','banana','orange','kiwi','apple','kiwi']
for i in fruits:
print(i,end=" ")
#while loop
i=0
while i<len(fruits):
print(fruits[i],end=" ")
i+=1
|
string="upasana"
print(string[0])
string1=string.replace('u','U')
print(string)
print(string1)
string+=" majhi"
print(string)
age=12
age=age*2#age*=2
print(age)
string="upasana"
print(string[0:-1])
|
def is_palindrome(word):
if word[0::1]==word[::-1]:
return "palindrome"
else:
return "Not palindrome"
print(is_palindrome("madam"))
print(is_palindrome("mmmmm")) |
for i in range(1,11):
print(f"hello:{i}\n")
for i in range(10):
print(f"hello:{i}\n")
for i in range(11):
print(f"hello:{i}\n") |
name="maggie"
for i in range(len(name)):
print(name[i])
for i in name:
print(i)
for i in "upasana":
print(i)
num=input("enter name")
sum=0
for i in num:
sum+=int(i)
print(sum) |
# def my_map(fun,l):
# new_list=[]
# for item in l:
# new_list.append(fun(item))
# return new_list
# print(my_map(lambda a:a**2,[1,2,3,4,5]))
#function returning function
# def outer_fun(msg):
# def inner_fun():
# print(f"The message is :{msg}")
# return inner_fun
# variable=outer_fu... |
class Person:
count_instance=0 #cls ,cls attribute
def __init__(self,first_name,last_name,age):
Person.count_instance+=1
self.F_name=first_name
self.S_name=last_name
self.age=age
@classmethod
def from_string(cls,string):
fname,lname,age=string.split(",")
r... |
matrix=[[1,2,3],[4,5,6],[7,8,9]]
for i in matrix:
print(i)
for i in matrix:
for j in i:
print(j)
#access the list element
print(matrix[0][0])
|
name=input("Enter ur name:")
i=0
repeat=" "
while i<len(name):
if name[i] not in repeat:
repeat+=name[i]
print(f"{name[i]}:{name.count(name[i])}")
i+=1 |
def spiral(mat):
if not mat:
return "Matrix not found"
xmax, xmin, ymax, ymin = len(mat[0]), 0, len(mat), 0
right,left,up,down = False, False, False, False
num_objs = 0
for obj in mat:
num_objs+=len(obj)
collec = []
if not collec:
right = True
while len(collec) ... |
#Find pairs in an integer array whose sum is equal to 10
def make_ordered_pair(pair):
if pair[0] <= pair[1]:
return [pair[0], pair[1]]
else:
return [pair[1], pair[0]]
def find_pairs_equaling_target_num(num_inputs, target_num):
pair_collector=[]
for i, num in enumerate(num_inputs):
... |
#Determine if 2 Strings are anagrams
# def check_if_anagram_or_nah(first_word, second_word):
# if sorted(second_word) == sorted(first_word):
# return True
# else:
# return False
#
# print(check_if_anagram_or_nah('racecar','raccear'))
def check_anagram(first_word, second_word):
char_lookup =... |
#Day_02_04_rnn_4_1_comprehension.py
# 컨프리헨션 : 집계 함수에 저달할 컬렉션을 만드는 한 줄짜리 반복
import random
for i in range(5):
print(i)
for i in range(5):
if i % 2:
print(i)
[i for i in range(5)]
(i for i in range(5))
{i for i in range(5)}
print([i for i in range(5)])
print([0 for i in range(5)])
print(['yes' for i i... |
def insert(ch):
return 1
def delete(ch):
return 1
def sub(src, tgt):
if src == tgt:
return 0
else:
return 2
def pretty_print(mat, target, source):
print '-', '-', ' '.join([ch for ch in target]);
source = ''.join(["-", source])
for sc, line in zip(source, mat):
pri... |
# imports
import math
import sys
print("This program offers entropy calculations for three different types of input.")
def entropyCalc(val):
entropy = 0
entropy += -(val * math.log2(val))
return entropy
def strToFloat(string):
arr = string.split("/")
flt = float(int(arr[0]) / int... |
#!/usr/bin/python
import re
if __name__ == "__main__":
word_map = {}
valid_word = re.compile("[a-z]+")
with open("content.lst", "r") as content:
for line in content:
words = line.strip().split(' ')
for word in words:
word = word.lower()
word... |
from General import *
import os
if __name__ == "__main__": #Main function
speed(9) #turtle speed
pOn = True #application switch
gen = General() #instance of general class
gen.DrawContainer(200) # draw container on screen
# Homework requests
while(pOn):
#Interface of program
... |
Dict={'abc':18,'atul':23,'alex':45,'jones':53}
print(Dict);
print((Dict['alex']));
Dict.update({'atul':25});
print(Dict);
print("Deleting Keys from Python");
#del Dict['charlie'];
print(Dict);
print("items method returns key value by tuple");
print(list(Dict.items()));
Boys={'scott':44,'abc':18};
print... |
class InsufficientFundsError(RuntimeError):
def __init(self,msg):
self.args=msg;
from abc import ABC , abstractmethod
class Account(ABC):
def __init__(self,mname,amt):
self.__name=mname;
self.__balance=amt;
def getBalance(self):
return self.__balance;
def getName(self):
ret... |
class LineItem:
def __init__(self,mno,mname,mprice,mqty):
self.__no=mno;
self.__name=mname;
self.__price=mprice;
self.__qty=mqty
def setID(self,value):
self.__no=value;
def setName(self,value):
self.__name=value;
def setPrice(self,value):
self.__price=value
def setQty(self,value):
se... |
class FixedDeposit:
def __init__(self,amt,duration,obj):
self.__principal=amt;
self.__duration=duration;
self.__temp=obj;
def interest(self):
return self.__principal*self.__duration*self.__temp.rate();
from abc import ABC, abstractmethod
class Scheme(ABC):
@abstr... |
print("Prime no");
x=int(input("Enter a no:"));
flag=1;
if (x>1):
for i in range (2,(x//2)+1):
if (x%i==0):
flag=0;
if (flag==0):
print(x, " no is not a prime");
else :
print(x, " no is prime"... |
import math
from math import sqrt
'''
【程序12】
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对整数进行逐步分解,找到所有质因数;
1、判断该数不等于N,否则输出
2、如果该数能被N整除,就输出N的值,并用n除以k的商,作为新的正整数你n,
3、如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
'''
class FactorizationPrimeFactor():
def factorization_prime_factor(self):
number... |
import math
from math import sqrt
'''
【程序8】
题目:输出9*9口诀。
程序分析:分行考虑,两个循环,大循环控制行,小循环控制列,注意输出格式化
'''
class Multiplication():
def multiplication(self):
for i in range(1,10):
for j in range(1,i+1):
print('%d * %d = % -4d'%(j,i,i*j),end=' ')
print('\n')
if __name__==... |
#1 Defina uma função addSuffix(suf,nomes) que retorne a lista de nomes com o sufixo suf adicionado. Exemplos:
def addsufix(x,s):
return [s+x for w in s]
#2 Escreva uma função countShorts(words), que receba uma lista de palavras e retorne a quantidade de palavras dessa lista que possuem menos de 5 caracteres.
def c... |
def GetDivnum(trinum):
num=0
temp=trinum
div2num=0
mulodd=1
if trinum==1: return 1
while temp%2==0:
temp=temp//2
div2num+=1
k = 1
while temp>1:
k += 2
divoddnum=0
while temp % k == 0:
temp = temp // k
divoddnum += 1
... |
from math import sqrt
end = 2000000
test = list(range(0,end+1))
test[0] = test[1] = 0
def is_prime(num):
if num is 2 or 3 : return True
for i in range(2,int(sqrt(num)+1)):
if num%i==0 : return False
return True
for i in test:
if i is 0 : continue
if is_prime(i):
for j in range(i*... |
def reverseString(x):
if x == "":
return ""
else:
return x[::-1]
num = input("Enter number: ")
print(reverseString(num))
|
num=0
pos=0
i=0
def is_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
while num<1000:
i+=1
if is_prime(i) == True:
print(i,end="\t")
pos+=1
... |
import unittest
from translator import englishtofrench, englishtogerman
class TestEnglishToFrench(unittest.TestCase):
def test1(self):
self.assertEqual(
englishtofrench("This is a simple case"),
"C'est un cas simple")
self.assertEqual(
englishtofrench("The rai... |
import random
import matplotlib.pyplot as plt
# n = input('How many students we have:')
d = []
for n in range(1,100):
count = 1000.000
for i in range(1000):
a = []
for j in range(n):
c = random.randint(1, 365)
# print c
a.append(c)
b = list(set(a))
... |
''''231. Power of Two QuestionEditorial Solution My Submissions
Total Accepted: 102366
Total Submissions: 264848
Difficulty: Easy
Given an integer, write a function to determine if it is a power of two.'''''
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool... |
# 让类支持比较操作
from functools import total_ordering
from abc import ABCMeta, abstractmethod
@total_ordering
class Shape(object):
@abstractmethod
def area(self):
pass
def __lt__(self, obj):
if not isinstance(obj, Shape):
raise TypeError('obj is not Shape')
return self.ar... |
# 通过实例方法名字的字符串调用方法
from lib1 import Circle
from lib2 import Rectangle
from lib3 import Triangle
def getArea(shape):
for name in ('area', 'getArea', 'get_area'):
f = getattr(shape, name, None)
if f:
return f()
shape1 = Circle(2)
shape2 = Triangle(3,4,5)
shape3 = Rectangle(6,4)
shapes ... |
# 解析/构建 XML文档
# from xml.etree.ElementTree import parse
# f = open('demo.xml')
# et = parse(f)
# root = et.getroot()
# for child in root:
# print(child.get('item'))
# list(root.iter())
# ....
from xml.etree.ElementTree import Element, ElementTree
from xml.etree.ElementTree import tostring
e = Element('Data... |
X = input("enter value of x ")
Y = input("enter value of y")
temp = X
X=Y
Y = temp
print("value of X",X)
print("value of Y",Y)
|
num = int(input("Enter your four digit number "))
r=0
r = r + num%10
num = num//10
r = r + num%10
num = num//10
r = r + num%10
num = num//10
r = r + num%10
num = num//10
print("the sum is ",r)
|
year=int(input("enter your year"))
if year%400==0:
print("year is leap year")
elif year%4==0 and year%100!=0:
print("year is leap year")
else:
print("invaild")
|
"""Pi verification"""
from decimal import Decimal as D
def correct_decimal_points(pi: D, file_name: str = "src/pi.txt") -> int:
"""Counts correct decimal points of approximated pi based on verification file
:param pi: approximated pi
:type pi: Decimal
:param file_name: path to verification file (deci... |
# -*- coding: UTF-8 -*-
# Napis funkci, ktera ti pro dve zadane delky odvesen pravouhleho trojuhelnika vypocita delku prepony. (TIP budes potrebovat Pythagorovu vetu)
from math import sqrt
a = int(input('Zadej delku prvni odvesny: '))
b = int(input('Zadej delku druhe odvesny: '))
c = sqrt(a**2 + b**2)
print('Delka p... |
"""
Реализовать два небольших скрипта:
а) итератор, генерирующий целые числа, начиная с указанного,
б) итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл
не должен быть бесконечным. Необходи... |
"""
Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность),
income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия,
например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность) на базе ... |
"""Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text."""
def int_func(user_string_list):
tmp_str = " "
return tmp_str.join(user_string_list).title()
def main():
pass
user_strin... |
"""
Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку.
Подсказка: использовать функцию range() и генератор.
"""
def main():
new_list = [i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0]
print(new_list)
print("Программа завершена")
if __name... |
"""
Реализовать программу работы с органическими клетками, состоящими из ячеек.
Необходимо создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий количеству
ячеек клетки (целое число).
В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (__add__()),
вычита... |
import heapq
import inspect
class SimpleVector(dict):
"""
A vector object. This is a wrapper class for the
standard python dictionary.
"""
def __getitem__(self, index):
self.setdefault(index, 0)
return dict.__getitem__(self, index)
def normalize(self):
"""
Standard normalization function.
@return the... |
#!/usr/bin/env python
def Append(a, x):
a.append(x)
a.sort(key = lambda x:x[0])
a.sort(key = lambda x:x[2],reverse = True)
if __name__ == '__main__':
# reg, location_seq, score, local_rank, final_rank
final_list = []
locations = int(raw_input())
for i in xrange(locations):
testees =... |
#!/usr/bin/env python
def get_digits(x, n):
x_origin = x
i = 0 # position of the first non-zero digit
j = 0 # beginning of the dot
# 0.025
# 00.025
# trim the leading 0's
while i < len(x):
if x[i] == '0':
i += 1
elif x[i] == '.':
j = i
i ... |
#!/usr/bin/env python
if __name__ == '__main__':
string = raw_input()
digits = set()
for i in string:
digits.add(i)
double_it = str(2 * int(string))
digits2 = set()
for i in double_it:
digits2.add(i)
if digits == digits2:
print 'Yes'
else:
print 'No'
... |
#!/usr/bin/env python
import os
if __name__ == '__main__':
num = raw_input();
i = 0
while i < int(num):
numbers = raw_input().strip()
li = numbers.split(' ')
if int(li[0]) + int(li[1]) > int(li[2]):
print "Case #%d: %s" %(i + 1, 'true')
else:
... |
def iter_palindrome(s):
for i in range(0, len(s)/2):
if s[i] != s[-(i+1)]:
return False
return True
print iter_palindrome('')
#>>> True
print iter_palindrome('abab')
#>>> False
print iter_palindrome('abba')
#>>> True
|
# Write a procedure, rotate which takes as its input a string of lower case
# letters, a-z, and spaces, and an integer n, and returns the string constructed
# by shifting each of the letters n steps, and leaving the spaces unchanged.
# Note that 'a' follows 'z'. You can use an additional procedure if you
# choose to as... |
class List:
name = 'default'
contact = 'default'
adress = 'default'
def __init__ (self, name,contact,adress):
self.name = name
self.contact = contact
self.adress = adress
Turat = List('Turat','0780546004','Asanbay')
Kirill = List('Kirill','0564604650','8 mkr')
Taalay = List('Taal... |
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
rate = float(rate)
if(h>40):
pay = 40*rate + 1.5*(h-40)*rate
else:
pay = rate*h-40
print(pay) |
import random
#系统采样
from example.code_3.random_sampling import RandomSampling
def SystematicSampling(dataMat,number):
length=len(dataMat)
k=int(length/number)
sample=[]
i=0
if k>0 :
while len(sample)!=number:
sample.append(dataM... |
class Carrinho:
def __init__(self):
self.produtos = []
def adiciona (self,produto):
self.produtos.append(produto)
def lista(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
for ... |
class Whell:
def CreateWell(self):
print('Колеса установлены')
class BodyCar:
def CreateBodyCar(self):
print('Кузов автомобиля собран')
class Engine:
def CreateEngine(self):
print('Двигатель установлен')
class Salon:
def CreateSalon(self):
print('Салон установлен')
cl... |
class Node:
"""A node of a linked list"""
def __init__(self, node_data):
self._data = node_data
self._next = None
self._prev = None
def get_data(self):
"""Get node data"""
return self._data
def set_data(self, node_data):
"""Set node data"""
self... |
from Node import Node
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
self._size = 0
def is_empty(self):
return self.head == None
def add(self, item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
if... |
"""
• Write a script that figures out the number of business days between
two dates. Business days should only take into account weekends, not holidays.
"""
import pandas as pd
from datetime import datetime
from random import randrange as rr
""" For USER input """
# print('Please Enter the first date')
# year1 = int... |
"""coding: utf-8
Name: SudokuSolver
Description: An algorithm for solving given sudoku board if there exist a solution. Will use backtracking algorithm.
Input: numpy.array
Output: numpy.array
Remarks:
Each cell can have position (i, j) from (0, 0) to (8, 8)
Each board has 9 * 9 = 81 cells so I need to create condition... |
a = "hello"
b = "hellO"
if a == b:
print("yes")
else:
print("no")
if a == "hello":
print("yass")
|
import numpy as np
import pandas as pd
# # SERIES ->-similar to numpy arrays , but can be accessed through lables
# lables = ['a','b','c']
# items = [10,20,30]
# # Series creates a kind of dict
# # fun signature Series(list_of_items , list_of_lables)
# print(pd.Series(data=items))
#
# print("*"*20)
# print(pd.Series(... |
"""
Defines Channel() helper class.
"""
from message import Message
from datetime import datetime
import json
class Channel:
def __init__(self, visible_name, cleaned_name):
self.name = visible_name
self.cleaned_name = cleaned_name
self.messages = list()
self.users = list()
... |
# Program for displaying Roman Numerals. (1 through 10)
# CTI_110
# P3HW1_Roman Numerals
# Reginald Richardson
# September 17, 2018
# Ask for an integer in-between 1 to 10.
integer = int(input('Enter an integer within the range of 1 to 10: '))
#If value parameters.
if integer == 1:
print('The Roman... |
# Calculating male and female class percentages
# 09/10/18
# CTI-110 P2HW2 - Male Female Percentage
# Reginald Richardson
# Male and female percentage formula.
Male_value = float(input('Enter the number of males in the class'))
Female_value = float(input('Enter the number of females in the class'))
TotalStuden... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
i = len(a) - 1
res = []
while i >= 0:
res.append(a[i])
i -= 1
return res
if __name__ == '__main__':
fptr = open("result.txt", 'w')
arr_coun... |
def miniMaxSum(arr):
arr.sort()
print(sum(arr[:4]), sum(arr[-4:]))
a = [1, 3, 5, 7, 9]
miniMaxSum(a)
a = [1, 2, 3, 4, 5]
miniMaxSum(a)
a = [5, 4, 1, 3, 2]
miniMaxSum(a) |
def kangaroo(x1, v1, x2, v2):
# if they have the same speed, since x2 > x1, v1 will never reach v2
if v1 == v2:
return "NO"
res = (x2 - x1) / (v1 - v2)
resmod = (x2 - x1) % (v1 - v2)
if res < 0:
return "NO"
else:
if resmod == 0:
return "YES"
... |
# In this We will try to check wheter Median Filter is LTI system or not
import numpy as np
import matplotlib.pyplot as plt
def Add_Noise(signal,mu = 0,sigma = 1): # Function to add noise
gaussian_noise = np.random.normal(0, 1, signal.shape[0])
signal_noise = signal + gaussian_noise
return signal_noise
... |
planet_list = ["Mercury", "Mars"]
planet_list.append("Jupiter")
planet_list.append("Saturn")
planet_list.extend(["Uranus", "Neptune"])
planet_list.insert(1, "Venus")
planet_list.insert(2, "Earth")
planet_list.append("Pluto")
del planet_list[-1]
rocky_planets = planet_list[0:4]
print("rocky_planets", rocky_planets... |
class Garden:
"""Object modeling a garden"""
def __init__(self, surface, soilType, location):
self.surface = surface
self.vegetables = list(tuple())
self.fruits = list(tuple())
def DisplayGardenContent(self):
for var in self.vegetables:
print ("there are " + str... |
"""
Use iter() to create a generator from an iterable.
"""
words = [(455, 'sea'),
(336, 'boat'),
(281, 'white'),
(1226, 'whale'),
(329, 'captain'),
(510, 'Ahab')
]
def add_bars(data):
"""Prints a horizontal bar every two lines."""
g = iter(data)
while... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.