text stringlengths 37 1.41M |
|---|
"""
Short script to create a dictionary for PR algo. Requires python 3.6+
for default ordered dictionaries.
Use main() to get the dictionary.
Dictionary contains swimmer names as keys, and meet[] objects as values.
Concrete example: {'Phelps Michael' : [2016 Olympics, Worlds], 'Adrian, Nathan G' :[2016 Olympics, Pan Am... |
def clean_data(data):
return list(map(int, data[0].split()))
def get_max(data):
# ties are broken by order, so first largest is largest
current_max = [0,0]
for i, val in enumerate(data):
if val > current_max[1]:
current_max = [i, val]
return current_max
def redistribute_data(... |
import itertools
def clean_data(data):
# passphrases are strings of characters separated by spaces
return list(map(lambda x:x.split(" "), data))
def is_unique(passphrase):
# passphrase contains duplicate words if casting to set changes (reduces) length
return len(passphrase) == len(set(passphrase))
d... |
import random
database = {}
def init():
import datetime
print("Welcome to HorlarBank")
print("=== ==== ====== ==== ====================")
datetime_object = datetime.datetime.now()
print(datetime_object)
print("=== ==== ====== ==== ====================")
haveAccount = int(input("Do... |
# -*- coding: utf-8 -*-
import os
import sys
import math
print("Oblicz dzienne zapotrzebowanie kaloryczne")
name = input("Podaj swoje imię: \n")
if name[-1] == "a":
name = int(-161)
else:
name = int(+5)
height = int(input("Podaj swój wzrost w centymetrach: \n"))
weight = int(input("Podaj swoją wagę w kilogramac... |
'''
Lorin Vandegrift
2/7/2015
Assigment 1:
-- Number Operations: add, sub, mul, div, eq, lt, gt
-- Boolean Operators: and, or, not
Sequencing Operators: if, ifelse
-- Create Dictionary: dictz (No operands)
-- Stack Operations: begin, end
-- Name definition: def (takes value and name)
-- entire stack printing: s... |
from itertools import permutations
n=input()
a=[]
a=list(permutations(n))
for i in range(0,len(a)):
print(*a[i],sep='')
|
"""
Day 1 - Single Number
LeetCode Easy Problem
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:... |
n = int(input("lutfen bir sayi giriniz :"))
for i in range(1,n+1):
print(("#"*i).rjust(n), end="\n")
|
# Credit to KINOCK SEBASTIAN for this code
import tweepy
# Reading Consumer key and secret from consumerKeys File
consumerKeyFile = open("consumerKeys", "r")
consumerKey = consumerKeyFile.readline().strip()
consumerSecret = consumerKeyFile.readline().strip()
consumerKeyFile.close()
# authenticating twitter consumer ... |
from openpyxl import Workbook
sheet = workbook.active
# Let's say you have two sheets: "Products" and "Company Sales"
print(workbook.sheetnames)
# You can select a sheet using its title
products_sheet = workbook["Products"]
sales_sheet = workbook["Company Sales"]
products_sheet.title = "New Products"
print(workbook... |
import os,time,keyboard,json,hashlib,ast,numpy,menu
import system_choose as sc
import score as ds
import matplotlib.pyplot as plt
if __name__ == "__main__":
score = dict()
with open("score.json","r",encoding = "UTF-8-sig") as f:
some_string = f.read()
if not some_string:
score = {}
... |
import openpyxl
# create workbook
# wb = openpyxl.Workbook()
# for loading the existing workbooks
wb = openpyxl.load_workbook('transactions.xlsx')
# print(wb.sheetnames)
sheet = wb['Sheet1']
# wb.create_sheet('Sheet2',0)
# wb.remove_Sheet(sheet)
# to get the cell
# cell = sheet['a1']
# print(cell.value)
# to cha... |
numbers = [1,5,7,5,8,1,9,6,4,7,13,9,7,1,36,3,5]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
|
def phone_magic():
phone = input("phone: ")
# A new dictionary (key, value)
digits_mapping= {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five"
}
output = ""
for ch in phone:
output += digits_mapping.get(ch, "!") + " "
print(output)
def another_function(a, b):
print(a*b)
print("s... |
# A new tuple, it cannot be changed.
# You can't add, remove or change any item. Like a constant.
numbers = (7,5,1)
x, y, z = numbers #unpacking the values of numbers tuple
print(x)
print(y)
print(z)
coordinates = [10.25, 54.88, 124.56, 8.96] # a new List
x, y, z, w = coordinates #unpacking the values
print(x)
pri... |
import random # standard module of python3 library
print("random float nums")
for i in range(3):
print(random.random())
print("\nrandom integers")
for i in range(5):
print(random.randint(0, 10))
print("\nSelect leader")
members = ['Vaios', 'John', 'Mary', 'Dimitra']
leader = random.choice(members)
print(leader)
|
import turtle
var=turtle.Turtle()
s=turtle.getscreen()
turtle.screensize(1800,3200)
s.bgcolor("black")
var.hideturtle()
var.pencolor("red")
var.penup()
var.setposition(140,-270)
var.pendown()
var.write("Stay Home, Stay Safe!",'false','right', font=('Showcard Gothic',20))
var.penup()
var.setposition(100, -32... |
class Rectangle:
def __init__(self, b, l):
self.b = b
self.l = l
def area(self):
return self.l * self.b
def perimeter(self):
return 2 * (self.l + self.b)
l = int(input("enter length of 1st rectangle:"))
b = int(input("enter breadth of 1st rectangle:"))
arr = Rectangle(l, ... |
# Priklad definicie triedy. Zbytocnej triedy
class Person:
name = "Michal"
def print_name():
print(f"Name is {Person.name}")
Person.print_name()
# Trieda je nejaky predpis niecoho v tomto pripade je to predpis osoby kazda osoba ma meno a priezvisko
class Person:
def __init__(self, name, surname):
... |
# OVERLOADING
class Person:
def __init__(self, name, surname):
self.name = name
self.surname = surname
def say_hello(self, name=None):
print("Hello") if not name else print(f"Hello {self.name}")
person = Person("Michal" ,"Hucko")
person.say_hello()
person.say_hello(name=True)
# ... |
#while(true):
try:
def add():
n1=int(input('enter a number\n'))
n2=int(input('enter a number\n'))
sum=n1+n2
print('n1 and n2 equal=',sum)
add()
except ValueError:
print('plz enter a integer type value')
|
myDate = int(input('Enter a number\n'))
month = myDate // 30 + 1
day = myDate % 30
if day == 0:
day = 30
month -= 1
print('The day is: %d and the month is: %d' % (day, month))
|
# Search for a word in a sorted list
def search_in_list(thelist, word):
if len(thelist) == 0:
return False
if len(thelist) == 1:
if word == thelist[0]:
return True
else:
return False
mid = len(thelist) // 2
if word >= thelist[mid]:
thelist = thel... |
"""
Write a script that reads the current time and converts it to a time of day in hours, minutes, and
seconds, plus the number of days since the epoch.
"""
import time
print('**** started ****')
seconds_in_a_day = 24 * 60 * 60
the_time = time.time()
print('time:', the_time)
days = the_time // seconds_in_a_day
prin... |
import sys
import listsearch
sys.path.append(r"C:\DevLcl\Sandbox\python-sandbox\think_python\chapter_10")
fin = open(r'C:\DevLcl\Sandbox\python-sandbox\think_python\words.txt')
def word_list():
thelist = []
for line in fin:
thelist.append(line.strip())
return thelist
def find_reverse_pair(mylist... |
def is_triangle(a, b, c):
if a > b+c or b > a+b or c > a+b:
print('No')
else:
print('Yes')
print('Give me "a", "b", "c" one after eachother')
a = int(input())
b = int(input())
c = int(input())
is_triangle(a, b, c)
|
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return 'Point is located at: x=%g, y=%g' % (self.x, self.y)
def __add__(self, other):
if isinstance(other, Point):
return self.add_point(other)
elif isinstance(other, tu... |
target = 999
def sumDivisibleBy(n):
p = target // n
sum = n * (p * (p + 1)) / 2
return sum
result = sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15)
print(result)
|
def main():
from math import sqrt
a=4
b=5
oper1 = float((2*(3/4)) + (4*(2/3))- (3*(1/5)) + (5*(1/2)))
oper2 = float(2*math.sqrt(35**2) + 4*math.sqrt(36**3) - 6*math.sqrt(49**2))
oper3 = float((a**3 + 2*b**2) / (4*a))
oper4 = float((2*((a+b)**2) + 4*((a-b)**2)) / (a*b**2))
oper5 = float((... |
"""
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 100 # Number of trials to run
SCORE_CURRENT = 1.0 # Score for... |
from Animal.Role import *
from Animal.Danaus.plexippus import *
from Land_Use.Developed.farm import *
import numpy as np
import pandas as pd
from Functions.Tests import *
def iterate_field(group: list = None, number_fields: int = 2) -> CropField:
"""
Iterate groups of fields to find optimal arrangements. Grou... |
# python3
import sys
def swap_by_index(values, a, b):
temp = values[a]
values[a] = values[b]
values[b] = temp
def selection_sort(values):
for i in range(0, len(values)):
min_index = i
for j in range(i + 1, len(values)):
if values[j] <= values[min_index]:
m... |
#!/usr/bin/python
"""
this is the code to accompany the Lesson 3 (decision tree) mini-project
use an DT to identify emails from the Enron corpus by their authors
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess impor... |
# Python common data structures
# data structures are just ways for us to store information for easy access and use
names = ["Adam", "Bill", "Steve"]
# lists will reisize as needed and can store any type
# lists are MUTABLE always add or remove elements
# lists can contain duplicates
stuff = ["Apple", 4, [[],1], 9.8,... |
# a lambda is an anonymous function
# () =>{}
# popular in funcitonal programming
nums = [1,2,3,4,5,6]
result = map(lambda n : n*10,nums)
# Lambdas are NOWHERE near as common or useful in python as in other languages JS
for r in result:
print(r) |
# a simple greeting app that supports saying hello in many different languages
import english # import the python file (A python file is called a module)
from spanish import hola
from germanic_languages.german import gutentag
name = "Adam"
english.hello(name) # if you import just the module
# you have to use the m... |
# Common Errors in Python
# LookUpError: get an index that does not exist from a list or tuple or use dictionary key that does not exist
# TypeError: when you pass in a variable that is of the wrong type (pass in a str instead of int/float)
# ValueError: when the type is right but the value of that variable is wrong
# ... |
#!/usr/bin/env python
"""
generate_graph.py
Generates a random graph for grading. For use
please run the module with --help
"""
__author__ = "Bobby Streit"
__version__ = "1.0"
__maintainer__ = "Bobby Streit"
__email__ = "rpstreit@utexas.edu"
import argparse
import random
MAX_WEIGHT = 100
PARSER = argparse.Argu... |
N = int(input())
star = '*'
stars = '* '
stars2 = ' *'
for i in range(N):
if N%2==0:
print(stars*(N//2))
print(stars2*(N//2))
else:
print(star + stars2*(N//2))
print(stars2*(N//2)) |
# RPG based on the game of fadishouis
# 12 issue run: January 2020 -January 2020
import sys
print("fadishouis: The game changing the earth")
print("Valid actions for current location")
# valid directions and actions for the characters
valid_actions = {"directions": ["north", "south", "east", "west"],
"... |
class Node:
def __init__(self, v):
self.value = v
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.current = None
def add_in_tail(self, item):
if self.tail is None:
self.head = item
self.current = item
else:
self.tail.next = it... |
class Node:
def __init__(self, v):
self.value = v
self.prev = None
self.next = None
class OrderedList:
def __init__(self, sort_ascending = True):
self.head = None
self.tail = None
self.sort_ascending = sort_ascending
def print_all_nodes(self):
node = self.head
while node != None:
print(node.valu... |
import pygame
import time
import random
pygame.init()
pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)
screen = pygame.display.set_mode((1280,720))
done = False
#set initial variables
p1_x,p1_y=30,30
p2_x,p2_y=(screen.get_width()-60),30
ball_x,ball_y=((screen.get_width())/2),((screen.ge... |
# Natural Language Toolkit: Language Model Unit Tests
#
# Copyright (C) 2001-2023 NLTK Project
# Author: Ilia Kurenkov <ilia.kurenkov@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
from functools import partial
from itertools import chain
from nltk.util import everygrams, pad_sequ... |
# Natural Language Toolkit: API for alignment and translation objects
#
# Copyright (C) 2001-2023 NLTK Project
# Author: Will Zhang <wilzzha@gmail.com>
# Guan Gui <ggui@student.unimelb.edu.au>
# Steven Bird <stevenbird1@gmail.com>
# Tah Wei Hoon <hoon.tw@gmail.com>
# URL: <https://www.nltk.org/>... |
# Natural Language Toolkit: Simple Tokenizers
#
# Copyright (C) 2001-2023 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# Steven Bird <stevenbird1@gmail.com>
# URL: <https://www.nltk.org>
# For license information, see LICENSE.TXT
r"""
Simple Tokenizers
These tokenizers divide strings into substring... |
# Natural Language Toolkit: Positive Naive Bayes Classifier
#
# Copyright (C) 2012 NLTK Project
# Author: Alessandro Presta <alessandro.presta@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
A variant of the Naive Bayes Classifier that performs binary classification with
partia... |
# Natural Language Toolkit: Minimal Sets
#
# Copyright (C) 2001-2023 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
from collections import defaultdict
class MinimalSet:
"""
Find contexts where more than one possible target... |
#5.5
#while
x=1
while x<=100:
print str(x)
x=x+1
#for
words=["This","is","an","ex","parrot"]
for word in words:
print word
#range
for number in range(1,101):
print number
#key,value
d={"x":1,"y":2,"z":3}
for key,value in d.items():
print "key="+key+" value="+str(value) |
#9.6
class Fibs:
def __init__(self):
self.a=0
self.b=1
#implement __iter__
def __iter__(self):
return self
#implement next
def next(self):
self.a,self.b=self.b,self.a+self.b
return self.a
fibs=Fibs()
for f in fibs:
if f>1000:
print f
break... |
#example2-1
months=["January","February","March","April","May","June","July","August","September",
"October","November","December"]
endings=["st","nd","rd"]+17*["th"]+["st","nd","rd"]+7*["th"]+["st"]
year=raw_input("year: ")
month=raw_input("Month(1-12): ")
day=raw_input("Day(1-31): ")
month_number=int(month... |
#############################################
# This class implements the interface for a typical cipher.
# It defines functions usually used in a cipher
#############################################
class CipherInterface:
############################################
# Sets the key to use
# @param key - th... |
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
np.set_printoptions(precision=4)
obj = Series(range(3), index=['a', 'b', 'c'])
index = obj.index
print(index)
print(obj)
print(index[1:]) |
"""
source: https://leetcode.com/problems/search-insert-position/
author: hpjhc
date: 2018/10/21
"""
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
e... |
"""
source:https://leetcode.com/problems/roman-to-integer/
author: hpjhc
date: 2018/10/12
"""
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res = 0
for i, key in en... |
"""
source:https://leetcode.com/problems/1-bit-and-2-bit-characters/
author: hpjhc
date: 2018/9/21
"""
class Solution:
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
bits.pop()
res = 0
while(bits and bits.pop()):
res... |
import re
# Reg Expression
# Removing Begining of a String
str = ' hello python '
str = re.sub(r"^\s+", "", str, flags=re.UNICODE)
print("removed spaces at left side :",str)
# Ending of a string
str = ' hello python '
str = re.sub(r"\s+$", "", str, flags=re.UNICODE)
print("removed spaces at right side :",... |
# importing pandas module
import pandas as pd
# defining File path
fpath = "Fruit.xlsx"
# method to be used to read the excel file
data2 = pd.read_excel(fpath,sheet_name='sweet or sour',header=[0])
print(data2)
#Reading custom no. of rows and columns:
import pandas as pd
# File path
fpath = "Fruit.xlsx"
# method to be... |
if __name__ == '__main__':
languages = ['python', 'perl', 'groovy', 'java', 'curl', 'javascript']
for num, name in enumerate(languages):
print( num, name)
# index starts from 1
for num, name in enumerate(languages, start =1):
print( num, name)
# count of list items
for count, ... |
persons = {
'user_name':'chandra',
'first_name':'chandra shekhar',
'last_name':'goka'
}
#Looping key,values
for key,value in persons.items():
print(f"Key: {key} - Value: {value}")
favorite_subjects={
'chandra':'Computers',
'panvith':'Physics',
'jon':'Mathematics',
'robert':'Computers'... |
# A program to do simple math while demonstrating the use of Functions
def adding(num1, num2):
answer = num1 + num2
return answer
def subtracting(num1, num2):
answer = int(num1) - int(num2)
return answer
def multiplying(num1, num2):
answer = int(num1) * int(num2)
return answ... |
def display_board(x):
"""
This function displays the board for the X and O game before and after each turn.
"""
#prints the game table
print('|',x[0],'|',x[1],'|',x[2],'|')
print('|',x[3],'|',x[4],'|',x[5],'|')
print('|',x[6],'|',x[7],'|',x[8],'|')
def turn(y):
"""
Dec... |
#!/usr/bin/env python3
"""tuple typeanotation
create a tuple
"""
from typing import Tuple, Callable
def make_multiplier(multiplier: float) -> Callable[[float], float]:
"""make a multiplier call
Args:
multiplier (float): [number to use]
Returns:
Callable[[float], float]: [function to make... |
"""
This code is part of Data Science Dojo's bootcamp
Copyright (c) 2016-2018
Objective: Explore and visualize data using Python
Data Source: Multiple
Python Version: 3.4+
Packages: matplotlib, pandas, seaborn
"""
# Script for following along in Data Exploration and Visualization module
# Set your working directory t... |
"""
This code is part of Data Science Dojo's bootcamp
Copyright (c) 2016-2018
Objective: Machine Learning of the Kyphosis dataset with a Decision Tree
Data Source: bootcamp root/Datasets/kyphosis.csv
Python Version: 3.4+
Packages: scikit-learn, pandas, numpy, pydotplus
"""
from sklearn.tree import DecisionTreeClassifi... |
a=3
b=4
print('the value of a+b is ',3+4) #Arithmetic Operators
print('the value of a-b is ',3-4) #Arithmetic Operators
print('the value of a*b is ',3*4) #Arithmetic Operators
print('the value of a/b is ',3/4) #Arithmetic Operators
print('the value of a%b is ',type(3%4)) #Arithmetic Operators
#Assignment operators
a=... |
# inspired from https://www.bogotobogo.com/python/Multithread/python_multithreading_Synchronization_Producer_Consumer_using_Queue.php
import threading
import time
import random
import queue
q = queue.Queue()
class ProducerThread(threading.Thread):
def __init__(self, target=None, name=None):
super(Produce... |
#!/usr/bin/python3
# Prints the weather from the command line.
# From Automate the boring stuff.
import json
import requests
location = input("Enter the City: ")
countrycode = input("Enter country code: ")
# Getting the DATA
url = 'http://api.openweathermap.org/data/2.5/forecast?q=%s,%s&APPID=(KEY)' % (
... |
"""
All decisions are based on the number of occupied seats adjacent to a given seat (one of the eight positions immediately up, down, left, right, or diagonal from the seat). The following rules are applied to every seat simultaneously:
If a seat is empty (L) and there are no occupied seats adjacent to it, the se... |
def fizzbuzz():
list = []
for x in range(1,101):
if(x%3==0 and x%5==0):
list.append("FizzBuzz")
elif(x%3 == 0 ):
list.append('Fizz')
elif(x%5 == 0):
list.append("Buzz")
else:
list.append(x)
return list
print(fizzbuzz()) |
def longest_run(L):
"""
Assumes L is a list of integers containing at least 2 elements.
Finds the longest run of numbers in L, where the longest run can
either be monotonically increasing or monotonically decreasing.
In case of a tie for the longest run, choose the longest run
that occurs first.... |
n1 = int(input('Digite um numero: '))
ant = n1 - 1
dep = n1 + 1
print('O nuemro que você digitou é {}, o numero antecessor a ele é {} e por fim o numero depois é {}'.format(n1, ant, dep)) |
n1 = float(input('Digite o tamanho de largura: '))
n2 = float(input('Digite o tamanho de altura: '))
a = (n1*n2)/2
l1 = a / 2
print('Sabendo que a lagura de sua parede é {} e a sua altura {} o espaço em é {}m2 e a quantidade de tinta usada '
'será {}'.format(n1, n2, a, l1)) |
from LinkedListNode import node
l=[1,2,3,4,5,6,7,8,9,10]
head=node(l[0])
for i in range(1,len(l)):
head.appendToLast(node(l[i]))
def kThLast(k):
p1=head
p2=head
for i in range(k):
if p1.next==None:
return None
else:
p1=p1.next
while p1.next!=None:
p2... |
from LinkedListNode import node
l=[3,5,8,5,10,2,1]
head=node(l[0])
for i in range(1,len(l)):
head.appendToLast(node(l[i]))
def part(pivot):
linked1=None
linked2=None
temp=head
while temp!=None:
newNode = node(temp.data)
if temp.data<pivot:
if linked1==None:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-04-01 00:03:12
# @Author : Yong Lee (honkly@163.com)
# @Link : http://www.cnblogs.com/honkly/
# @Version : 1.0
class Car():
"""A simple attempt to represent a car."""
def __init__(self, manufacturer, model, year):
"""Initialize attrib... |
print("第一次打印时读取整个文件:")
with open('learning_python.txt') as file_object:
print(file_object.read())
print("第二次打印时遍历文件对象:")
with open('learning_python.txt') as file_object:
for line in file_object:
print(line.strip())
print("第三次打印时将各行存储在一个列表中, 再在with 代码块外打印它们")
with open('learning_python.txt') as file_object:
words... |
filename = 'guest_book.txt'
while True:
name = input("Please input your name:\n")
print("Hello! " + name)
with open(filename,'a') as file_object:
file_object.write(name + '\n') |
#
numero = int(input("Digite um numero: "))
# vai verificar a condicao
while numero < 100:
# caso a condicao seja verdadeira, o bloco abaixo sera executado
print(f"\t {numero}")
numero = numero + 1
# ao fim do bloco, volta para o inicio e verifica se a condicao ainda esta verdadeira
print("PROGRAMA ENC... |
class SortingRobot:
def __init__(self, l):
"""
SortingRobot takes a list and sorts it.
"""
self._list = l # The list the robot is tasked with sorting
self._item = None # The item the robot is holding
self._position = 0 # The list position the robot... |
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode, col
def count_per_skill(df):
"""
:param df: dataframe with schema: [name: string, technical_skills: array<string>]
:return : dataframe with two columns - 1) skill name, 2) distinct # of people who have that skill
"""
# ... |
"""
Not in use when import
outstanding_balance = float(raw_input("What is your outstanding balance? "))
annual_interest_rate = float(raw_input("What is your annual interest rate? "))
"""
monthly_lower_bound = outstanding_balance / 12.0 # 12 is set because we are looking to pay this off in a year
monthly_upper_bound = ... |
out_file = open("name.txt", "w")
name = input("What is thy name? ")
print(name, file=out_file)
out_file.close()
in_file = open("name.txt", "r")
name = in_file.read().strip()
print("your name is ", name)
in_file.close()
in_file = open("numbers.txt", "r")
line1 = int(in_file.readline())
line2 = int(in_file.readline())
... |
numbers = [3, 1, 4, 1, 5, 9, 2]
print(numbers[0], "\n",
numbers[-1], "\n",
numbers[3], "\n",
numbers[:-1], "\n",
numbers[3:4], "\n",
5 in numbers, "\n",
7 in numbers, "\n",
"3" in numbers, "\n",
numbers + [6, 5, 3])
numbers[0] = "ten"
numbers[-1] = 1
print(numbers[2:])
print(9 in numbers)
print(numbers) |
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixe... |
def mean(mylist):
the_mean = sum(mylist) / len(mylist)
return the_mean
print(mean([1, 4, 5]))
print(type(mean), type(sum))
#Type of > <class 'function'> <class 'builtin_function_or_method'> |
# LinearRegression is a machine learning library for linear regression
from sklearn.linear_model import LinearRegression
# pandas and numpy are used for data manipulation
import pandas as pd
import numpy as np
# matplotlib and seaborn are used for plotting graphs
import matplotlib.pyplot as plt
plt.style.use('seaborn... |
#!/usr/bin/python
#
# Script to fetch indices from user and store it in encrypted form in /etc/user_indices
#
import fileinput
from M2Crypto import *
import sys
import base64
username = raw_input('Enter a username: ')
indices = raw_input('Enter indices (space separated): ')
try:
indices_list = indices.split(" ")
i... |
# Simple Linear Regression
# Importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
# Co-Efficient estimation Function
def estimate_coefficent(x,y):
x_size = np.size(x)
mean_x, mean_y = np.mean(x), np.mean(y)
SS_xy = np.sum(y*x - x_size*mean_y*mean_x)
SS_xx =... |
# Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = 1
b = 2
c = 3
d = a + (b * c)
print(a, b, c, d)
name = input('Введите Ваше имя: ')
name = 'Привет ' + name + '! Меня зовут Альберт!'
print(name)
case =... |
# -*- coding: utf-8 -*-
class Location:
def __init__(self, location=0):
self._location = location
def get(self):
return self._location
def set(self, new_location):
self._location = new_location
def decrease(self, delta=1):
self._location -= delta
def increase(sel... |
# -*- coding: utf-8 -*-
import requests
import keys
import constants
from objects import Location
# This function get the latitude and longitude of an address through Google Geocoding API.
# Return an object with the address, latitude and longitude.
# https://developers.google.com/maps/documentation/geocoding/start
... |
num = float(input("Enter number\n"))
intPart = num - (num % 1)
tmpInt = intPart
tmp = num
while int(tmp) != tmp:
tmp *= 10
tmpInt *= 10
floatPart = int(tmp - tmpInt)
print(floatPart)
def reverse(num):
ret = 0
while num >= 1:
ret *= 10
ret += num % 10
num //= 10
return ret
f... |
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import constants as c
class RegressionHandler:
"""
This class encapsulates the logic for calculating and plotting a linear regression.
"""
@staticmethod
def plot_regression(dataframe, sex=c.Sex.MALE):
"""
... |
def largestPerimeter(nums) -> int:
def is_triangle_valid(nums0, nums1, nums2):
valid = True
if nums0 >= nums1 + nums2:
valid = False
elif nums1 >= nums2 + nums0:
valid = False
elif nums2 >= nums1 + nums0:
valid = False
return valid
num... |
# https://leetcode.com/problems/word-search-ii/
def word_search_2(grid, words):
R = len(grid)
C = len(grid[0])
found_list = []
for word in words:
print(f"finding {word}")
found = ""
i = 0
j = 0
k = 0
while 0 <= i < R and 0 <= j < C and k < len(word):
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 22:22:27 2019
@author: jayada1
Consider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of distinct combinations to reach the given score.
Input:
The first line of input contains an integer T denoting the numbe... |
def insert_char_at_all_positions(char, perm_list):
res = []
for perm in perm_list:
n = len(perm)
for i in range(n + 1):
new_perm = perm[:i] + char + perm[i:]
if new_perm not in res:
res.append(new_perm)
return res
def generate_all_permutations(str1, ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 3 13:04:06 2019
@author: jayada1
"""
"""
Given an MxN matrix, find the number of ways of reaching bottom right element from top left element
only right and down movements allowed.
"""
#Solution 1: Recursion
def numpaths(m,n):
if m==1 or n==1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.