text
stringlengths
37
1.41M
um=input() if(um=='Saturday' or um=='Sunday'): print("yes") else: print("no")
# Inicializar un arreglo de 5 elementos en cero y mostrarlo ''' a = [0,0,0,0,0] for i in a: print("\t", a[i], end="") ''' # Operacion con arreglos # Cargar elementos ''' a = [] n = int(input("Ingrese la cantidad de elementos del vector: ")) for i in range(0,n,1): a.append(int(input("Ingrese el valor de cada el...
def get_third_place_order(group_dict: dict) -> list: """ Collect the 'order' in which the best four third placed teams in the group stage play their round of 16. The 'first' team faces the winner of Group B, the 'second' team the winner of Group F, the 'third' team the winner of group E, and the ...
from ParachuteModel import ParachuteModel class ParachuteController: def __init__(self): self.parachute_model = None def set_model(self, model: ParachuteModel): if model is None: raise Exception("Invalid model") self.parachute_model = model def fall(self): """...
""" Porgram ryzujący trójkąt prosokątny o zadanej długości boku """ dlugosc_przyprostokatnej = int(input('Podaj dłuygośc przyprostokątnej: ')) spacja = ' ' gwiazdka = '*' i = 0 while i < dlugosc_przyprostokatnej: if i == 0: print('*') elif i > 0 and i < dlugosc_przyprostokatnej-1: print(f'*{s...
""" Program obliczający średnią wartość z podanych przez Usera do przechowaniaaliczb uzyć listy max licba wprowadzeń to 10 skoerzystać z funkcji sum() """ wejscie= [] licznik=0 len_liczby =10 while licznik<10: #pobranie danyc do tabeli w pętli wejscie.append(input(f'Podaj liczbe nr {licznik+1}: ')) liczni...
# implementacja metody Basketumożliwiającą doadanie porduktu do koszyka class Product: def __init__(self, id, name, price): self.product_ID = id self.product_name = name self.product_price = price def print_info(self): return f'Produkt"{self.product_name}", id: {self.product_I...
tekst_wejsciowy = input('Podaj tekst do wypowiedzenia dla jąkały: ') iteracja = 0 iteracja_wewnatrz = 0 tekst_wyjscie = list(tekst_wejsciowy) for znak in tekst_wejsciowy: if (iteracja %2)!=0: #del tekst_wyjscie[iteracja] tekst_wyjscie.insert((iteracja+iteracja_wewnatrz), znak) iteracja_w...
''' Woda zamarza przy 32 stopniach Fahrenheita, a wrze przy 212 stopniach Fahrenheita. Napisz program "stopnie.py", który wyświetli tabelę przeliczeń stopni Celsjusza na stopnie Fahrenheita w zakresie od –20 do +40 stopni Celsjusza (co 5 stopni). Pamiętaj o wyświetlaniu znaku plus/minus przy temperaturze. [ºC]=([ºF...
# 9.12: .groupby(): custom 'summary' function using # .apply(). Group rows by 'SalesRep' and use .apply() with a # function that expects a DataFrame of grouped rows and # returns the sum of 'SaleAmount' from the DataFrame. (In # other words, this replicates what .groupby().sum() does). import pandas as pd def pri...
# 8.29: Use .set_index() to set the a column for the student # DataFrame as the index for the DataFrame. (This method # returns the new, modified DataFrame.) import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] ...
# 3.18: BeautifulSoup object: the below code reads a string # read from an html file and parses the file and its tags into # a BeautifulSoup object. # Explore the following attributes of the object named 'soup': # * print the type of the object # * print the object itself # * print the .text attribute # from...
# 5.19: Convert another function to lambda. # The below function by_last_float() takes a string argument # and returns a portion of that string (converted to float) as # return value. Replace this function with a lambda. revenue = '../revenue.csv' def by_last_float(line): words = line.split(',') return flo...
# 8.41: Use .isin() (with the Series as argument) in a filter # to show only those rows where the 'c' value is 'yourstr' or # 'mystr'. import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] }, in...
# 6.8: Create an __init__() method. # Add a method to the below class, __init__(self) that inside # the function announces and prints the argument self, i.e. # print(f'self: {self}'). # # Construct 2 new instances, and then print each instance. # Put a blank line between each instance. class Be: """ this cla...
# 3.29: Use str.encode() and bytes.decode() to convert a # string to a bytestring and back to string. # greet.encode() should include an encoding ('ascii', # 'latin-1' or 'utf-8'): greet = 'Hello, world!' bytestr = greet.encode(# add encoding here) print(bytestr) # subscript the bytestring to see individual charac...
# 8.24: Print the .index and .columns attributes on this # DataFrame import pandas as pd df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2.9, 3.5, 4.9], 'c': ['yourstr', 'mystr', 'theirstr'] }, index=['r1', 'r2', 'r3'])
# 1.4: Loop through a file, split out a column and append to # a list. Before the loop begins, initialize an empty list. # Perform the same operations as in previous, but add each id # value (the first field value in each line) to the list. fname = '../student_db.txt' fh = open(fname) headers = next(fh) ...
# 2.23: Result set: .fetchmany(). Use the cursor object to # .execute() a SELECT query for all columns in the revenue # table. Use .fetchmany(3) to retrieve just 3 rows, then use # .fetchmany(4) again to retrieve the remaining 4 rows. Close # the database connection when done. import sqlite3 db_filename = '../se...
# 4.52: Group for extraction. # Use a parenthetical grouping to extract the number from this # text. import re line = '34: this is a line of text' matchobj = re.search(r'', line) print(matchobj.group(1)) # Expected Output: # 34 # Note that if you see the message AttributeError: 'NoneType' # object has no attri...
# 3.30: Encode a latin-1 string to bytes and back to string, # then try to encode as ascii # The below string contains a non-ascii character. Encode # into the following encodings: 'latin-1', 'utf-8' and # 'ascii'. string = 'voilà' bytestr = string.encode(# add encoding here) print(bytestr)
# 5.12: Given your understanding that the key= argument to # sorted() will in a sense process each element through # whatever function we pass to it, sort these strings by their # length, and print the sorted list. mystrs = ['I', 'was', 'hanging', 'on', 'a', 'rock'] # your code here # Expected Output: # ['I', 'a'...
# 6.1: Define a class. # Use the class statement with name MyClass (or you may # substitute a name of your own choice). To fill the # otherwise empty block, use the pass statement. # # Initialize an instance of the class and print its type to # show that it is an instance of the class. # Expected Output: # <cla...
# 8.35: Use .loc[] indexing with a list to select the first 3 # rows (19270701, 19270702 and 19270706) of the DataFrame. # (Note that these have been read into the DataFrame as # integers.) Do this first by passing a list of the 3 index # values, then by passing a slice starting with 19270701 and # ending with 192707...
# 9.4: Convert a function to lambda. The following function # takes one argument and returns the value doubled. Convert # to lambda and use in the map() function. def doubleit(arg): return arg * 2 seq = [1, 2, 3, 4] seq2 = map(doubleit, seq) print(list(seq2)) # [2, 4, 6, 8]
import os, sys # coding=utf-8 fname = input('file name please:') with open(fname, 'r') as myfile: jomle=myfile.read().replace('\n', '') print ("number of ا:",jomle.count("ا")) print ("number of ب:",jomle.count("ب")) print ("number of پ:",jomle.count("پ")) print ("number of ت:",jomle.count("ت")) print ("number of ث:...
""" Binary Tree implementation starter """ import random from binarytree.node import Node from binarytree.binarytree import BinaryTree if __name__ == '__main__': ROOT = 5 print('\t...creating a binary tree...') binary_tree = BinaryTree(ROOT) print('The binary tree with root value', ROOT, 'is created....
class Solution: def divide(self, dividend, divisor): if dividend < -2**31 or dividend > 2**31-1 or divisor < -2**31 or divisor > 2**31-1: return 2**31-1 if dividend == 0: return 0 else: flag = dividend * divisor flag = 1 if flag > 0 else -1 ...
def merge(a,b): res=[] while a and b: if a[0]<b[0]: res.append(a[0]) a.pop(0) else: res.append(b[0]) b.pop(0) if a: res+=a else: res+=b return res def mergeSort(arr): if not arr or len(arr)==1: return arr ...
class Product(object): def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity def __iter__(self): return self def __next__(self): if self.num < self.n: cur, self.num = self.n, self.num + 1 ret...
#!/usr/bin/python import math recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } def recipe_batches(recipe, ingredients): if len(recipe.keys()) != len(ingredients.keys()): return 0 else: dict = {key: ingredients[key] / recipe[key] for k...
from enum import Enum class InstructionTypes(Enum): CALC = 1 READ = 2 WRITE = 3 class Instruction: def __init__(self, parent, instruction_type=InstructionTypes.CALC, mem_address=0b0000, mem_data=0x0000): self.instruction_type = instruction_type self.parent = parent self.mem_a...
import turtle import random win = turtle.Screen() win.title("make the geme") win.bgcolor("black") win.setup(width=800, height=600) win.tracer(0) scorevalue = 0 # making snake snake = turtle.Turtle() snake.shape("square") snake.color("white") snake.penup() snake.speed(0) #score score = turtle.Tu...
# if ~ else a = 10 if a>5: print('big') else: print('small') n = -2 if n > 0: print('양수') elif n<0: print('음수') else: print('0')
''' Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24h digital clock? The program should print two numbers: the number of hrs (between 0 and 23) and the number of minutes (between 0 and 59). ''' N= int(input('enter the minutes passed since m...
''' what is the result of 10**3 ''' a = 10 print( a**3 )
''' weight converter: Input the weight of the person in either in kg or pound(lbs). If the person provides his/her weight in kg then convert it into lbs else convert it to kg. ''' weight_1 = float(input('enter your weight in kg or lbs')) weight_2 = input('kg or lbs') pound = 2.2 if weight_2 == 'kg': convert = wei...
''' given x=5 what will be the value of x after we run x += 3 ''' x = 5 x += 3 print(x)
"""This module defines how notes are converted to frequencies. Currently only 12-tone equal temperament, but this would be the place to implement other tuning systems. Base frequency can be edited on-demand. """ import math # equal temperament RATIO = math.pow(2, 1 / 12) NATURALS = { "C": -9, "D": -7, ...
"""Data preparation of credit default data. Pre processing that can be carried out before splitting into training and test data: Ordered categorical columns are ordinal encoded. Unordered categorical columns are one hot encoded. In general, the categories need to cover the entire data set. In this data set th...
import sqlite3 import sys import random # Creating SQLite Connection conn = sqlite3.connect("card.s3db") cur = conn.cursor() # function to check validity def check_card(newcn): tfcs = "" tfs = 0 temp_cn = newcn[:-1] chsm = newcn[15] for i in range(len(temp_cn)): if i % 2 == 0: fc...
from selenium import webdriver driver = webdriver.Chrome(executable_path='C:\\Users\\Diego\\Downloads\\Programas a Instalar\\2021\\Drivers\\chromedriver_win32\\chromedriver.exe') driver.get("https://rahulshettyacademy.com/AutomationPractice/") driver.maximize_window() #Finding all the checkboxes, common attribute is ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 6 03:35:46 2021 @author: GuSs_90 """ import psycopg2 try: connection = psycopg2.connect( host = 'localhost', user = 'postgres', password = '123456', database = 'bd_cesar5' ) print("Conexion exito...
#! /usr/bin/env python import sys # def get_fibonacci_last_digit_naive(n): # if n <= 1: # return n # # previous = 0 # current = 1 # # for _ in range(n - 1): # previous, current = current, previous + current # print(previous, current) # # return current % 10 def get_fib...
tSize = int(input("Please enter the size of the tile as an integer: ")) tSpan = int(input("Please enter the length of the span as an integer: ")) tTiles = ((tSpan) //(tSize)) spanToUse = tSpan - tSize numPairs = spanToUse//(2*(tSize)) borderSize = (spanToUse%2*(tSize))/2 bTile = numPairs + 1 wTile = numPairs gSize = bo...
import string def getAvailableletters(lettersGuessed3): l = list(string.ascii_lowercase) availableletters = '' for indx2 in l: if indx2 not in lettersGuessed3: availableletters+=indx2 return availableletters
from difflib import SequenceMatcher from .models import Question, Answer """ Normalize text to be lowercase and free of dashes for comparison """ def cleaned(text): return text.lower().replace("-", " ") """ Check if the two strings contain the same words but in different orders """ def tokens_match(str1, str2): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from converter import Converter class Parser: def __init__(self, filename): self.file = open(filename, 'r') buffer = '' for line in self.file.readlines(): line = line.strip() if line == '': converter = Converter(buffer) self.dic...
# CS 212, hw1-2: Jokers Wild # # ----------------- # User Instructions # # Write a function best_wild_hand(hand) that takes as # input a 7-card hand and returns the best 5 card hand. # In this problem, it is possible for a hand to include # jokers. Jokers will be treated as 'wild cards' which # can take any rank or sui...
f1 = open('r1_list.txt', 'r') f2 = open('r2_list.txt', 'r') f1_line = f1.readline() f2_line = f2.readline() line_no = 1 while f1_line != '' or f2_line != '': f1_line = f1_line.rstrip() f2_line = f2_line.rstrip() if f1_line != f2_line: if f2_line == '' and f1_line != '': print(">+", "Line-%d" % line_no, f1_l...
# coding:utf-8 ''' 峰值元素是指其值大于左右相邻值的元素。 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 你可以假设 nums[-1] = nums[n] = -∞。 输入: nums = [1,2,3,1] 输出: 2 解释: 3 是峰值元素,你的函数应该返回其索引 2。 输入: nums = [1,2,1,3,5,6,4] 输出: 1 或 5 解释: 你的函数可以返回索引 1,其峰值元素为 2;   或者返回索引 5, 其峰值元素为 6。 思路: 二分查找 mid>mi...
# coding:utf-8 ''' 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] ''' class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if __name__ == '__main__': ...
#coding:utf-8 ''' 输入一个链表,反转链表后,输出新链表的表头。 思路: 需要中间遍历保存当前节点的next 防止链表的中断 临界条件: ''' class ListNode(object): def __init__(self,v): self.val=v self.next=None class Solution: def ReverseList(self,pHead): if not pHead: return pre=None next=None while...
# coding:utf-8 ''' 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。 思路1: 最简单暴力的是遍历一遍复杂读是O(n) 思路2: [3, 4, 5, 1,2] 利用二分查找 low high if low<mid 说明左边是是递增序列,最小值肯定在右边 left=mid if low>mid 说明最小值肯定是在左边,右边必然是递增的序列 如果high low 相邻,最小值肯定是high...
# coding:utf-8 ''' 给定两个数组,编写一个函数来计算它们的交集。 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 思路: 可以使用hashmap 首先扫描第一个数组,再扫描第二个数组,复杂度O(M+N) 空间复杂度O(min(M,N)) 或者是双指针法,首先对数组进行排序,O(nlogn+mlogm) - 对数组 nums1 和 nums2 排序。 - 初始化指针 i,j 和 k 为 0。 - 指针 i 指向 nums1,指针 j 指向 nums2: 如果 num...
#coding:utf-8 ''' 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 链表中的环: 可以使用快慢指针的方式进行 快指针每次走两步 慢指针每次走一步 如果直至相等,然后快指针再从头走,直至相遇,则就是 ''' class ListNode: def __init__(self,v): self.val=v self.left=None self.right=None class Solution: def EntryNodeOfLoop(self, pHead): if not pHead or not pH...
#coding:utf-8 ''' 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 思路: 两个排序的链表进行合并,跟链表的插入类似,只需要比较两个链表的大小,将小的优先插入, 而后将长链表拼接到新的链表的后边即可 ''' class ListNode: def __init__(self,v): self.val=v self.next=None class Solution: def Merge(self, pHead1, pHead2): if not pHead1 and not pHead2: ...
# coding:utf-8 ''' 请实现两个函数,分别用来序列化和反序列化二叉树 二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串, 从而使得内存中建立起来的二叉树可以持久保存。 序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串, 序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。 二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。 主要的关键点是是每次递归都有返回值 反序列化的时候的pop ''' class TreeNode(object): def __init__(self...
#coding:utf-8 ''' 堆(Heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵完全二叉树的数组对象 堆heap是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。堆总是满足下列性质: - 堆中某个节点的值总是不大于或不小于其父节点的值; - 堆总是一棵完全二叉树。 将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。常见的堆有二叉堆、斐波那契堆等。 堆是非线性数据结构,相当于一维数组,有两个直接后继。 堆的定义如下:n个元素的序列{k1,k2,ki,…,kn}当且仅当满足下关系时,称之为堆。 (ki <= k2i,ki <= k2i+1)或者(ki...
# coding:utf-8 ''' 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 如果当前字符流没有存在出现一次的字符,返回#字符。 思路: 用hashmap 保存字符的出现的次数, 用s保存是字符的顺序,然后查找顺序查找第一个出现一次的字符 ''' class Solution: # 返回对应char def __init__(self): self.s = [] self.hashmap = {} ...
# coding:utf-8 ''' 给出一个完全二叉树,求出该树的节点个数。 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外, 其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。 若最底层为第 h 层,则该层包含 1~ 2h 个节点。 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def countNodes(self, ...
from Puzzle import Puzzle from PuzzleSolver import PuzzleSolver import utils file = "data/board2.txt" p = Puzzle(utils.board_from_file(file)) logs = open("data/test.txt", "a") solver = PuzzleSolver(p) print(p) y = input("Solve puzzle? (y/n): ") if y == 'y' and p.is_solvable(): solution = solver.a_star() for s...
# na2degrees.py # matthew johnson 18 january 2017 ##################################################### """ We will define graphs as dictionaries where the keys are the nodes and the values are sets containing all neighbours. Here is an example digraph (we can define graphs in the same way --- just need to ensure sy...
import sqlite3 from sqlite3.dbapi2 import connect from werkzeug.security import check_password_hash, generate_password_hash import logging def encrypt_password(password): """ Function used to encrypt a user's password. :param password: string :return: type: string returns the encrypte...
#!/usr/bin/env python # coding: utf-8 # In[1]: def new_name(): numbers=[] names=[] nam1= input("enter name") num= int(input("enter number")) name=names.append(nam) number=numbers.append(num) return name # In[ ]: new_name() # In[ ]: def new_name(): numbers=[] names...
class Node: def __init__ (self, value): self.value = value self.next = None class SLL: def __init__ (self): self.head = None def addToFront(self, value): new_node = Node(value) new_node.next = self.head self.head = new_node return self def addToBack(self, value): if self.head == None: self.add...
#Programming Challenge #Elevators in a building #Number_of_elevators = 2 #Number_of_floors = 3 floors >= 1 and <= number_of_floors #I would first create each elevator as an object #elevator1 #properties #floor = #door = open or closed #status = occupied or unoccupied (this would represent elevator moving or not movi...
# 装饰器 def log(func): def wrapper(*args, **kwargs): print("log func {}".format(func.__name__)) print(type(args), args) print(type(kwargs), kwargs) return func(*args, **kwargs) return wrapper @log def print_func(*args, **kwargs): print("this is func") print_func(1, 2, 3, a=1, b=2, c=3) ''' log func print_...
with open("input.txt", encoding="utf-8") as file: valid_passwords = 0 for line in file: position = 0 positions, password = line.split(":") min, max_letter = positions.split("-") max, letter = max_letter.split(" ") password = password.strip() if password[int(min) ...
import heapq def main(): puzzleType = input("Welcome to Maaz Mohamedy's 8-puzzle solver.\nType '1' to use default puzzle," + " or '2' to enter your own puzzle. \n") if puzzleType == '1': puzzle = pickDefaultArrangement() if puzzleType == '2': puzzle = pickCustomArrangement() algo = input("\tEnter your ch...
list_a = [10, 20, 30] list_b = [10, 20, 30] if list_a is list_b: print('list_a is list_b') else: print('list_a is not list_b') print('list_a 는{}'.format(id(list_a))) print('list_b 는{}'.format(id(list_b))) num_a = {"a":1, "b":1} num_b = {"a":1, "b":1} if num_a is num_b: print('num_a is num_b') else: ...
#coding:utf-8 ''' try语句按照如下方式工作; 首先,执行try子句(在关键字try和关键字except之间的语句) 如果没有异常发生,忽略except子句,try子句执行后结束。 如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。 如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中。 ''' if __name__=="__main__": print("python异常") '...
# -*- coding:utf-8 -*- ''' 斐波那契数列,下一个数为前两个数之和 ''' if __name__ == "__main__": a, b = 0, 1 while(b<10): a, b = b, a+b #print(b) print(b, end=" ")
# -*- coding:utf-8 -*- ''' 元组Tuple:与列表list类似,但是无法修改其中的元素 ''' if __name__ == '__main__': print("元组测试") tuple1 = ('a', 1 , 1.2, ['b', 4],('c',5)) #访问具体元素 print(tuple1[3]) #访问第2个到第4个元素 print(tuple1[1:4]) #访问第2个到最后一个元素 print(tuple1[1:]) #访问第1个到倒数第二个元素 print(tuple1[:-1]) #访问...
class Solution: def is_palindrome(self, x): import math if x <= 0: return x == 0 log_answer = math.log10(x) total_digits = math.floor(log_answer) + 1 msd_mask = math.pow(10, total_digits - 1) for i in range(total_digits // 2): most_sig_digit...
print("we are going to look for greater or lower or equal number ") x = int(input("X: ")) y = int(input("Y: ")) if x < y: print("x is less than Y") elif x > y: print("X is greter than Y") else: print("X is equal to Y") print("Thank You For playing") print("this is to make life easy")
def readFile(input_name): return [l.strip() for l in open(input_name, "r").readlines()] def shouldChange(limit, seat, adj): if seat == "#" and adj.count("#") >= limit: return "L" if seat == "L" and not "#" in adj: return "#" return seat # Could be more than 2x faster. Was lazy to do it def part1(d): ...
def readFile(input_name): with open(input_name) as f: return [line.strip()[:-1].split(" (contains ") for line in f] def allergenList(d): alergen_list = [] for ingredients, allergens in d: ingredients, allergens = ingredients.split(" "), allergens.split(", ") for allergen in ...
import sqlite3 # create a new database if the database doesn't already exist with sqlite3.connect("new.db") as connection: c = connection.cursor() c.execute("INSERT INTO population VALUES('New York City', 'NY', 8400000)") c.execute("INSERT INTO population VALUES('San Francisco', 'CA', 800000)")
''' generates a bunch of random data calculates the largest learning rate to use then tries to fit the following line to that data y=w1*x + w2 to it lots of cheesy plotting ''' import random import constants import utils import numpy as np import matplotlib.pyplot as plt def gettotalerror_vectorize(w,x,y): ''' ...
""" The evaluation module contains all classes used to evaluate expressions. """ from printing import Printer from expressions import Function, Sequence, Symbol, Bindings class Kernel: """ This class is provides the context for the evaluation of expressions. It manages the rule set, substitution environme...
# -*- coding: utf-8 -*- #-the in keyword can also be used to checl #to see if one string is 'in' another string #-the in expression is a logical expression and returns #true or false and can be used in an if statement fruit = 'banana' 'n' in fruit 'm' in fruit 'nan' in fruit if 'a' in fruit : print 'found it!'
largest_so_far = -1 print 'before:', largest_so_far for the_num in [9, 41, 12, 3, 74, 15]: if the_num > largest_so_far : largest_so_far = the_num print 'new largest | numbers:' print largest_so_far, '|', the_num print 'so, the largest number is:', largest_so_far # -*- coding: utf-8 -*- #We make a ...
# -*- coding: utf-8 -*- def test(a, b, c, d): a += 1 b = 'Alice' c.append(2) d['age'] = 16 q = 5 w = 'hello' e = [] r = {} test(q, w, e, r) print(q) print(w) print(e) print(r) s = r s['age'] = 17 print(s) print(r) d = w d = 'Alice' print(w) print(d) h = q h = 6 pr...
# -*- coding: utf-8 -*- #An average just combines the counting and sum patterns #and divides when the loop is done #把之前的算几个loop,和loop值的sum,加在一个程序,计算average #average = sum(总值) 除于 count(数量) # # # count = 0 sum = 0 print 'before', count, sum for value in [9,41, 12, 3, 74, 15]: count = count + 1 sum = sum + value ...
from drawman import * from time import sleep def f(x): return x*x print(drawman_scale) drawman_scale(100) x = -5.0 to_point(x, f(x)) pen_down() while x <= 5: to_point(x, f(x)) x += 0.1 pen_up() sleep(7)
#!/usr/bin/python3.8 # 1: Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором списке. my_list_1 = [2, 5, 8, 2, 12, 12, 4] my_list_2 = [2, 7, 12, 3] temp_list = [] for num_list1 in my_list_1: if num_list1 not in my_list_2: temp_list.append(num_list1) print(temp_l...
def ex1(): string1= raw_input("Digite uma palavra: ") tam = len(string1) print "A palavra dada tem tamanho:",tam
import numpy def pythagoreanTheorem(length_a, length_b): length_c = numpy.sqrt(numpy.square(length_a) + numpy.square(length_b)) print(length_c) def list_mangler(list_in): list_out = list() for x in list_in: if x%2==0 : list_out.append(x*2) else : list_out.append(x*3) print(list_out) def grade_calc(grad...
# -*- coding: utf-8 -*- """ Created on Tue Dec 6 18:20:07 2016 @author: Egor """ class Tree: def __init__(self): self.nodes = list() # negative result self.nodes.append(dict({0: None, 1: None, 2: None})) # positive result self.nodes.append(dict({0: None, 1: None, 2: None}...
#You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. # Use the file name mbox-short.txt as the file name def openfile(): fname = raw_input("Enter file name: ") try: fh = open(fname, 'r') except: ...
import numpy as np import pandas as pd numbers = [1, 2, 3, 4, 5] #mean print np.mean(numbers) #median print np.median(numbers) #standard devation print np.std(numbers) #Series: one dimensional object like a list or column in database, 0 to n-1 indices series = pd.Series(['Shamikh', 'Hossain', 'Duke', 19, 223], ind...
from collections import Counter #Opening a file in read mode fp=open("sample.txt","r") count=0 #Split each line into words and store it in w #Counting the number of words which is the length of w and adding it to a variable for j in fp: w=j.split() print(w) print(len(w)) count=count+len(w) pr...
str1="This is Python " str2="75 challenge" #Printing the variables by combining them. + operator is used to combine print(str1+str2) #Output #This is Python 75 challenge
from collections import deque class Graph: """ Graph Class Represents a directed or undirected graph. """ def __init__(self, is_directed=True): """ Initialize a graph object with an empty vertex dictionary. Parameters: is_directed (boolean): Whether the graph is directe...
from random import randint magic=randint(0,9) input ('') print (randint(0,9)) if magic==1: print ("You will be okay") if magic==2: print ("Soon you will find out but not today") if magic==3: print ("Yes") if magic==4: print ("No") if magic==5: print ("You are wise and will give the advice") if magic...
# 204101 sec 002 # Lab Homework 02 ข้อ 2 # Anurak Boonyaritpanit # 560510680 # ฟังก์ชั่นสำหรับแปลงค่าอุณภูมิจากองศา เซลเซียส -> ฟาเรนไฮต์ def convertTempCelsiusToFahrenheit( celsius ): fahrenheit = float((celsius * 9/5) + 32) return fahrenheit # ฟังก์ชั่นหลัก ทำงานที่นี่เป็นที่แรก def main(): ...
# 204101 sec 002 # Lab Homework 7 assignment 2 # Anurak Boonyaritpanit # 560510680 # In this case to show use "for" loop ============================================================================================================================ # uncomment code below to show # DEFINE initial value mySum = ...
# 204101 sec 002 # Lab Homework 6 ข้อ 2 # Anurak Boonyaritpanit # 560510680 num = int(input("num = ")) factorial = 1 if( num == 0): factorial = 0 else: for n in range(1,num+1): factorial = factorial*n print("{}!={}".format(num,factorial))
class NPC: def __init__(self, name, items, money, phrase): self.name = name self.items = items self.money = money self.phrase = phrase def talk(self): print(self.phrase) def sell(self, char): c = 1 for i in self.items: print(str(c) + "....