text
stringlengths
37
1.41M
import sys class Logger(object): """ Logger class. Writes errors and info to the cmd line. """ def __init__(self, verbose=False): """ Initialize a logger object. Args: verbose (boolean): If True, the logger will print all status upd...
class GPA(): def __init__(self): self.gpa = 0.0 def get_gpa(self): return self.gpa def set_gpa(self, value): if value < 0.0: self.gpa = 0.0 elif value > 4.0: self.gpa = 4.0 else: self.gpa = value def get_letter(self): ...
""" This file contains psuedocode developed by together by the class one semester... """ # Open the file # Read through it character by character # One way to do this for this program, is to read line by line # and then call line.strip() to get rid of any whitespace # for (line in ...) # If current character is ...
""" File: ta03-solution.py Author: Br. Burton This file contains a Rational class to hold fractions and demonstrates their basic functions. """ class Rational: """ The Rational class stores a rational number (i.e., fraction) in the form of a top and bottom number. """ def __init__(self): ""...
def findBraces(): user = 'stacks06.txt' jOpen = open(user, "r") stack = [] for i in jOpen: k = i.strip() for ch in k: # if current character is an open one just add to the stack if ch == '(' or ch == '[' or ch == '{': stack.append(ch) #...
class Point: def __init__(self): self.x = 0 self.y = 0 def prompt_for_point(self): self.x = int(input('Enter x: ')) self.y = int(input('Enter y: ')) def display(self): print('Center:') print('({}, {})'.format(self.x, self.y)) class Circle(Point): def _...
""" File: asteroids08.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids08 game. """ import math from abc import ABC from abc import abstractmethod import random import arcade # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT ...
""" File: asteroids08.py Original Author: Br. Burton Designed to be completed by others This program implements the asteroids08 game. """ import math from abc import ABC from abc import abstractmethod import random import arcade # These are Global constants to use throughout the game SCREEN_WIDTH = 800 SCREEN_HEIGHT ...
class Book: def __init__(self): self.title = '' self.author = '' self.publication_year = 0 def prompt_book_info(self): self.title = input('Title: ') self.author = input('Author: ') self.publication_year = input('Publication Year: ') def display_book_info(sel...
import time def insert(word, pos, char): if pos == 0: return char + word elif pos == len(word): return word + char return word[:pos] + char + word[pos:] def result(word, letters): start, end = 0, len(letters) max_pos, pos = len(word), 0 while start < end: ...
# Time: O(n) # Space: O(n) # Given n processes, each process has a unique PID (process id) # and its PPID (parent process id). # # Each process only has one parent process, but may have one or more children processes. # This is just like a tree structure. Only one process has PPID that is 0, # which means this proces...
""" Implements the observer pattern and simulates a simple auction. """ import random class Auctioneer: """ The auctioneer acts as the "core". This class is responsible for tracking the highest bid and notifying the bidders if it changes. """ def __init__(self): """ Initializes au...
import abc class Item(abc.ABC): """ Abstract representation of an Item """ def __init__(self, name, description, product_id): """ Initializes variables. :param name: string :param description: string :param product_id: string """ print("Item") ...
class Order: """ Class that represents an order received. """ def __init__(self, order_number, product_id, item, name, factory_object, **product_details): """ Initializes Order object. :param order_number: int :param product_id: string, combination of alphabet and numbers...
from enum import Enum, auto class Colours(Enum): """ Represents colours of particular store items that come in different colours (Robot Bunny, Easter Bunny, Candy Cane). """ ROBOT_BUNNY_BEGIN = ORANGE = auto() EASTER_BUNNY_BEGIN = BLUE = auto() PINK = auto() ROBOT_BUNNY_END = WHITE = a...
class User: """ This class represents a FAM user and their user details. """ def __init__(self, name, age, account, budgets, lock_status): """ Initialize user details. :param name: a string :param age: an int :param account: an Account object :param budg...
""" (6 Marks) The code below reads a series of strings from data.txt and saves them into file_names list It then does the following using a SINGLE-LINE list comprehension: 1. Determines if the string contains a json or txt extension 2. Creates a list containing the [file name string and FileType enum] and assi...
import json # import json module # with statement with open('result.json', 'rt', encoding='UTF-8-sig') as json_file: json_data = json.load(json_file) print(json_data[0]) print(type(json_data[0])) questions = [] for i in range(len(json_data)): for key in json_data[i].keys(): questions.append(key) prin...
from datetime import datetime import time import random odds = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59 ] for i in range(3): right_this_minute = datetime.today().minute if right_this_minute in odds: print("This minute ...
vowels = ['a','e','i','o','u'] word = input("请输入一个英文单词:") found = {} #建立一个空字典 # found['a'] = 0 found['e'] = 0 found['i'] = 0 found['o'] = 0 found['u'] = 0 #found['e'] = found['e'] + 1 #递增e的频度记数 #fouond['e'] += 1 #+=同样能递增e的频度记数,相较上面更为简洁 for letter in word: #利用迭代计算单词中元音字母出现次数 if letter in vowels: ...
threes = list(range(3,31,3)) for three in threes: print(three)
from users_class import User class Privileges(): '''New prvilege class to be use for admin and possibly more users''' def __init__(self, privileges=['can add post','can delete post','can ban user']): self.privileges = privileges def show_privileges(self): print("The administator: " + str(self.privileges)) ...
languages = { 'tristan' : 'javascript', 'charla' : 'java', 'terrence' : 'ruby', 'andrew' : 'c++', 'taylor' : 'python', 'dreezy' : 'sql', } new_applicants = ['sayi','kim','charla','andrew','matt'] for new_applicant in sorted(new_applicants): for name,language in languages.items(): if new_applicant == name: ...
#We're creating a restaurant class with a name and cuisine type class Restaurant(): '''A restaurant with a name and cuisine.''' def __init__(self,name,cuisine): '''Initializing name and cusine''' self.name = name self.cuisine = cuisine self.number_served = 0 def describe_restaurant(self): '''Describing t...
#!/bin/python3 def input_array(): array = [] while True: try: array.append(int(input())) except ValueError as er: print(er) except EOFError: return array def insertion_sort(array): """ insertion sort an array """ for j in range(1, len(array...
def aspect_ratio(val, lim): lower = [0, 1] upper = [1, 0] while True: mediant = [lower[0] + upper[0], lower[1] + upper[1]] if (val * mediant[1] > mediant[0]) : if (lim < mediant[1]) : return upper lower = mediant elif (val * mediant[1] ==...
import re import sys if len(sys.argv) is not 3: print("Incorrect usage") sys.exit(0) wordMap = {} textFname = sys.argv[1] #speech.txt outputFname = sys.argv[2] with open(textFname, 'r') as inputs: for line in inputs: line = line.strip() word = re.split('[- \' ; \t "]', line) for si...
# -*- coding:utf-8 -*- # 思路:遍历二叉树的同时交换左右子树的值,直至节点为None # 测试:空子树——返回 # 使用一个栈模拟递归调用 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Mirror(self, pRoot): if pRoot is None: return pRoot.left, pRoot.righ...
class Solution: def rectCover(self, number): if number <= 2: return number a, b = 1, 2 for i in range(1,number): a, b = b, a + b return a
# -*- coding:utf-8 -*- # 思路:迭代 # 测试样例:空链表 class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode # 迭代: def Clone(self, pHead): if not pHead: return newcode = RandomListNode(pHead.label)...
# 赋值——对象引用 # 例1: print('............赋值例1..............') x = 3.14 y = x print([id(item) for item in [x,y]]) # 输出x和y的地址,地址相同 print(x, y) x = 1.15 print([id(item) for item in [x,y]]) # 此时地址发生了变化,不再相同 print(x, y) # 两值也不再相等(不可变对象) # 例2 print('...........赋值例2...............') a = [1,3,4] a1 = a a2 = a a1[0] = 100 a2[1] = -...
# -*- coding:utf-8 -*- # 测试用例:空数组,全部未超过一般 class Solution: def MoreThanHalfNum_Solution(self, numbers): # 哈希表 if len(numbers) == 0: return 0 if len(numbers) == 1: return numbers[0] sign = len(numbers) / 2 data = {} for i in numbers: ...
x = input().split() n = int(input()) for i in range(n-1, len(x)): print(x[i], end=" ") for i in range(n): print(x[i], end=" ")
import time from datetime import datetime timings = [] def sort_array(arr): # Bubble sort n = len(arr) start = int(round(time.time() * 1000)) for k in range(n): for j in range(0, n - k - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] finis...
# -*- coding: utf-8 -*- """ Created on Fri Nov 27 19:33:53 2020 @author: Lenovo-PC """ """ def transitive_closure(a): closure = set(a) while True: new_relations = set((x,w) for x,y in closure for q,w in closure ) closure_until_now = closure | new_relations if closure_unt...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: li @license: Apache Licence @contact: liping19901114@163.com @site: @software: PyCharm @file: threading_event.py @time: 2018/5/25 17:42 @desc: 用红绿灯来模拟事件 """ import threading from time import sleep event = th...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: 1.0 @author: li @license: Apache Licence @contact: liping19901114@163.com @site: @software: PyCharm @file: python反射.py @time: 2018/5/23 23:10 """ class Dog(object): def __init__(self, name): self.name = name ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/10/19 22:54 # @Author : liping # @File : 二叉树高度.py # @Software: PyCharm\ def get_tree_length(input_list): tree_dict = {} tree_info = [] for node in input_list: k, v = node.split() tree_info.append([k, v]) k_list = [] ...
'''Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n(where n is the number of lines in the file).''' fp=open('test.txt','r+') content=fp.readlines() fp.seek(0) count=0 for line in content: count+=1 line=str(count) + ' ' + l...
def vowel_check(ch): list1=['a','e','i','o','u'] if ch in list1: return'True' return 'False' print vowel_check(raw_input('Enter the Character'))
class proceso: instrucciones= 0 memoria=0 numero=0 def __init__(self, instrucciones, memoria, numero): self.instrucciones= instrucciones self.memoria= memoria self.numero= numero def getNumero(self): return self.numero def setNumero(self, instrucci...
from Adventure.game_data import World, Item, Location from Adventure.player import Player def do_menu_action(action, location, player, world): ''' (str, Location, Player, World) -> None The function will do all the options in [menu], which includes the following: look inventory score quit ...
word = input('Enter first text: ') separator = input('Enter second text: ') if separator in word: # with arithmetics # start_index_for_cut = word.index(separator) + len(separator) # result = (word[start_index_for_cut:]).lstrip() # no arithmetics # result = word.partition(separator)[2].lstrip()...
class Aminal: #默认集成object #类属性 和实例化属性的区别在于类属性不用self,而实例化属性要self, 类属性可以被实例化属性调用,也可以被类属性调用 __eye = 2 b = 10 leg = [] def __init__(self,name,age): #实例化一个方法,在类实例化的时候被调用。 self.name = name self.age = age def run(self): print('在跑------') #调用 a = Aminal('ywy',25) #print(...
import time print(time.time()) #时间戳是从1970 1月1日 零点 print(time.ctime()) #打印 Sat Sep 22 10:32:33 2018 print(time.localtime()) #打印时间元祖,time.struct_time(tm_year=2018, tm_mon=9, tm_mday=22, tm_hour=10, tm_min=34, tm_sec=16, tm_wday=5, tm_yday=265, tm_isdst=0) print(time.localtime(1)) #和上面的格式一样,不过是1970 1-1 零点 print...
print('###########################################################') print(' ') print(' Author: Mufaro Simbisayi ') print(' ') print('#####################################...
# 高阶函数英文叫Higher-order function # Python内建了map()和reduce()函数 # map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回 def f(x): return x * x r = map(f, [1, 2, 3, 4, 5, 6]) print(list(r)) # map()传入的第一个参数是f,即函数对象本身。由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list L = [] for n ...
# File: grid.py # Author: Nathan Robertson # Purpose: Encapsulate a series of points which form a 2D grid. Is a sparse grid so only impasses are stored. class Grid: def __init__(self, impasses, min_point, max_point): self.impasses = impasses self.max_point = max_point self.min_poi...
import numpy as np def mundaneMath(first_num, last_num): sum=0 for i in range(first_num, last_num+1): ''' The latter number is last_num+1 bc range function doesn't count the last number. ''' if i%2 == 0: sum = sum + i else: continue print(sum) return sum if __name__ == "__main__": mundaneMath(1, 1...
x=20 y=30 if x<y: print('x is less than 20') #elif a=20 b=20 if a<b: print('a is less than b') elif a==b: print('a is equal to b')
story="my n.\nI live in nepal.\nI am\t a student" print(story) ### a=['1','6','66','6','manoj','ram','rajan'] a[4]='ramesh' print(a) #### name=[1,6,7,3,5,8,9,22,44,5] name.remove(6) print(name) #tuple t=[1,2,3,4,5] t1=(1) print(t1) # m1= int(input("Enter your marks 1:")) m2= int(input("Enter your marks 2:")) m3= int(i...
def main(): print("Hello world!") num = int(input("Please enter a number between 1 and 25: ")) while num < 1 or num > 25: num = int(input("Invalid number entered, must be between 1 and 25. Enter again: ")) for n in range(1, num+1): print(f"Number {n} cubed: {n**3}") print(f"Numbe...
# -*- coding: utf-8 -*- # python 2 # program napisal Miro - 4.4.2017 - naloga 8.2 # FIZZBUZZ print "" print "IGRA FIZZBUZZ" print "" izbor = raw_input("Vnesi vrednost med 1 in 100 : ") # vnesemo vrednost med 1 in 100 if int(izbor) < 1 or int(izbor) > 100: print "Števila ni med 1 in 100 !!!" pass el...
import dices class skill(object): """ Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the valu...
__author__ = "Lucas Blom" __email__ = "lucas.blom@maine.edu" __status__ = "beta" ''' ## UPDATE ME This program gathers movie data from a csv file, creates a pandas data frame with it, and a tkinter application to show all data or iterate through rows individually ''' import tkinter as tk import pandas as pd # defin...
import datetime import calendar class PayrollManagementSystem: def calculate_payroll(self, employees): print("Payroll Management System") print("=========================") for employee in employees: print(f"Employee #:{employee.id}\nEmployee Name :{employee.name}...
#6 a = int(input('Сколько километров пробежал спортсмен в первый день? ')) b = int(input('Сколько километров пробежал спортсмен в последний день? ')) c = 1 while a < b: a*= 1.1 c+= 1 print("Спортсмен достиг результата в", b, "км на", c, "день")
def computepay(hour, rate): if hour <=40: return hour*rate return 40*rate + (hour-rate)*1.5*rate h = int(input("Enter hours: ")) r = float(input("Enter rate: ")) print("Pay:",computepay(h,r))
numbers = [] while True: try: number = input("Enter a number: ") if number == "done": break number = int(number) numbers.append(number) except ValueError: print("Invalid input") print(sum(numbers), len(numbers), sum(numbers)/len(numbers))
#https://leetcode.com/problems/symmetric-tree/ class Solution: def isSymmetric(self, root: TreeNode) -> bool: return self.Aux(root, root) def Aux(self, t1, t2): if t1 is None and t2 is None: return True elif t1 is None or t2 is None: return False els...
a = 10 b = 9 # Addition of numbers print(a + b) # Subtraction of numbers print(a - b) # multiplication of numbers print(a * b) # Division operator print( a / b) # floor division print(a // b) # Modulo of both number mod = a % b # Power p = a ** b print(p)
''' A dummy script to test CI ''' import math def circle_area(radius): ''' Returns the area of a circle given its radius circle_area: Float -> Float ''' if radius < 0: raise ValueError("The radius cannot be negative.") if type(radius) not in [int, float]: # pylint: disable=C0123 ...
def pos_neg(a,b,neg): if not neg: if a*b < 0: return True else: return False else: if a < 0 and b < 0: return True else: return False print pos_neg(-1,2,False) print pos_neg(1,-2,False) print pos_neg(-1,-2,True)
# -*- coding: utf-8 -*- """ Created on Sat Jul 24 16:14:24 2021 @author: P Akash """ # importing libraries import pygame import random from enum import Enum from collections import namedtuple import sys # initializing pygame modules pygame.init() # initialize game font font = pygame.font.Font('ari...
def index_search(i, c): try: return matrix[i].index(c) except: None def word_search_in_matrix(matrix, word, array): w_len = len(word) r_row = True r_column = True for i in array: if i[1] + w_len - 1 <= len(matrix[i[0]]): for x in range(w_len): ...
class Solution: def intersection(self, nums1, nums2): return list(set(nums1) & set(nums2)) if __name__ == '__main__': print(Solution().intersection([4, 9, 5], [9, 4, 9, 8, 4])) # [9, 4]
class Solution: def reverseWords(self, str): reverse_words = [] for w in str.split(): reverse_words.append(w[::-1]) return " ".join(reverse_words) if __name__ == '__main__': print(Solution().reverseWords("The cat in the hat")) # ehT tac ni eht tah
class Card(object): suits = { 'c': 'clubs', 'd': 'diamonds', 'h': 'hearts', 's': 'spades' } values = { 1: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King' } def __init__(self, value,suit): self.value = value self.suit = suit ...
def maximum_product_of_three(lst): len_lst = len(lst) product = [] for i in range(len_lst-2): for j in range(i+1, len_lst-1): for k in range(j+1, len_lst): product.append(lst[i] * lst[j] * lst[k]) return max(product) if __name__ == '__main__': print(maximum_pro...
d = true while d == true: a = input("enter number 1") b = input("enter what you want to do:,*,/,+ or -") c = input("enter second number") if d = true while d == true: a = int(input("enter number 1")) b = input("enter what you want to do:,*,/,+ or -") c = int(input("enter second number")) if b == "/": ...
## (1) Import packages import numpy as np import pandas as pd import sys ## (2) Read training data train = pd.read_csv(sys.argv[1], header = None) # Delete column 0 train = train.drop(train.columns[[0]],1) ## (3) Create training feature DataFrame and outcome Series # Split features and outcome y = pd.Series(train.ix[...
import Stack import re def postfix(example): t_list = re.split('([^0-9])', example) stack = Stack.Stack() for t in t_list: if t == '' or t == ' ': continue elif t == '+': sum = stack.pop() + stack.pop() stack.puch(sum) elif t == '*': ...
class Stack: def __init__(self): self.stack = [] def size(self): return len(self.stack) def pop(self): if len(self.stack) != 0: return self.stack.pop() else: return None def push(self, value): self.stack.append(value) def peek(self)...
class Node: def __init__(self, v): self.value = v self.prev = None self.next = None class OrderedList: def __init__(self, asc): self.head = None self.tail = None self.ascending = asc def compare(self, v1, v2): # метод сравнения if v1 < v2: ...
# модель построения Графов class Vertex: def __init__(self, val): self.Value = val def __repr__(self): '''Метод упрощенного отображения объектов класса Vertex''' return 'V_{}'.format(self.Value) class SimpleGraph: def __init__(self, size): self.max_vertex = siz...
import unittest import Linked_List2 class LinkedList2Test(unittest.TestCase): def test_norm2(self): # тесты на создание и заполнение списка link_2 = Linked_List2.LinkedList2() # создание пустого списка self.assertIsNone(link_2.head) # проверка на содержание None в пустом списке link_2...
#7. Faça um Programa que leia um número e exiba o dia correspondente da semana. (1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido n1=int(input("Digite um numero de 1 a 7: ")) if n1 == 1: print("1 - Domingo") elif n1 == 2: print("2 - segunda") elif n1 == 3: print("...
a = [] print(a) a = [1] print(a) a = [1,2,3] print(a) a = [1,"1"] print(a) a.append(4) a.append(5) a.append(6) print(a) a.insert(1,"2") print(a) a = [6,7,8] b= [5,4,3] b.extend(a) print(b) print(a[0:3]) print(a[:3]) print(a[3:]) print(a[:]) a[0] = 7 print(a) ai = [1,2,3] print(ai) # Iterating over list...
""" Size of player's hand and the amount of cards on table """ HAND_SIZE = 3 TABLE_SIZE = 4 # suits and values declaration suits = ["CUPS", "COINS", "SWORDS", "CLUBS"] values = {"ACE":1, "TWO":2, "THREE":3, "FOUR":4, \ "FIVE":5, "SIX":6, "SEVEN":7, "FANTE":8, \ "HORSE":9, "KING":10} # String constants H...
# -*- coding:utf-8 -*- # author : Keekuun """ 斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入, 故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34... """ def fibo1(max): n, a, b = 0, 0, 1 while n < max: yield b # print(b) a, b = b, a + b n += 1 for i...
#!/usr/bin/python # -*- coding: UTF-8 -*- # author:FunC_ZKK """ 题目:一个标准的科学实验是,抛球并且看它能够弹跳多高。一旦球的“弹跳性”已经确定了, 这个比率值就会给出弹跳性的指数。例如,如果球从10米高落下弹跳到6米高,这个索引就是 0.6,并且球在一次弹跳之后总的运动距离是16米。如果球继续弹跳,两次弹跳后的距离将会 是10米+6米+6米+3.6米=25.6米。注意,每次后续的弹跳运动的距离,都是到地板的距离加上 这个距离的0.6倍,这个0.6倍就是球反弹回来的距离。编一个程序,让用户输入球的一个初始 高度以及允许球持续弹跳的次数。输出球的运动的总距离。 "...
# -*- coding:utf-8 -*- # author : Keekuun # 列表生成式,list l1 = [i for i in range(10)] # 或者 l2 = list(range(10)) print(l1, l2) # type(l) list # 打印:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] l3 = [x * x for x in range(1, 11) if x % 2 == 0] print(l3) l4 = [m + n for m in 'ABC' for n in 'XYZ'] print(l4) # 生成器,generator:惰性,可迭代 g = (i ...
#!/usr/bin/env python3 # # Reads the file 'guardian-puzzlewords-withsees.txt' and removes unwanted # material from it, combines clues when multiple clues for a word are # present, and writes the result to 'guardian-puzzlewords.txt'. # # Words can have one or more clues: # # ACCREDITATION # Granting of recognition (13...
from itertools import groupby import re pattern1 = r'([456]\d{3}(-?\d{4}){3}$|\d{16}' card_num = '5644-5567-7878-1121' #def repetition(card_num): # return max(len(list(g)) for _, g in groupby(card_num) if re.match( pattern1, card_num): print("hyphen and string length are correct") num = card_num.replace('...
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ n1 = 0 n2 = 0 d = [0 for _ in range(10)] for n in input_list: ...
# rand() function is from random module and random module is also in numpy. # This rand() function is used to create the array of elements near to zero. print() from numpy import random a=random.rand(5) print(a) print() ## 2-D array a1=random.rand(2,3) print(a1) print() ## 3-D array a2=random.rand(1,3,3) print(a2...
# This randint() function is from the random module. This random module is also in numpy. # randint() function create array of random numbers. print() from numpy import random a=random.randint(1,20,10) print(a) print() a1=random.randint(1,10,4) print(a1)
# Linspace function is used to create 1-D evenly spaced array. print() from numpy import linspace,ndim,size,shape a=linspace(1,100,num=10) print(a) print(a.ndim) print(a.size) print(a.shape) print() a1=linspace(1,100,num=20) print(a1) print(a1.ndim) print(a1.size) print(a1.shape) print() a2=linspace(100,200,num=8...
# Create categorical graphical analysis - The create_categorical_charts function isolates all the object data type variables in a given data # frame, and generates a bar plot on the count statistics by the target variable def create_categorical_charts(df, target_variable, vars_to_ignore): df = df.select_dtypes(in...
import coin # The definition of hypothesis F is "p is 0.5" # The following code computes L(E|F) evidence = 140, 110 Likelihood_fair = coin.Likelihood(evidence, 0.5) # If the definition of hypothesis B is "p is either 0.4 or 0.6 with # equal probability, find L(E|B). Likelihood_biased = coin.Likelihood(evidence, 0.4...
#1 scores=[80,75,55] total=0 for score in scores: total+=score average=total/3 print(average) #2 13%2 #3 pin="881120-1068234" yymmdd=pin[:6] num=pin[7:] print(yymmdd) num(pin) #4 pin="881120-1068234" print(pin[7]) #5 a="a:b:c:d" b=a.replace(":","#") print(b) #6 a=[1,3,5,4,2] a.sort() a.reverse() print(a) #7 ...
class InvalidCredentials(Exception): def __init__(self,msg="Invalid Credentials"): Exception.__init__(self,msg) try: names=[ { "name": "Venkat" "password": "849" }, { "name": "Rakesh" "password": "656" } ...
# Python 3 program for Bresenham’s Line Generation # Assumptions : # 1) Line is drawn from left to right. # 2) x1 < x2 and y1 < y2 # 3) Slope of the line is between 0 and 1. # We draw a line from lower left to upper # right. # function for line generation def bresenhamAbajoArriba(x1, y1, x2, y2): m_new = 2 * (y2 ...
import random class Game: def __init__(self, decks_count, reset_on_dealer_blackjack): self.deck = Deck(decks_count) self.reset_on_dealer_blackjack = reset_on_dealer_blackjack def start_round(self): self.deck.reset() game_round = Round(self.deck) return game_round ...
#!/usr/bin/env python3 """ Threads that waste CPU cycles """ import os import threading # a simple function that wastes CPU cycles forever def cpu_waster(): while True: pass # display information about this process print('\n Process ID: ', os.getpid()) print('Thread Count: ', threading.active_count()) f...
# first_name = input("What is your first name?") # last_name = input("What is your last name?") # print(last_name, first_name) # first_name = input('What is your first name?') # last_name = input('What is your last name?') # # # def reverse_order(first_name, last_name): # print("%s %s" % (last_name, first_name)) ...
# print("Hello World") # # # # # print() # Creates a blank line # # # # print("See if you can figure this out") # # # # print(10 % 3) # # # # # # # # Variables # # # # car_name = "Lamborguieapig" # # # # car_type = "Beast" # # # # car_cylinders = 8 # # # # car_mpg = 9000.1 # # # # # # # # # Inline Printing # # # # pri...
class Graphics(): size=0 m_list=[] def __init__(self): print("What SIZE of broad you want to choose :- \n") self.size=int(input("Example:- (For 3x3 , Enter 3)\n")) for i in range(self.size): print(" ---"*(self.size)) print("| "*(self.size+1)) if(i == self.size-1): print(" ---"*(self.si...
"""Dylan Valmadre""" def main(): min_length = 10 valid_pw = False get_password(min_length, valid_pw) def get_password(min_length, valid_pw): while not valid_pw: password = input(str("Enter password: ")) if len(password) < min_length: valid_pw = False print("Pa...
list1=[None]*5 i=0 while i<5: a=input("Enter the list items %d:"%i) list1[i]=a i+=1 print "List1 is ",list1