text
stringlengths
37
1.41M
class Transformer: """ Primitively, defines a transformation of str -> str. Base method is the transform(str) -> str. """ def transform(self, text: str) -> str: return text def chain(self, other): """Return a new transformer being the combination of sending the output of {self}...
#문자열 다루기 txt = 'python is easy!' print(txt[1]) #인덱스가 1번인 것을 가져와라 print(txt[-1]) #마지막 데이터 print(txt[-2]) #마지막에서 두번째 데이터 print(txt[7:9]) # start indes : stop index . 7에서 8까지 출력하고 싶다면 print(txt[0:2]) print(txt[:2]) #0번은 생략 가능 print(txt[10:14]) print(txt[10:-1]) #데이터 가져올 때 마지막 데이터를 빼고 싶다면 print(txt[-5:-1]) print(txt[-5:]) ...
##############Projeto de uma agenda AGENDA = {} #Declarada como variavel global, não preciso passar ela como parametro para as funções def buscar_contato(nome): a = 1 for name in AGENDA: if nome == name: #testa se o contato está na agenda print("Dados de {}".format(name)) #Imprimindo nome d...
class AI: def __init__(self, board): self.board = board def reduce(self): self.adjacent_threes() def adjacent_threes(self): for coord, number in self.board.numbers.items(): if number == 3: coords = self.board._get_coord(coord) for adjacen...
import numpy as np import backend import nn class Model(object): """Base model class for the different applications""" def __init__(self): self.get_data_and_monitor = None self.learning_rate = 0.0 def run(self, x, y=None): raise NotImplementedError("Model.run must be overriden b...
""" This script is made to create new game libraries """ import re import sys def create_library(old_dictionary, new_dict_language): """ Creates library in the filtered_dictionaries dict :return: nothing """ with open('assets/unfiltered_dictionaries/' + old_dictionary + '.txt', 'r') as outfile...
from random import randint num=randint(1,100) print('\nI will think a number between 1 and 100 u need to guess that number.\n') print('Rule:-\n\t1. When you are close to the number it gets warm otherwise cold.') print('\t2. The closer u go it goes warmer otherwise it get colder.\n') gusslist=[0] flag= False guess = ...
a=int(input("enter number")) b=int(input("enter number")) print("number after swapping are a = ",a," & b = ",b) a=a+b b=a-b a=a-b print("number after swapping are a = ",a," & b = ",b)
def slice_less(my_list, lesser): q = [] for i in sorted(my_list): if i > lesser: q.append(i) q.reverse() return q
from math import pow def IsPointInCircle(x, y, xc, yc, r): return pow(x - xc, 2) + pow(y - yc, 2) <= pow(r, 2) a = float(input()) b = float(input()) c = float(input()) d = float(input()) e = float(input()) print(IsPointInCircle(a, b, c, d, e) * "YES" or "NO")
n = int(input()) dct = {} for i in range(n): key, value = input().split() dct[key] = value dct[value] = key word = input() print(dct[word])
def formatting(sample): sample = ''.join([c for c in sample if c not in '()+-']) if len(sample) == 7: sample = '495' + sample else: sample = sample[1:] return sample new = formatting(input()) for i in range(3): cur = formatting(input()) if cur == new: print('YES') e...
def genDecDigs(cntDigits, maxDigit): if cntDigits > 0: for nowDigit in range(maxDigit + 1): for tail in genDecDigs(cntDigits - 1, nowDigit): yield nowDigit * 10 ** (cntDigits - 1) + tail else: yield 0 print(*genDecDigs(2, 3))
class Question: def __init__(self, prompt, answer): self.prompt = prompt self.answer = answer question_prompts = [ "\n1. Is Mount Shasta an active volcano?\n(a) Yes\n(b) No\n(c) I hope not!\n\n", "\n2. On average how often does Mount Shasta erupt?\n(a) Never\n(b) Every 60 years\n(c) ...
# This a copy of the Node API we put in program.py, in case you delete it. class Node: def __init__(self, prefix): """ Creates a Node with the given string prefix. The root node will be given prefix ''. You will need to track: - the prefix - whether this prefix is also a complete word - c...
numbers = [3, 4, 7, 34, 59, 88, 120] numbers.sort() print (numbers) print ('The largest number in the list is', numbers[-1])
numberslist = [3, 4, 7, 34, 59, 88, 120] for x in numberslist: if x % 2 == 0: print (x)
testline = (input('Say a word')) freq = {} for letter in testline: if letter in freq: freq[letter] += 1 else: freq [letter] = 1 print (freq)
import numpy as np #imports numpy and names as np import pandas as pd #imports pandas and names as pd import matplotlib.pyplot as plt #imports matplot and names as plt def combine_rows(data_frame, row_labels, name, drop=True): #function to combine rows, takes fram, labels, name as parameters, sets drop=T """ A...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ...
import os import csv # Open and read csv file /Users/feldtmam1/Documents/Data Analytics Bootcamp/repos/python-challenge/PyBank #csvpath = os.path.join('/Users/feldtmam1/Documents/Data_Analytics_Bootcamp/repos/python-challenge/PyBank/', 'budget_data.csv') with open('budget_data.csv', "r" ) as my_file_handle: # ...
# 231. Power of Two class Solution: def isPowerOfTwo(self, n: 'int') -> 'bool': if n==0: return False else: return (n&(n-1))==0
#!/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np import math ##### read the data files ######################## # I put the data in two files: 'datax.txt' and 'datay.txt' # datay.txt contains the x values and # datax.txt contains the y values because # I messed up. xfile = open("datay.txt", "r")...
""" def saludar(): print("holiii") saludar() def suma(a,b): return a + b num1 = 5 num2 = 6 print(suma(num1, num2)) def foo(*args, **kwargs): print(args) #tupla print(kwargs) #diccionario foo ('dba',1, name = 'joy', age=32) f = lambda x: print(x) f('hola') print(f) """ def myfunc(n): return lambda a : a...
#!/bin/python3 import math import os import random import re import sys # Complete the compareTriplets function below. def compareTriplets(a, b): print(alice,bob) if __name__ == '__main__': a = list(map(int, input().rstrip().split())) b = list(map(int, input().rstrip().split())) alice=0 ...
# Draw Sigmoid with given t def draw_sigmoid(t): ''' Simple plotting function that draws a sigmoid curve in a xkcd (<3) way. For multiple t, subplots are being created. @t: list with min 1 and max 4 integer values. ''' if len(t) > 4 or t < 1: raise ValueError("Wrong length of t. (has to ...
#!/usr/bin/env python3 TNUM = 0 TSYM = 1 TOPEN = 2 TCLOSE = 3 TEOF = 4 TokenStr = ('Number', 'Symbol', 'LeftParen', 'RightParen', 'EOF') def lerror(msg): raise RuntimeError(msg) def tokenize(s): i = 0 mlen = len(s) result = [] while i < mlen: while i < mlen and s[i].isspace(): ...
my_file = open('test.txt') print(my_file.read()) my_file.seek(0) print(my_file.read()) my_file.seek(0) contents = my_file.read() print(contents) my_file.seek(0) contents_list = my_file.readlines() print(contents_list) my_file.close() with open('test.txt') as my_file: contents = my_file.read() print...
# Comparison operators return boolean values. print(2 == 2) # returns true print(2 == 1) # returns false print('hello' == 'Hello') # comparing strings are size sensitive print('Hello' == "Hello") print('2' == 2) # returns false print(1.0 == 1) # returns true print(3 != 3) # returns false print(4 !...
def my_func(a, b): # return 5% of the sum of a and b return sum((a, b)) * 0.05 print(my_func(40, 60)) # in above code number of arguments passed to function is limited. # Using *args def my_func(*args): # *args builds a tuple of all the value passed return sum(args) * 0.05 print(my_...
my_set = set() my_set.add(1) print(my_set) my_set.add(2) print(my_set) my_set.add(2) print(my_set) # casting a list to set my_list = [1, 1, 1, 3, 2, 2, 3] my_set = set(my_list) print(my_set)
#requirements - given an array of numbers, find a number that appears an odd number of times| input = [1,1,1,2,2] # looks at all numbers, tells you know which one is in the list odd # of times def find_number_of_odd_count (numbers): for num in numbers: num_count = get_count(num, numbers) if is_...
from Currency import Currency, getInstance class Money(object): """Money objects represent money in various currency. They support methods for testing a money's currency, formating them for display, converting them to and from different currencies as well as provide methods to preform mathmatical oper...
# Move all zeroes to the end of the array while preserving the order of the non-zero elements def moveZeroes(nums): counter = 0 for num in nums: if num == 0: nums.remove(num) nums.append(0) return nums
import numpy as np import random random.seed(1) def create_board(): emptyBoard = np.zeros((3,3), dtype = int) return emptyBoard def place(board, player, position): if player == 1 or player == 2: if board[position] == 0: board[position] = player return board else: ...
#print out the times tables from 1 to 10 using a loop def tablesOnetoTen() : x = 1 y = 1 for x in range( 1, 11 ) : print( "Table for {} * ( 1-10 )".format(x) ) for y in range( 1 , 11 ) : print( x * y, end=" " ) print() tablesOnetoTen()
#!/usr/bin/env python3 import collections def remove_duplicates(results): return [item for item, count in collections.Counter(results).items() if count == 1] # test print(remove_duplicates(["1", "1", "2", "3"]))
# WHILE loop: # With the while loop we can execute a set of statements as long as a condition is true a = 1 while a < 8: a += 1 # If you dont use this loop will run (printing 1) forever print (a) # BREAK statement: # With the break statement we can stop the loop even if the while condition is tr...
a = "Hello World" print(a) b = """today the world looks so clean and fresh""" print(b) print(len(a)) #length of the string print(a[1]) #index with in the string print(a[0:5]) #range with in the string print(a.lower()) print(a.upper()) print(a.count('Hello')) print(a.count('o')) print(a.count('l')) print...
''' Created on May 7, 2017 @author: sourish.sarkar ''' s1='apples' s2="oranges" s3="grapes" s5="John likes {},{},{}".format(s1,s2,s3) print("s5" ,s5) #Positional arguments s6="John likes {1},{0}, {1}".format(s1,s2) print("s6:",s6) #Keyword arguments s7="John likes {app},{ora},{app}".format(app=s1.capitalize(),ora=s2.s...
import math class RpnCalculator: def __init__(self): self.history = [] ## Calculator methods def push(self, value): """ Adds a value to the calculators stack """ self.history.append(value) def result(self): """ Returns the last pushed value fr...
import pyttsx3 import datetime import speech_recognition as sr import pyaudio import wikipedia import webbrowser import os engine = pyttsx3.init("sapi5") voices = engine.getProperty('voices') engine.setProperty('voice',voices[1])#engine.setproperty('voice',voices[0].id) def speak(audio): engine.say(audio) e...
# ¿Por qué hay un error en el codigo y como se podria arreglar? ''' def foo(a, b): print(a + b) x = foo(2, 3) * 10 ''' # No se puede multplicar oprque la funcion no devuelve nada. # Para arreglarlo necesitamos un return def foo(a, b): return(a + b) x = foo(2, 3) * 10 print(x)
#--------------------------------------------------------------------- # Una tupla es una coleccion ordenada e inmutable. Se escriben con () # No podemos ni añadir ni eliminar elementos una vez creada la tupla, # pero si podemos unir varias tuplas #--------------------------------------------------------------------- ...
print("----Primer try except----") try: n = int(input("Introduce un entero: ")) except: print("Eso no es un numero entero") print("----Segundo try except----") try: sum = 0 file = open("numero.txt", "r") for numero in file: sum = sum + 1.0 / int(numero) print(sum) except ZeroDivisionErr...
# Escribe un programa que pregunte al usuario en bucle texto. Para # parar la solicitud tendrá que escribir "CERRAR" ruta = "exercices\\ficheros\\ej96.txt" # Opción nº1 ''' while True: entrada = input("Escribe un valor: ") if entrada == "CERRAR": break with open(ruta, "a+") as fichero: ...
# Crea un scrip que deje al usuario escribir cualquier palabra y # automaticamente se abra el navegador con el termino buscado en # el motor de busqueda google import webbrowser busqueda = input("¿Que desea buscar?: ") webbrowser.open_new("http://www.google.com/?#q={}".format(busqueda))
# Crea un script que genere y muestre una lista con un # rando del 1 al 20. rango = range(1, 21) print(list(rango)) # La funcion range() genera un objeto rango de enteros. Para # obtener la lista necesitamos usar list() paras convertir # el objeto rango() en una listas
# Crea un programa que imprima "Hola". Cada iteración va a aumentar # en un segundo el tiempo de espera para volver a imprimir import time i = 2 while 1 < 2: print("Hola") time.sleep(i) i += 1
# Accede al tercer valor de la clave desde el diccionario. b from pprint import pprint d = dict(a = list(range(1,11)), b = list(range(11, 21)), c = list(range(21,31))) print(d["b"][2])
''' d = {"Name": "John", "Surname": "Smith"} print(d["Smith"]) ''' # En la parte superior, Smith, no es una clave, es un valor. # Pare mostrar el valor deberiamos indicar print(d["Surname"]) d = {"Name": "John", "Surname": "Smith"} print(d["Surname"])
# ¿Por que hay un error en este codigo y como lo puedes arreglar? ''' def foo(a=1, b=2): return a + b x = foo - 1 ''' def foo(a=1, b=2): return a + b print(type(foo())) x = foo() - 1 print(x)
# El siguiente código imprime "Hola", comprueba si 2 es mayor que 1 y # entonces se para el bucle porque la condicion es correcta. Reemplaza # el break con algo mas para que se muestre "Hola" en bucle infinito ''' while True: print("Hola") if 2 > 1: break print("Hi") ''' while True: print("H...
# Se supone que el codigo debe de pedir al usuario un nombre y apellido, # y este lo imprima por pantalla. En lugar de eso lanza un error ''' irstname = input("Enter first name: ") secondname = input("Enter second name: ") print("Your first name is %s and your second name is %s" % firstname, secondname) ''' firstnam...
from tkinter import * class Form: def __init__(self, rules_file): self.root = Tk() self.root.title("Ludo") self.frame1 = Frame(self.root) self.label1 = Label(self.frame1, text="Player Name", fg="black") self.name = Entry(self.frame1, width=20) self.label2 = Labe...
import pygame from setup import SCREEN from constants import BLACK pygame.init() class Box(object): """ Class to represent a box. It has an: - x, y, width 'w' and height 'h' - colour 'c' - size of line, default 0 """ def __init__(self, msg, x, y, w, h, c, s=0): self._msg ...
# -*- coding: utf-8 -*- # __author__: Re def divsion(): a = 5.0 b = 6 c = a/b d = a//b # / 与 // 整除(地板除)与浮点除 地板除 取比商小最大整数 ??? # 结果完全由操作数类型决定 print(str(c)) print(str(d) ) print(-2*4+ 3**2) if __name__ == "__main__": divsion()
# !/usr/bin/python # -*- coding: utf-8 -*- # __author__: Reworld if __name__ == "__main__": foo = 'abc' for i in range(len(foo)): print foo[i], '(%d)' % i for i, ch in enumerate(foo): print ch, '(%d)' % i sqdEvens = [x ** 2 for x in range(8) if not x % 2]
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ """ Each input record is a 2 element list [personA, personB] where personA is a string representing the name of a person and personB is a string representing the name of one of personA's friends. Note that it may or may ...
import unittest class Calculator: def add(self, a, b): return a + b class TestCalculator(unittest.TestCase): def test(self): c = Calculator() a = 3 b = 4 exptected = 7 result = c.add(a, b) self.assertEqual(result, exptected) t = TestCalcu...
import pandas as pd s1 = pd.Series([1,2,3,4,5,6,7]) print(s1) print(s1+5) #i.e. 0th location + 5 so the output starts from the element 6 till 12 s2 = pd.Series([11,22,33,44,55,66,77]) #s2 = pd.Series([11,22,33,44,55,66]) #output comes in float and last element is displayed as Nan print(s2) print(s1+s2) #output gi...
l, r = input().split() l = int(l) r = int(r) if l == 0 and r == 0: print("Not a moose") elif l == r: print("Even", l + r) else: print("Odd", max(l, r) * 2)
''' Created on Jul 22, 2015 @author: jiahuan ''' print ("Hello World!") print (1 + 2*3) a = 10 while a < 20 : a = a + 2 print a #define my own Function def hello(): print("\nHello from function hello()") return 12345 print hello() a = [-1, 0, 2, 4, 6, 8, 10] print ("\nbefore deletion, a is:...
#1 import library import pygame from pygame.locals import * #2initialize the game pygame.init() width,height=1083,493 screen=pygame.display.set_mode((width,height)) #3load game player=pygame.image.load("resources/carp.png") road=pygame.image.load("resources/road.png") #4keep looping through running=1 exitc...
#Version Python de l'exercice 2 a = 1 b = 2 print(f"a vaut {a} et b vaut {b}") a,b = b,a print(f"a vaut {b} et b vaut {a}")
#!/usr/bin/python3 class Tour : def __init__(self, quillesAuPremierLancer = 0, quillesAuDeuxiemeLancer = 0, quillesAuTroisiemeLancer = 0): self.quillesAuPremierLancer = quillesAuPremierLancer self.quillesAuDeuxiemeLancer = quillesAuDeuxiemeLancer self.quillesAuTroisiemeLancer = quillesAuTr...
# create and open a file with open("NewFile.txt", "a+") as f: f.write("We are writing some new text here.") f.close() f = open("NewFile.txt", "r+") radme = f.read(33) print(radme) f.close()
#Create a class that contains #information about employees of a company and #define methods to get/set employee name, job title, and start date. class Employee(object): '''Employees which can be hired (aggregated) by a company''' def __init__(self, name, title, start_date): self.name = name sel...
def main(): testfunc(42) testfunc(42, 50) # Adding default values to method arguments makes those arguments optional. # If you want the value to be optional but have no value, specify the value 'None' def testfunc(arg1, arg2 = None, arg3 = 10): # pass # Check for no argument if arg2 is None: ...
#fibonnaci in a function def funk(number): if number==1 or number==2: return 1 return funk(number-1)+funk(number-2) print(funk(8))
#OPERATORS print("OPERATORS".lower()) print(2 + 5 * 3) print((2 + 5) * 3) num1 = 5 num2 = 9 print(num1 + num2) print(num1 * num2) num3 = 1 num3 += 1 print(num3) print(10 % 3) print(10 % 2) print("Hello" * 5) print("-" * 60) # Oprerator Predence # Highest Precedence # () Parentheses # ** Exponentiation # * Mul...
while True: aNumber = input("Enter a number: ") if not aNumber: break try: aNumber=int(aNumber) except ValueError: print("Invalid input") continue print((aNumber) ** 2)
import string def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ # TODO your code here inits = fullname[0].upper() temp = "" counter = 0 for char in fullname: if char.isspace(): temp = fullname[counter + 1] inits ...
from decimal import Decimal def notstr(instr): instr = instr.replace("1", "z") instr = instr.replace("0", "1") instr = instr.replace("z", "0") return instr def bintodec(floatnum): x = Decimal("0") floatnum = floatnum.replace(".", "") sign, floatnum = floatnum[0], floatnum[1:] if sign...
class Building: def __init__(self, x1, y1, x2, y2, house_name): self.house_name = house_name # upper left: self.ul_x = int(x1) self.ul_y = int(y1) # bottom right: self.br_x = int(x2) self.br_y = int(y2) self.size = self.infr_size_calc(self.ul_x, self....
from turtle import * colors = ['red', 'blue', 'brown', 'yellow', 'grey'] shape("turtle") speed(1) left(180) for n in range (3,8): print(n) color (colors[n-3]) count_loops = 0 while True: count_loops = count_loops + 1 print(count_loops) right(180*2/n) forward (100) ...
from turtle import * shape("turtle") n = 20 speed(50) for i in range (n): forward (2*i) left (90) forward (2*i) mainloop()
#4.a print("* "*20) #4.b n = int(input("Enter a number: ")) print ("* "*n) #4.c print("x * "*4, end ="") print("x") #4.d n = int(input("Enter a number: ")) if n%2 == 0: m = int((n/2)) print("x * "*m) else: m = int((n-1)/2) print("x * "* m, end="") print("x") #4.e print() #4.f for i in range (1,4): ...
# 1. Create connection from urllib.request import urlopen from bs4 import BeautifulSoup from youtube_dl import YoutubeDL import pyexcel url = "https://www.apple.com/itunes/charts/songs" conn = urlopen(url) # 2. Download content raw_data= conn.read() page_content = raw_data.decode("utf8") with open("dantri.html","wb"...
n = int(input("Nhap so: ")) s = 0 for i in range(0,n+1,2): s +=i print(i, end = " ") print ("Tong la :",s)
our_items = ["T-shirt","Sweater"] while True: Request = input("Welcome to our shop, what do you want (C, R, U, D)? ") if Request =="R": print(our_items) elif Request =="C": new_item = input("Enter new item: ") our_items.append(new_item) print(our_items) elif Request == "...
from flask import Flask import os import models import routes def create_app(): """Construct the core flask application This allows to create only one instance named app by using basic factory pattern, and to define some config for app. Returns: app: unique instance of flask app for whol...
# Generators def create_cubes(n): for x in range(n): yield x**3 for x in create_cubes(10): print(x) def gen_fibon(n): a = 1 b = 1 for i in range(n): yield a a,b = b,a+b for number in gen_fibon(10): print(number) def simple_gen(): for x i...
a = 5 print( a ) a = 10 print( a ) print( a + a ) print(a) a = a + a print(a) print(type(a)) a = 30.1 print(type(a)) my_income = 100 tax_rate = 0.1 my_taxes = my_income * tax_rate print(my_taxes)
# Advance Dictionaries d = {'k1':1,'k2':2} print({k:v**2 for k,v in zip(['a','b'], range(2))}) for k in d.keys(): print(k) print(d.values())
# Functions def name_function(): ''' DOCSTRING: Information about the Functions INPUT: no input... OUTPUT: Hello .. ''' print('Hello') #help(name_function ) def say_hello(name='Jose'): return 'hello ' + name result = say_hello('David') print(result) def add(n1,n2): return n...
z=eval(input("Dati numarul de zile: ")) if ((z<28)or(z>31)): print("Nu sunt luni cu asa numar de zile") elif z==28: print("e luna februarie, nu e an bisect") elif z==29: print("e luna februarie,e an bisect") elif z==30: print("aprilie,iunie,septembrie,noiembrie") else: print("ianuarie,mart...
n=eval(input("dati numarul:")) s1=0 s2=0 a=0 b=0 c=0 d=0 for i in range (1,n+1): s1+=i**3 i=0 for i in range (1,n+1): a+=i s2=a**2 i=0 if s1>s2: print("a:prima suma > a doua suma") if s1==s2: print("a:sumele sunt egale") if s2>s1: print("a: a doua suma > prima suma") ...
# string concatenation ( how do yo put strings together) # suppose we want to create a string that says "subscribe to _____" #youtuber = " Jenny Augustin" # some string variable # a few ways to do this #print("subscribe to"+youtuber) #print("subscribe to{}".format(youtuber)) # put any youtuber you type into {} #prin...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Creates a csv file containing the financial data of specified organizations using ProPublica. Inputs: LIST_OF_ORGS_FILE (the list of propublica numbers) EXISTING_DATA_FILE (any data that is already compiled, including manual data) Output: finaldata.csv (data autograbb...
import deck as d CARDS_IN_HOLE = 2 CARDS_IN_FLUSH = 5 class StudPokerHand: print_hand = "" cards_in_hand = 2 def __init__(self,deck): self.hand = [] self.deck = deck def __str__(self): """Print hands in a more visible format.""" self.print_hand = "" for x i...
from collections import deque class LinkedList: def __init__(self): self.data = deque() def get_size(self): return len(self.data) def is_empty(self): return self.get_size() == 0 def value_at(self, index): return self.data[index] def push_front(self, value): ...
# -*- coding: utf-8 -*- """ Created on Mon Dec 4 17:30:19 2017 @author: Mark Pei @email: duchungk7@gmail.com """ # Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Salary_Data.csv') X = datase...
#!/usr/bin/env python """Script that archives all files and folders in the current working directory""" import os import zipfile __author__ = "Kiran Vasudev" def recursive_archive(directory, archive_name): all_Files_and_Folders = [ item for item in os.listdir(directory) if item != archive_name+".zip" ] for ...
# Problem 2: Wranging Regions # Name: # Introduction: The data gathered here tells us universities, their region, their starting salary # and their final salary. The overall goal of this practicum is to import this data, # clean the data, put it in a useful form to do calculations, and then display it # It is an impo...
# Your name: Ken Ma # Your class-section: SECTION 1 # Do not change this in any way! brackets = [ ["single", 12000, 0.37, [[ 0, 9525, 0.10], [ 9526, 38700, 0.12], [ 38701, 82500, 0.22], [ 82501, 157500, 0.24], [157501, 200000, 0.32], [200001, 500000, 0....
# Problem 3: Greatest Common Divisor and Least Common Multiple # Name: Ken Ma # Introduction: # Website: https://en.wikipedia.org/wiki/Greatest_common_divisor # Website: https://en.wikipedia.org/wiki/Least_common_multiple # The greatest common divisor (GCD) and least common multiple (LCM) between two # numbers are som...
#!/usr/bin/env python #-*- coding: utf-8 -*- def birinci_soru(): print "bu\nkty\nretmeli." def sqrt(n): approx = n / 2.0 better = (approx + n / approx) / 2.0 while better != approx: approx = better better = (approx + n / approx) / 2.0 print better return ap...
#!/usr/bin/env python #-*- coding: utf-8 -*- def capitalize_2(cumle="gökhan"): if 97 <= ord(cumle[0]) <= 122: n = chr(ord(cumle[0]) - 32) print n + cumle[1:]
class oncelikli_kuyruk: def __init__(self): self.items = [] def peek(self): return self.items[0] def enq(self, item, priority): if self.isEmpty(): self.items.insert(0, (item, priority)) print self.items else: peek = self.peek() ...