text
stringlengths
37
1.41M
# Rolando Josue Quijije Banchon # Software # #Tercer semestre #Tarea 5 de ejercicios de pagina web """EJEMPLO 5: Dado como dato la calificación de un alumno en un examen, escriba “aprobado” si su calificación es mayor o igual que 7 y “Reprobado” en caso contrario.""" class Tarea5: def __init__(self): ...
class Disciplin: def __init__(self, id, name, first_name, second_name, exam, coursework, count_lec, count_pr,count_lab = 0): self.id = id #код self.name = name #название self.first_name = first_name #имя преподователя self.second_name = second_nam...
# you can use print for debugging purposes, e.g. # print "this is a debug message" def solution(A): # write your code in Python 2.7 lower_value = min(A) size = len(A) centinel = lower_value for i in xrange(size): if ( centinel not in A ) : return centinel else : centinel...
#!/usr/bin/env python import sys import csv cookies = sys.argv[1] targetDate = sys.argv[3] dictionary = {} with open(cookies) as csvfile: content = csv.reader(csvfile) highestRepetition = 0 answer = [] # loop through each row in the csv file for row in content: cookie = row[0] ...
import numpy as np import csv import xlsxwriter import os # Use these to test the function before using a for loop (optional) or use the files provided for practice name = 'cerda' source1 = f"/Users/{name}/Desktop/ColdFingerData/06262020list.csv" # the file we are editing newFileName1 = f"/Users/{name}/Desktop/ColdFin...
""" This module implements the REL (REL) class, used for relational links between tables/objects A schema definition of thing=REL causes an INT(11) to be added to the database, to store the uid of the related class Thing On construction of an instance of REL, the link is stored as in integer. It is converted to the ob...
#!/usr/bin/python2.7 # Map1.py import sys import itertools def main(numberOfArms, stepSize): rangeMin = 0.0 rangeMax = 1.0 generateBandits(rangeMin, rangeMax, stepSize, numberOfArms) def arange(rangeMin, rangeMax, stepSize): probRange = [] currProb = rangeMin while (currProb <= rangeMax): probRange.append(...
#!/usr/bin/python """ Usages: ./test3.py (reads out the entire config file) ./test3.py thiskey thisvalue (sets thiskey and thisvalue in the config file) """ import sys from assignments3 import ConfigDict cd = ConfigDict('config_file.txt') if len(sys.argv) == 3: key = sys....
import os import argparse arguments = [] parser = argparse.ArgumentParser() # parser.add_argument("echo", help="This will print the first variable") parser.add_argument("x", type=int, help="base") parser.add_argument("y", type=int, help="the exponent") parser.add_argument("-v","--verbose", help="Adding the verbosity",...
people=30 cars=40 trucks=15 if cars>people: print("We should take the cars") elif cars<people: print("We should not take the cars") else: print("We can't decide") if trucks>cars: print("That's too many trucks") elif trucks<cars: print("Maybe we could take the trucks") else: print("We still can't...
from sys import argv print("How old are you?",end='') age=input() print("How tall are you?",end='') height=input() print("How much do you weight?",end='') weight=input() print(f"So,you're {age} old,{height} tall and {weight} heavy") script ,filename=argv txt=open(filename) print("Here's your life {filename}:") print(tx...
def isPrimeNumber(numToCheck): result = False res = [] remainders = [] if(numToCheck == 1): numToCheck = numToCheck + 1 result = True res.append(result) res.append(numToCheck) return res initialDisvisor =2 for j in range(initialDisvisor,numToCheck): ...
#! /usr/bin/env python import re import sys from datetime import datetime from typing import List, Optional from boggle import BoggleGrid, FileBasedDictionary def main(letter_grid: List[List[str]]): dictionary = FileBasedDictionary(file_path="american-english-large.txt") boggle_grid = BoggleGrid( let...
#Section 1: Terminology # 1) What is a recursive function? correct # A recursive function is a function that does one thing or another depending on the input # # # 2) What happens if there is no base case defined in a recursive function? correct # If there is no base case defined in a recursive function, the function ...
#Importing the required models and libraries. #To run this file one should have Xgboost,scikitlearn and the corresponding libraries installed. import pandas #Data analysis tools for the Python. import matplotlib.pyplot as plt #Plotting tools for Python. ...
# The server program is designed to be run on the base station (can be a laptop) # It will wait and receive messages coming from the rover's Raspberry Pi # Written with Python 3.9.0 import socket # IP and port of the server # TODO: instead of hard-coding let user select host = "0.0.0.0" port = 62522 # T...
import networkx as nx class Vertex: #contructor for Vertex def __init__(self, int_val, left = None, right = None): self.int_val = int_val self.left = left self.right = right def add_node(val, node, g): #check if value is less than nodes value if(val < node.int_val): #go t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pygame #import time import turtle pygame.init() #taille_police = 12 #taille_police2 = 17 #taille_police3 = 15 #POLICE = ('Arial', taille_police, 'normal') #POLICE2 = ('Arial', taille_police2, 'normal') #POLICE3 = ('Arial', taille_police3, 'normal') police1 =...
import abc class Cipher(abc.ABC): @abc.abstractmethod def decrypt(self, index, data): pass class CeasarShift(Cipher): def decrypt(self, index, data): key = index + 1 message = data.upper() alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" for letter in mes...
class StandardIWH: def __init__(self, w: float) -> None: """Standard Inertia Weight Handler. Parameters ---------- w : float Inertia weight. """ self.w = w def __call__(self, iteration: int) -> float: """Returns the inertia weight unchang...
# File with sample functions. def sum(x, y): # sums up two numbers """ Adds two numbers.Returns the sum.""" return x + y # Returns the product. def mul(x, y): # z is a local variable z = x * y return z
message = "this is a statement in english" # a starting consonant sound in your word moves to the end of the word followed by "ay" # This -> isthay # If the word starts with a wovel, then we add "way" to the end # other -> otherway translation = {} translation["this"] = "isthay" translation["statement"] = "atementstay...
def copied_word(): word = input("What's your favourite word? ") print(word * 12) print('"', word, '"' + " doens't sound like anymore.") copied_word()
phrase = input("Enter a word or phrase:").lower() data = '_'.join(phrase) + '_' wrong = 0 while '_' in data and wrong < 6: print('The thing to guess', data[1::2]) letter = input('What the letter ?').lower() while len(letter) != 1: letter = input('What letter ?') odata = data data.replace(le...
votes = {"chipotle": 0, "rev_soup": 0, "mellow": 0, "lemongrass": 0, "other": 0 } def vote(restaurant, votes): """tabulates one vote for a lunc h place""" strategy = """Add restaurants to the votes dict and add one to the values associated with th...
plan = """ dict of results -- election keys: candidate values: number of votes vote(candidate, election) get votes for this candidate add 1 set votes for this candidate ballot = [ "Luther Tychonievich", "Jame Cohoon", ] won(election) """ names = {"luther": "tychoniev...
# cost = int(input("How much is it ?")) # if cost > 10: # cost -= 5 # print("I'll give you", cost, "for it.") # # if cost > 500: # print("I will be paying with a check.") # else: # if cost > 20: # print("I will be paying with cash.") # else: # if cost <= 200: # print("I will...
racial_words=["nigga","black","white","damn","hispanics","dark skinned" ,"chinks","white skinned","pakis","slave","slut","nigger"] # Set words that indicate racial slur in list # file=open("Tweet_text_file.txt","r") ...
#################################################### # Python by example # Problem 003, 004, 005, 006, 007, 008 # Author: Omar Rahman # Date: 12//2019 #################################################### print("-----------------------------------") print(" Problem 3 ") print("---------...
#---------------------------------------------- # Problem 063 # Author: Omar Rahman # Date: 1/1/2019 #---------------------------------------------- #-------------- # Sqaures with gaps #-------------- import turtle turtle.shape("turtle") Screen = turtle.Screen() Screen.bgcolor("green") turtle.pens...
import math def sumMultiples(factors, n): #Question 001 total = 0 for x in range(1, n): for f in factors: if x%f==0: total += x break return total def sumEvenTerms(list): #Question 002 sum = 0 for x in list: if x%2==0: sum+=x return s...
n = int(input("Enter number of step(s)\n")) list1 = [["" for y in range(n)] for x in range(n)] print(list1) def steps(n, y = 0, stair = ""): if (y == n): return; if (n == len(stair)): print(stair) return steps(n, y+1) if (len(stair) <= y): stair += "...
# Some resources inspiring this demo: # - https://www.learndatasci.com/tutorials/python-finance-part-yahoo-finance-api-pandas-matplotlib/ # - https://www.codingfinance.com/post/2018-04-05-portfolio-returns-py/ from pandas_datareader import data import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt im...
class Stack: def __init__(self): self.items = [] def push(self, val): self.items.append(val) def pop(self): try: return self.items.pop() except IndexError: print("Stack is empty") # Postfix 계산 # 1. 허용연산자 = 이항연산자(+,-,*,/,^) # 2. 문자열의 연속된 두 항 사이에는 모두 공백 하나 ' '가 있음) def compute_postfi...
from datetime import datetime, date from dataclasses import dataclass @dataclass class User: name: str surname: str address: str date_of_birth: str # format is YYYY/MM/DD def age(self, at_date: str = None) -> int: dob = datetime.strptime(self.date_of_birth, "%Y/%m/%d") today = da...
#dfine validation function def isValid(): #validate the date monthValid = False dayValid = False sizeValid = False yearValid = False #set all validation to false to begin with and have user enter input while (monthValid == False) or (dayValid == False) or (sizeValid == False) or (...
import bankaccount def main(): #get the starting balance. start_bal = float(input('enter your starting balance: ')) #create a bankaccount object savings = bankaccount.BankAccount(start_bal) #deposit the user's payheck pay = float(input("How muh were you paid this week? ")) print("I will d...
import student2 student_list = [ student2.Student('Julie', 4.0, 23409, 'A', 'Ft'), student2.Student('Joe', 4.0, 45678, 'A', 'Ft'), student2.Student('Susie', 3.0, 52980, 'B', 'Pt'), student2.Student('Sarah', 2.0, 45893, 'C', 'Ft'), student2.Student('Sam', 1.0, 32409, 'F', 'Pt') ] def displayMenu()...
carManufacturers = {'Ford': 5, 'Chevy': 10, 'Honda': 4, 'Maserati': 2} carManufacturerNames = [] carManufacturerNames = list(carManufacturers.keys()) print"Car manufacturer:",carManufacturerNames[0],carManufacturers[carManufacturerNames[0]] print("Car manufacturer:",carManufacturerNames[1],carManufacturers[carManufactu...
#define total Grades for the for statement totalGrades = 12 #define main function def main(): #open a file called grades.txt for writing to grade_file = open('grades.txt', 'w') #for statement to get name and average. for choice in range(totalGrades): name = input("Please enter the student's ...
def validVoter(): name = input("What is your name?") age = int(input("How old are you %s?" % name)) if age >= 18: return True elif age > 100: return ("You are not an elf") elif age < 0: return ("You cant be a negative age") else: return False def display(): i...
import re fileName='3.txt' f=open(fileName,'r') pattern='[^A-Z][A-Z][A-Z][A-Z][a-z][A-Z][A-Z][A-Z][^A-Z]' s="" for line in f: m = re.search(pattern,line) if m: print(m.group().__getitem__(4)) s=s+m.group().__getitem__(4) print(s) # next level http://www.pythonchallenge.com/pc/def/linkedlist...
#Exercício 8 #Implemente um algoritmo que leia um número inteiro, em seguida calcule o fatorial deste número e apresente para o usuários. #Ex: n = 4 #O Fatorial de 4 é 24 n = int(input("Digite um número: ")) x = 1 for i in range(n,0,-1): x = x * i print(x)
#Exercício 9 #Escreva um programa que imprima os n primeiros número primos. Peça para o usuário informar o valor de n. n = int(input("Digite um número: ")) for i in range(1,n+1,1): primo = True for j in range(2,i): if i % j == 0 : primo = False if primo : print(i)
#!/usr/bin/python import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) host=input('Enter the ip address:') port=input('Enter the port number:') port=int(port) print('Server is initiated\nWait for Client to response') s.bind((host,port)) s.listen(5) c,addr=s.accept() print('Welcome to the Messengin...
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def BST_insert(root,node): if node.val == root.val: return root if node.val < root.val: if root.left: BST_insert(root.left,node) else: root...
# 设计哈希集合 # 不使用任何内建的哈希表库设计一个哈希集合 # # 具体地说,你的设计应该包含以下的功能 # # add(value):向哈希集合中插入一个值。 # contains(value) :返回哈希集合中是否存在这个值。 # remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。 # # 示例: # # MyHashSet hashSet = new MyHashSet(); # hashSet.add(1); # hashSet.add(2); # hashSet.contains(1); // 返回 true # hashSet.contains(3); // ...
# 计数质数 # 统计所有小于非负整数 n 的质数的数量。 # # 示例: # # 输入: 10 # 输出: 4 # 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 # 一个思路是,逢2、3、5的倍数就跳过去,从根本上减少需要循环检测的数据 # if (i > 2 and i % 2 == 0) or (i > 3 and i % 3 == 0) or (i > 5 and i % 5 == 0) or (i > 7 and i % 7 == 0): # 还是蠢,还是慢! import math class Solution: def countPrimes_overtime(self,...
# 至少是其他数字两倍的最大数 # 在一个给定的数组nums中,总是存在一个最大元素 。 # # 查找数组中的最大元素是否至少是数组中每个其他数字的两倍。 # # 如果是,则返回最大元素的索引,否则返回 - 1。 # # 示例 # 1: # # 输入: nums = [3, 6, 1, 0] # 输出: 1 # 解释: 6 # 是最大的整数, 对于数组中的其他整数, # 6 # 大于数组中其他元素的两倍。6 # 的索引是1, 所以我们返回1. # # 示例 # 2: # # 输入: nums = [1, 2, 3, 4] # 输出: -1 # 解释: 4 # 没有超过3的两倍大, 所以我们返回 - 1. # # 提示: # # nu...
# 数组拆分 I # 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。 # # 示例 1: # # 输入: [1,4,3,2] # # 输出: 4 # 解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4). # 提示: # # n 是正整数,范围在 [1, 10000]. # 数组中的元素范围在 [-10000, 10000]. # 思路:其实就是排序,按顺序拿。只有按顺序拿,才能保证被min操作牺牲掉的数值更少 class Solution: ...
# 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。 # # 例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和 [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。 # # 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。 # # 感觉就是简单遍历,这里注意一点就行吧,就是每次失败了,重...
class Solution: def merge_sort_two(self,nums1,nums2): result = [] i = 0 j = 0 while i < len(nums1) and j < len(nums2): if nums1[i] <= nums2[j]: result.append(nums1[i]) i += 1 else: result.append(nums2[j]) ...
class Solution: # def merge(self, nums1, m, nums2, n): # """ # :type nums1: List[int] # :type m: int # :type nums2: List[int] # :type n: int # :rtype: void Do not return anything, modify nums1 in-place instead. # """ # j = 0 # i = 0 # ...
# 搜索旋转排序数组 # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # 你可以假设数组中不存在重复的元素。 # 你的算法时间复杂度必须是 O(log n) 级别。 # 思路,循环数组,mid的计算特殊处理。但是也不是绝对的O(logn),最起码找到起始点还需要n的吧? class Solution: # def search(self, nums, target): # """ # :typ...
# x 的平方根 # 实现 int sqrt(int x) 函数。 # 计算并返回 x 的平方根,其中 x 是非负整数。 # 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 # 示例 1: # 输入: 4 # 输出: 2 # 示例 2: # 输入: 8 # 输出: 2 # 说明: 8 的平方根是 2.82842..., # 由于返回类型是整数,小数部分将被舍去。 # 优化:超过4以后,应该right直接用x // 2就够吧。,废话,超过9还能用x//3呢.所以说,可以动态的用x的平方根?但是你找的就是平方根,找到了就不用搜了!! # 利用平方计算?mid ** 2,大于x算结束?保留之前的不大于x的mi...
#adding two numbers in three lines a = int(input()) b = int(input()) print(a+b)
# 寻找旋转排序数组中的最小值 # 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 请找出其中最小的元素。 # # 你可以假设数组中不存在重复元素。 # # 示例 1: # # 输入: [3,4,5,1,2] # 输出: 1 # 示例 2: # # 输入: [4,5,6,7,0,1,2] # 输出: 0 # 被专题的模板坑了,其实可能并不适用? class Solution: def findMin_myself(self, nums): """ :type nums: L...
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 注意:给定 n 是一个正整数。 # # 示例 1: # # 输入: 2 # 输出: 2 # 解释: 有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # 示例 2: # # 输入: 3 # 输出: 3 # 解释: 有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 class Solution: def climbStairs_myself(self, n): ...
# 实现strStr() # 实现 strStr() 函数。 # # 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。 # # 示例 1: # # 输入: haystack = "hello", needle = "ll" # 输出: 2 # 示例 2: # # 输入: haystack = "aaaaa", needle = "bba" # 输出: -1 # 说明: # # 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 # # 对于本题而言,当 needle ...
# 反转字符串中的单词 III # 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 # # 示例 1: # # 输入: "Let's take LeetCode contest" # 输出: "s'teL ekat edoCteeL tsetnoc" # 注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 class Solution: def reverseWords_myself(self, s):#use api strs = s.split(' ') res = '' print(strs) ...
from datetime import datetime day_now = datetime.now() print('Today is {} / {} / {}'.format(day_now.day,day_now.month,day_now.year)) def ask(): x = str(input('Enter your name \n Name : ')) if x.isdigit(): print('Only letters are accepted.') else: pass try: y = int(inp...
## WE ARE MAKING AN ITERATOR / COUNTER board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] def display(): for row_no,row in enumerate(board): print(row_no,' ',*row) for i in range(len(board)**2): no_of_players = 2 if i%2==0: print('its X turn') row = int(input('what row you w...
# import modules from tkinter import * from englisttohindi.englisttohindi import EngtoHindi # user define funtion def eng_to_hindi(): trans = EngtoHindi(str(e.get())) res = trans.convert result.set(res) # object of tkinter # and background set for grey master = Tk() master.configure(bg = 'li...
import sqlite3 class CoffeeShop: def __init__(self): pass class Item: def __init__(self, row): self.ID = row[0] self.ItemName = row[1] self.ItemPrice = row[2] self.QtyRemaining = row[3] def __repr__(self): return str(self.ID...
memo = [] # Dynamic Programming Top-down. class Solution1: def canJump(self, nums): for i in range(len(nums)): memo.append("UNKNOWN") memo[len(nums)-1] = True return self.canJumpFromPosition(0, nums) def canJumpFromPosition(self, position, nums): if memo[position]...
##Emily Dennis 13/04/19 ###program displays the correct Saffir-Simpson Hurricane Wind ###Scale category for a wind speed entered by the user and the selected unit. #imports items from tkinter from tkinter import Frame, OptionMenu, StringVar, Tk, Entry, Button, LEFT, Label #creates hurricane class class Hurricane(...
def matrixMultiply(arr1, arr2): global n newArr=[[0]*n for _ in range(n)] for i in range(n): for j in range(n): sum=0 for k in range(n): sum += arr1[i][k]*arr2[k][j] newArr[i][j] = sum%1000 return newArr def matrix(degree): global arr ...
import copy def path(p, q, r): # p, 5, 3 if (p[q-1][r-1] != 0): path(p, q, p[q-1][r-1]) print(f"v{p[q-1][r-1]}", end=" ") path(p, p[q-1][r-1], r) def allShortestPath(g, n): # d는 최단거리의 길이가 포함된 배열(결과) # d = copy.deepcopy(g) p=[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0...
#Artificial Neural Network # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data #...
class Queue: def __init__(self): self.first = None # beginning of queue self.last = None # end of queue self.n = 0 # Number of elements in the queue def enqueue(self, item): oldLast = self.last self.last = self.Node() self.last.data = item ...
#list range will start on zero and continue until hit 11 newList = list(range(0,11)) print(newList) #the same but will be stepping by two elements list(range(0,11,2)) for i,letter in enumerate('abcde'): print("At index {} the letter is {}".format(i,letter)) mylist1 = [1,2,3,4,5] mylist2 = ['a','b','c','d','e'...
def ask(): while True: try: x = int(input("Enter a number: ")) except ValueError: print("Wrong input") continue else: break print(x**2) try: for i in ['a','b','c']: print(i**2) except TypeError: print("There was a type ...
class Animal(): def __init__(self,name) -> None: self.name = name def speak(self): raise NotImplementedError("Subclass must implement this abstract method") class Dog(Animal): def speak(self): return self.name + " says woof!" class Cat(Animal): def speak(self): ...
def exp(m, n): return m ** n def divides(m, n): print("\ndivides: ", end= " ") for i in range(1,m+1): if i % n == 0: print(i, end= " ") def is_in_string(string, c): return c in string def how_many(string, c): total = 0 for oneChar in string: if c == oneChar: ...
from random import randint def startGame(): rndNumber = randint(1,100) numberOfTries = 0 lastNumber = 0 print(rndNumber) while True: guessedNumber = int(input("Enter a number ")) numberOfTries +=1 print(validateGuess(guessedNumber, numberOfTries, rndNumber, lastNumber)) ...
def word_matching(text, keywords): # keywords = convert_keywords(keywords) # text = convert_text(text) text = text.lower() matching_count = 0 for i in range(len(keywords)): start_matching_index = 0 matching_keyword = keywords[i].lower() while(True): start...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' __author__ = 'xutengfei' __author_email__ = 'xutengfei1@genomics.cn Fuc: Compute the character with the highest frequency in the string. ''' import sys def max_word(in_file,out_file): with open(in_file,'r') as IN1, open(out_file,'w') as OUT: ...
import re a = 'c|C++|Java|C#|Python|Javascript' r = re.findall('Python', a) if len(r) > 0: print('Python is there') else: print('no Python')
a=1 b=2 c=3 a,b,c=1,2,3 #上面的代码和下面的相同 d=1,2,3 print(type(d)) a,b,c =d #序列解包 # a,b=d #不能用两个变量来解包3个变量的tuple # a,b=[1,3,4] print(d)
# 字典不能有重复的key #字典的key 是不可变的. d={'Q':'are you ok?','G':'i am fully agree'} print(d['G'])
# 4Gewinnt Kristoferz # Variables col = 7 row = 6 empty_chip = '.' human_chip = 'X' pc_chip = 'O' moves = 0 playerstart = input ("Who shall start? Please write Pc (1) or Human (2): ") while str.lower(playerstart) != "pc" and str.lower(playerstart) != "human" and playerstart != str(1) and playerstart != str(2...
#Product of array elements #Return the product of array elements under a given modulo. #That is, return (Array[0]*Array[1]*Array[2]...*Array[n])%modulo def product(arr,n,mod): # your code here pro=1 for j in range(0,n): pro=pro*arr[j] if pro>=mod: pro=pro%mod return pro { #...
import sys from math import sqrt def DistCalc(x1,x2,y1,y2): dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 ) print int(dist) test_cases = open(sys.argv[1], 'r') for test in test_cases: coordinates=[] for i in test.strip().split(" "): coordinates.append(i) x1=coordinates[0].replace("(", "") x1...
import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: coin1=1 coin3=3 coin5=5 minimum=0 test=int(test.strip()) if test>=coin5: while(test>=coin5): test-=coin5 minimum+=1 if test>=coin3: while(test>=coin3): test-=coin3 ...
import re import collections text = open('file_I.O/book.txt').read().lower() words = re.findall('\w+', text) print(collections.Counter(words).most_common(10))
#!/bin/python import math import os import random import re import sys # Complete the funnyString function below. def funnyString(s): rs=s[::-1] n=len(s) for i in range(1,n): d1=abs(ord(s[i])-ord(s[i-1])) d2=abs(ord(rs[i])-ord(rs[i-1])) if d1!=d2: return("Not Funny") ...
import json import arcade class Score: def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT): self.width = SCREEN_WIDTH self.height = SCREEN_HEIGHT self.path = "./score.json" self.score_dict = {} self.index = -1 self.char_count = 0 self.restart_timer = -1 def...
import os, tensorflow as tf # use the range operation to generate vectors of sequential values x = tf.range(start=0,limit=10,delta=1,dtype=tf.int32,name='range') with tf.Session() as sess: # init log files for tensorboard sfw = tf.summary.FileWriter(os.getcwd(),sess.graph) # dump the graph definition as...
import unittest import leetcode_solutions as ls class test_moviesOnFlight(unittest.TestCase): print("Test moviesOnFlight") def test_one(self): movieDurations = [10,20, 50,30, 90,100] #[60,75,85,90,120,125,150] d = 150 pair = ls.moviesOnFlight(movieDurations, d) self.assertEqu...
#!/usr/bin/env python3.6 # Decoradores @classmethod e @classmethod # TIPOS DE MÉTODOS EM PYTHON: # Métodos de instância: Recebem o objeto(self) como argumento # Métodos de classe: Recebem a classe(cls) como argumento # Métodos estaticos: Não recebem nada como argumento. # Digamos que temos a seguinte classe: class S...
#!/usr/bin/env python3.6 # Para criar nossos proprios erros, precisamos herdar de alguma classe de Erro, por exemplo TypeError # pode ser qualquer uma... class MyError(TypeError): """ Documentação da Classe """ # message é um atributo da superclase e code é um atributo que criamos para a classe MyError...
def count_from_zero_to_n(n): if n <= 0: raise ValueError('Valor invalido. A entrada deve ser um numero inteiro.') for x in range(0, n+1): print(x) count_from_zero_to_n(-1)
#!/usr/bin/env python3.6 class Car: def __init__(self, make, model): self.make = make self.model = model def __repr__(self): return f'<Car{self.make} {self.model}' class Garage: def __init__(self): self.cars = list() def __len__(self): return len(self.cars) ...
#!/usr/bin/env python3 # Create Stored movies with object-oriented programming: class Movie: """ Classe Filmes Tem os atributos: titulo, diretor e ano de lançamento. """ def __init__(self, new_title, new_director, new_year=1994): self.title = new_title self....
is_programmer = False # It's a infinite loop while not(is_programmer): # It means that: is_programmer == True print('Leraning Programming') learning_programming = input('Are you alredy a programmer? ').lower() is_programmer = learning_programming == 'yes' # is_programmer receives the boolean value of foll...
import typing def repeated_function(aString: str, n: int) -> str: if n == 1: return aString else: return aString + repeated_function(aString, n-1) print(repeated_function("Nome", 3))
option = 'p' while option not in 'quit': option = input('Type an option[p/q]? ').lower()[0] if option == 'p': print('Hello')
# Return a double of a list lista = list(range(10)) #============================= lista_dobro = list() print(lista_dobro) # It must show a void list for num in lista: lista_dobro.append(num*2) print(lista_dobro) #============================= # LIST COMPREHENSION WITH LIST print([num*2 for num in lista]) # We ...
print ("Moi, mikä sun nimi on?") nimi = input() print ("Moi," + nimi) if nimi == "k": print("Outo nimi mut, ok.") else: print("Hauska nimi!")
import os import csv dirname = os.path.dirname(__file__) csvpath = os.path.join(dirname,'Resources', 'budget_data.csv') print (csvpath) # def sum_of_budget_data(date): # total = 0 # for val in date: # total = total + val # return total # budget_data = [Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,...