text stringlengths 37 1.41M |
|---|
class Book:
def __init__(self,title,author,price):
self.title = title
self.author = author
self.price = price
def __str__(self):
newLine = "\n"
tip = f"Type: {self.name()}{newLine}"
titl = f"Title: {self.title}{newLine}"
auth = f"Author: {self.auth... |
hosting = dict()
while True:
string = input()
if string == "login":
break
info = string.split(" -> ")
key = info[0]
value = info[1]
if hosting.__contains__(key):
hosting[key] = value
else :
hosting.__setitem__(key,value)
unsuccesfulLogins = 0
while True:
st... |
arr = input().split(" ")
pozitiveArr = []
for i in range(len(arr)):
currNum = int(arr[i])
if currNum > 0:
pozitiveArr.append(currNum)
if len(pozitiveArr) < 1:
print("empty")
exit()
print(" ".join(str(x) for x in reversed(pozitiveArr))) |
import math as m
arr = input().split(" ")
for i in range(len(arr)):
arr[i] = int(arr[i])
arr.sort()
for num in reversed(arr):
if num < 1:
continue
if m.sqrt(num) == int(m.sqrt(num)):
print(num, end=" ") |
def compare(left,right):
if left > right:
return left
else:
return right
varType = input()
left = None
right = None
if varType == "int":
left = int(input())
right = int(input())
elif varType == "float" :
left = float(input())
right = float(input())
else :
left = input()
... |
import re
class Human:
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
@property
def firstName(self):
return self._firstName
@firstName.setter
def firstName(self,value):
if value == value.capitalize():
if len(va... |
'''
is_palindrome('testing') # False
is_palindrome('tacocat') # True
is_palindrome('hannah') # True
is_palindrome('robert') # False
is_palindrome('amanaplanacanalpanama') # True
'''
def is_palindrome(words):
words = words.lower().replace(" ","")
reverse = words[::-1]
if reverse == words:
return True
return False... |
# used to break out of loops
while True:
command = input("Type 'exit' to exit: ")
if (command == 'exit'):
break
#redundant example
for x in range(1,101):
print(x)
if x == 3:
break
#repeater example but end after 4 times
times = int(input("How many times did you take the dog for a walk today? "))
for t in ran... |
def list_manipulation(lst,command,loc,value=None):
if command == "remove" and value == None:
if loc == "end":
return lst.pop()
return lst.pop(0)
if command == "add":
if loc == "beginning":
lst.insert(0,value)
return lst
else:
lst.append(valu... |
class Card:
allowed_suit = ("Hearts", "Diamonds", "Clubs", "Spades")
allowed_value = ("A","2","3","4","5","6","7","8","9","10","J","Q","K")
def __init__(self,value,suit):
if suit not in Card.allowed_suit:
raise ValueError (f"{suit} is not an acceptable suit.")
self.suit = suit
if value not in Card.allowed_v... |
#"model" data from spotify playlist into a dictionary
playlist = {
"title": "80s Rock Anthems", "creator": "Spotify",
"song": [
{"title":"You Shook Me All Night Long", "artist":["AC/DC"], "duration":3.5},
{"title":"You Spin Me Round (Like a Record)", "artist":["Dead or Alive"], "duration":3.4},
{"title":"Everbody ... |
# builds 3 pyramids (nested for loop)
for x in range(3):
for n in range(1,11):
print("/\\" * n)
for n in range(1,11):
print("/\\" * n)
# with a while loop
times = 1
while times <11:
print("/\\" * times)
times += 1
#without string multiplication - ugly solution
for num in range(1,11):
count = 1
steps = ""
w... |
'''
calculate(make_float=False, operation='add', message='You just added', first=2, second=4) # "You just added 6"
calculate(make_float=True, operation='divide', first=3.5, second=5) # "The result is 0.7"
'''
def calculate(operation,first,second,make_float=True,message=None):
if operation == "add":
c = first + seco... |
def extremes(lst):
return (min(lst),max(lst))
print(extremes([1,4,7]))
print(extremes("alcatraz"))
# print(max([1,4,7]))
# print(max("alcatraz"))
|
d = dict(a=1, b=2,c=3)
print(d)
# d.clear()
# d = {}
#.copy makes a copy
c = d.copy()
print(c==d) #True
print(c is d) #False
#{}.fromkeys is used to create new dictionaies with the same values
new_user = {}.fromkeys(["name","email","bio","score"], "unknown")
print(new_user) #{'name': 'unknown', 'email': 'unknown', '... |
# want to make an def __init__(self,args): at the beginning of every class, because it will always be called
class User():
def __init__(self,first,last,age): #generally the first is called self as a rule of thumb, then add in other stuff
self.first = first
self.last = last
self.age = age
# 2 instances of User
... |
### BE CAREFUL WHEN USING WHILE LOOPS, THEY CAN CONTINUE FOREVER
# msg = input("What's the best car? ")
# while msg != "jeep":
# print("Nah")
# msg = input("What's the best car? ")
# print("Yup")
# will go on forever until the user inputs jeep
#BAD, USE CTRL+C to break the loop in powershell
# num = 1
# while num <... |
def single_letter_count(words,letter):
words = words.lower()
letter = letter.lower()
count = 0
for i in words:
if letter == i:
count +=1
return count
print(single_letter_count("It's a tuesday Ian", "A"))
##Another solution
def single_letter_count(string,letter):
return stri... |
#define function to flip a coin
from random import random
def flip_coin():
#generate float from 0-1
r = random()
if r > 0.5:
return "Heads"
else:
return "Tails"
print(flip_coin())
#another way to write it
def flip_coin():
if random() > 0.5:
return "Heads"
else:
return "Tails"
#second function overwrites... |
#!/usr/bin/env python3
import random as rand
import pdb
import time
# Maze tiles.
empty_tile = '*'
wall_tile = '█'
class Pos:
def __init__(self, pos: (int,int)):
self.x = pos[0]
self.y = pos[1]
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __eq__(se... |
# ACC VR & AR Diploma
# Gerges Romany
import time
num=1
x=1
while (num<=12):
print "<--------- ",num," ----------->"
while (x<=12):
print num , "*" , x , "=" , (num*x)
x=x+1
num=num+1
x=1
print "\n"
time.sleep(500)
|
for x in range(1000):
for y in range(1000):
for z in range(1000):
if x + y + z == 1000 and x < y < z and x**2 + y**2 == z**2:
print x,y,z
print x*y*z
|
#falsifieds
#Fake News classification project
#Michael Fedell - Robert Monaco
import csv
import sklearn
import numpy as np
def read_data(path):
#Initialize empty dataset
data = []
#Open csv specified by path
with open(path, 'r') as csvf:
#Read csv file, comma delimeted
read_file = cs... |
"""
Example to plot the beam radius over a range of distances
"""
from poptics.ray import GaussianBeam
import numpy as np
from poptics.wavelength import HeNeRed, WavelengthColour
import matplotlib.pyplot as plt
def main():
waist = 0.1 # Initial waist
wavelength = HeNeRed ... |
"""
Make plots of the Radial(n,m,r) function
"""
from poptics.zernike import radial
import matplotlib.pyplot as plt
from poptics.tio import getInt
import numpy as np
def main():
# Get mex value
n = getInt("n value",4,0)
rData = np.linspace(0.0,1.0,100) # rdata is rage 0 > 1.0
# ... |
"""
Simple program to set up a default spectometer with specified material
and calcualte minimum deviation angle from terminal prompts.
"""
from poptics.spectrometer import PrismSpectrometer
from poptics.tio import getString,getFloat,tprint
import math
def main():
# Get name of index and make a ... |
#!/usr/bin/env python3
"""
Reduce an ingredient set by common strings
"""
import argparse
from collections import deque
import csv
from pprint import pprint
import pandas as pd
def get_ingredients(file_handle: str, key='ingredient') -> list:
"""Loads ingredients from csv file
`key` specifies the key to re... |
from utilities import input_integer, InvalidChoice
from pharmacy_system import *
from clinic_system import *
Disease.read_disease_data()
Doctor.read_doctors_data()
pharmacy_warning = 'WARNING! You cannot do this until you have a pharmacy.'
print("---------------------------------------------------\n"
"HELLO, WE... |
# Implementation of a simple propositional calculus proofer.
def parse_propositon(input_proposition):
clauses = input_proposition.split(" and ")
return clauses
def parse_clause(input_clause):
input_clause = input_clause.replace("(", "")
input_clause = input_clause.replace(")", "")
literals = inpu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def dfs(target, dlist, _index=[0]):
if [] == dlist:
return False
elif target == dlist[0]:
return tuple(_index)
elif type(dlist[0]) == list:
return (dfs(target, dlist[0], _index + [0])
or dfs(target, dlist[1:], _index... |
"""
Created by: Ricardo Arias
Date of creation: April 5, 2020
Last modification: April 30, 2020
"""
def read_data():
"""
Reads the data from the file AU_INV_START.txt and store it in start_dict
"""
start_file = open('./data/AU_INV_START.txt', 'r') # Variable that reads the file
sta... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 00:41:48 2018
@author: denny
"""
import math
class Rect(object):
__slots__ = ("x","y","z","xx","yy","zz", "swapped_x", "swapped_y","swapped_z") # bot-left, top-right
def __init__(self, minx,miny,minz,maxx,maxy,maxz):
# initial... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
import sys
from trie import Trie
t = Trie()
def command_parse(arg):
global t
if len(arg)==1:
ins=arg[0]
if len(arg)==2:
(ins,var) = arg
if ins=='i':
t.add_word(var)
elif ins=='r':
t.remove(var)
elif ins=='f':
... |
from simulator.action_choices import *
class Player(object):
def __init__(self,player_name,agent, player_class):
"""
An object representing a unique player in the game.
"""
self.player_name = player_name
self.agent=agent # the agent assigned to this player.
self.... |
name = input("Your name, please? ")
print(f"Hey, {name}") |
"""
control.py
assignment #2
utilizing if statements check if a user provided name signed the Declaration of Independence
"""
import sys
import urllib.request
url = "http://www.ushistory.org/declaration/document/index.html"
name = input("What is the name you are searching for? ")
try:
site = urllib.request.urlo... |
"""
pokemon.py
assignment #4
inputs all the lines of a text file and sorts them
lists all 151 first generation Pokémon
can be sorted either in alphabetical or numerical order
in ascending or descending order
or search for the pokédex number of a particular pokémon
kanto.txt used has been uploaded to this repository
"""... |
# def showReversed(text):
# textReversed = text[::-1]
# return textReversed
#
#
# print(showReversed("dollar"))
def showReversed(text):
textReversed = list(text)
textReversed.reverse()
return textReversed
print(showReversed("dollar"))
import random
num = random.randint(1,10)
while True:
g... |
from turtle import *
setup
colormode(255)
pensize(20)
pencolor(255,255,255)
speed(1000)
def changedraw():
penr=254
for i in range(100):
circle(100,1)
penr-=1
pencolor((penr,penr-1,penr-2))
for u in range(100):
circle(-100,1)
penr-=1
pencolor((pe... |
#5.2
def isOdd(n):
if num%2==0:
return False
else:
return True
try:
num=eval(input("请输入一个整数:"))
if type(num)==type(1):
print("这是一个奇数.") if isOdd(num) == True else print("这不是一个奇数.")
else:
print("您输入的不是整数")
except:
print("您输入的不是整数")
|
liste = ["1", "2", "5a", "10b", "abc", "10", "50"]
for x in liste:
try:
result = int(x)
print(result)
except ValueError:
continue #hata alan değerler es geçilir
while True:
sayi = input("sayı: ")
if sayi == "q":
break
try:
result = float(sayi)
... |
## Toplama Operatörü (+)
# Who is İt
customerName = "Yücel"
customerLastName = "Toluyağ"
customerGender = True # man
customerAge = 2020 - 1962
customerAdress = "Faruk Eczanesi"
CustomerIdentify = "123465456"
customerFull = customerName + ' ' + customerLastName
## Order
customerOrder = 110
customerOrder2 = 1100.5
cus... |
from Blackjack import Blackjack
class Player:
def __init__(self, money=1000):
self.cardlist = []
self.money = money
self.pot = 0
class BlackjackPlayer(Player):
def __init__(self):
super(BlackjackPlayer, self).__init__()
self.sum = 0
self.blackjack ... |
#!/usr/bin/env python3
# open the file
dash = "=" * 70
onepiece_character_list = []
with open ("./Onepiece_data/onepice_fruits.txt") as onepiece_devil_fruit_file:
for each_character in onepiece_devil_fruit_file:
onepiece_character_list.append(each_character.strip('\n'))
# get total number of characters
de... |
#!/usr/bin/env python3
# allow the user to pass in both start_date and end_date
# as input!
# use that input as query param for the API call
# Basic - Return the following info:
# how many asteroids are being returned?
# Advanced - Return the following info:
# how many asteroids are potentially hazardous?
# Danger ... |
#!/usr/bin/env python3
import requests
import pprint
AOIF_CHAR = "https://www.anapioficeandfire.com/api/characters/"
def main():
## Ask user for input
got_charToLookup = input("Pick a number between 1 and 1000 to return info on a GoT character! " )
## Send HTTPS GET to the API of ICE and Fire character... |
# -*- coding: utf-8 -*- #Para evitar erros com acentuação no python
# CONEXÃO COM O SERVER QUE COMUNICA COM ARDUINO #
import socket #Biblioteca para conexao por sockets
import os #Biblioteca que permitem que você interferencia com o SO subjacente em que o Python está sendo executado para o uso de funções core... |
"""
# Kareen Sade id: 304924327
# Curse: Python
HW 10
"""
#creating a function that will get a parameter (positive whole number) and
# reaturning a number that his order of numbers is reverse to the parameter.
def reverse(n):
#truning the parameter into a string
st=str(n)
#reverse the order of notes insi... |
import random
from WordsForGame import WordsForGame
import string
def getValidWord(WordsForGame):
word = random.choice(WordsForGame) # randomly chooses words from list
while '-' in word or ' ' in word:
word = random.choice(WordsForGame)
return word.upper()
def hangman():
word = getValidWor... |
'''
argumet function
*args
**keyword
'''
'''
######default argument###########
def default_argument(number,name="Hey"):
print(number+' --------- ' +name)
def input_number():
number=input('enter the number')
default_argument(number)
default_argument(number,"hlo")
input_number()
'''
'''
########## *args argument#... |
###########control flow in python##########
#### if condition########
####if condition:###########
check=1>2
if check:
print("gaurav")
else:
print("saurav")
let="car"
if let=="car":
print("Honda car")
else:
print("no car")
let="bank1"
if let=="bank":
print("lone pass")
elif let=="bank1":
print("lone finishe... |
x = 10
y = 10
if x<y:
print("X: " + x + ", is less than Y: " + y + ".")
elif x>y:
print("X: " + x + ", is greater than Y: " + y + ".")
else:
print("X: " + x + ", is equals to Y: " + y + ".")
#Assignment: create a school grading system such that
'''
MARKS GRADE
A 80-100
A- 75-79
B+ 70-74
B 65-69
... |
#!/usr/bin/python2.7
n = int(raw_input())
while n != 42:
print n
n = int(raw_input())
|
"""
Uses stockDBhandler for retrieving the database values.
"""
from stockDBhandler import Database_Management
class Console_Viewer:
def __init__(self):
self.db = Database_Management()
def run_menu(self):
self.print_welcome_message()
print()
self.menu_text = {1... |
# Jack Trimboli
# CS 100 2021S Section 108
# HW 11, April 23, 2021
class Dog:
species = "Canis familiaris"
def __init__(self, name, breed):
self.name = name
self.breed = breed
self.tricks = []
def teach(self, trick):
self.tricks.append(trick)
print(self.name + " now... |
"""
Jack Trimboli
CS 100 2021S Section 108
HW 06, February 19th, 2021
"""
# 1a
def hasFinalLetter(strList, letters):
res = []
for x in strList:
if x[-1] in letters:
res.append(x)
return res
# 1b - three testcases
list1 = ["hello", "world", "python", "is", "cool"]
letters1 = "ol"
list2... |
player_pos = list(str(input()))
dangerous = "NO"
if player_pos.count("1") >= 7 or player_pos.count("0") >= 7:
player_pos = [int(char) for char in player_pos]
for idx in range(len(player_pos)):
count = float('inf')
count = sum(player_pos[idx:idx+7])
if count == 7:
dangerous =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
import collections
def hash_df(in_df_column):
"""
Creates a dictionary of de-duplicated column values as keys, whose value is a list of
all of the row indices that the column value exists. Provides a O(1) lookup complexity
for findi... |
from graphs.pathfinding import bfs_dist
class Graph:
'''
General graph class for pathfinding, etc
'''
def __init__(self):
self.nodes = []
self.edges = {}
def __str__(self):
rep = [f'{key}:{value}' for (key,value) in self.edges.items()]
return '\n'.join(rep)
de... |
from tkinter import *
import twitter_account
import Utils
root = Tk()
label_words = Label(root, text = "Words")
label_place = Label(root, text = "Place")
label_lat = Label(root, text = "Latitude")
label_long = Label(root, text = "Longitude")
entry_words = Entry(root)
entry_lat = Entry(root)
entry_long = Entry(root)
... |
def compute_distances_from_start(vertices):
distance_changes = True
while distance_changes:
distance_changes = False
for vertex in range(len(vertices)):
# print(vertices[vertex])
distance_to_start_init = vertices[vertex][1]
# print("Initial distance_to_start =... |
def knot_hash(input, repeat=1):
current, skip_size = 0, 0
lst = list(range(n))
for _ in range(repeat):
for length in input:
length = int(length)
new_lst = lst[:] + lst[:]
re = list(reversed(new_lst[current: (current + length)]))
k = current
... |
import unittest
def convert(input):
output = ""
x = input // 10
i = input % 10
l = x // 5
x = x % 5
output = l * "L" + x * "X" + i * "I"
return output
class RomanConverterTest(unittest.TestCase):
# def test_convert2k18(self):
# self.assertEqual('MMXVIII', convert(2018), "T... |
"""
Make jumbled names.
Take some names as input.
Then interchange their surnames to make fun.
"""
import random
if __name__ == '__main__':
names = input("Enter names seperated by *\n")
name_list = names.split("*")
name_split = [items.split(" ") for items in name_list]
f_names = [name_split[items][0] ... |
#!/usr/bin/python
import random
# Varaibles
colors = ['Coeur', 'Pique', 'Trefle', 'Carreau']
cards = ['1', '2', '3', '4', '5', '6', '7', '8', '10', 'V', 'D', 'R']
listOfCards = []
deckSize = 52
deck = {}
# init lists
for c in colors:
for ca in cards:
listOfCards.append("%s%s" % (ca, c))
print "List des ca... |
def first_perfect_square(numbers):
f_p_s = -1
for i in range(len(numbers)):
if numbers[i] >= 0 :
if ((numbers[i] ** 0.5)%1 == 0) :
f_p_s = i
break
return f_p_s
#####################################################################
def num_perf... |
bicycles = [ 'trek', 'cannondale', 'redline', 'specialiezd' ]
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA " +... |
"""
Расчет индекса массы тела
"""
# Ввести значения через пробел
w,r = map(float, input('Введите Вес(кг) и Рост(см) через пробел: ').split())
#w = int(input()) # Вес
#r = float(input()) # Рост
imt = w / (r / 100) ** 2 # Индекс массы тела
print(int(imt))
if imt < 18.5:
print('Underweight')
if 18.... |
class Charger:
"""
Package class represents a location that a Robot would return to when it is not doing a task
Attributes:
location: A Point object which is the Charger's location in the Warehouse
"""
def __init__(self, location):
"""
Inits Charger with a Point... |
class Point:
"""
Point class is used to establish coordinate locations throughout the warehouse
These points allow us to have an understanding how objects are moving around during the simulation
Attributes:
x: Integer representing x coordinate
y: Integer representing y coordi... |
import simpy
"""
TUTORIAL 1
class Car(object):
def __init__(self, env):
self.env = env
# Start the run process everytime an instance is created
self.action = env.process(self.run())
def run(self):
while True:
print('Start parking and charging at %d' % se... |
def funcname():
print("Please enter a number")
x = input()
print("Please enter a number")
y = input()
print(x, y)
funcname()
|
#! /usr/bin/env python
import re
# Day 5: Doesn't He Have Intern-Elves For This?
# http://adventofcode.com/day/5
with open('input/Day05.txt') as f:
data = f.readlines()
# Part 1
bad_duos = re.compile('(ab|cd|pq|xy)', re.I)
def vowel_count(string):
return len(filter(lambda x: x in 'a e i o u'.split(), strin... |
class Game():
boardValues = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
def board(self):
count = 0
for i in range(3):
print("|",end = " ")
for j in range(3):
print(self.boardValues[i+j+count], "|",end = " "),
count +=2
print("\n+... |
a = list(map(int, input().split()))
for i in range(1, len(a)):
if a[i] > a[i-1]:
print(a[i])
#The solution of the problem (Решение задачи): https://pythontutor.ru/lessons/lists/problems/increasing_neighbours/
|
old_list = list(map(int, input().split()))
sort_list = []
def selection_sort(old_list):
for i in range(len(old_list)):
max1 = max(old_list)
sort_list.append(max1)
old_list.remove(max1)
return sort_list
print(selection_sort(old_list))
#Сортирует элементы спика по убыванию. На... |
import sqlite3
db = sqlite3.connect("contacts.sqlite")
db.execute("CREATE TABLE contacts (name TEXT, phone INTEGER, email TEXT)")
db.execute("INSERT INTO contacts(name, phone, email) VALUES ('Tim', 43354252, 'email@email.pl')")
db.execute("INSERT INTO contacts VALUES ('Ida', 5435, 'myemail@gmail.pl')")
cursor = db.c... |
#!usr/bin/python
a=-1
if (type(a)==int and a>0):
if a%2==0:
print "Even"
else:
print "Odd"
else:
print "Invalid Input"
|
#!usr/bin/python
a=int(input("Enter how many times to print :"))
for i in xrange(a):
print "Hello"
|
input = [7, 3, 5, 2, 1, 4, 8, 6]
def partition(arr, begin, end):
print (arr, begin, end)
if (begin < end):
# select pivot to be final element
pivot = arr[end]
# used to count swaps made for values less than pivot
i = begin - 1
print(arr[begin:end+1])
for index, v... |
'''
description:draw quadrangle on image. firstly, read coordinate information of quadrangle from text file. then open the corresponding
image and draw the quadrangle on image.
input:
textdir:the directory which contains sevaral text file,each txt file contain sevaral quadrangle information of one image
imgdir:the dir... |
"""Deadpool core"""
from textblob import TextBlob
from test_deadpool import statements
def get_nouns(statement):
"""Get noun phrases for a statement"""
return TextBlob(statement).words
def analyze(df, statement):
"""Main function"""
nouns = get_nouns(statement)
# check if any of the nouns are in... |
n = int(input("Введите число - "))
n1 = n
n2 = int(str(n) * 2)
n3 = int(str(n) * 3)
total = (n1 + n2 + n3)
print("Cумма чисел n + nn + nnn = ", total) |
#!/usr/bin/env python3 -tt
import math
digits = "123456789"
def is_pandigital(string):
return "".join(sorted(string)) == digits
def is_pandigital_product(x):
for i in range(1, math.ceil(math.sqrt(x)) + 1):
if x % i == 0:
equation_as_string = str(i) + str(x//i) + str(x)
if is_... |
#!/usr/bin/env python3 -tt
import math
one_hundred_f = math.factorial(100)
string = str(one_hundred_f)
print(sum(int(digit) for digit in string))
|
#!/usr/bin/env python3 -tt
import itertools
lower = 'abcdefghijklmnopqrstuvwxyz'*3
passwords = ["".join(x) for x in set(itertools.permutations(lower, 3))]
with open('/Users/jamesshapiro/Desktop/p059_cipher.txt', 'r') as f:
line = f.readlines()[0].strip()
chars = line.split(",")
total = 0
plaintexts = []
max_spa... |
#!/usr/bin/env python3 -tt
import itertools
def find_a_pythagorean_triplet_with_perimeter(n):
leg_lengths = list(range(1, n+1))
combos = itertools.combinations_with_replacement(leg_lengths, 2)
for combo in combos:
leg_1 = combo[0]
leg_2 = combo[1]
if leg_1 + leg_2 > n - 1:
... |
n=int(input())
n1,n2,n3=map(int,input().split())
largest=(n1 if (n1 > n2 and n1 > n3)
else(n2 if(n2 > n1 and n2 > n3)else n3))
print(largest)
|
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import operator
def regex_or(*items):
return '(?:' + '|'.join(items) + ')'
# This file contains mapping functions
# this function takes as arguemnt a token and
# and determines whather the argument is
# and sad or happhy emoticons by analyzing the
# ... |
# The parent_directory function returns the name of the directory that's located just above the current working directory. Remember that '..' is a relative path alias that means "go up to the parent directory". Fill in the gaps to complete this function
import os
def parent_directory():
# Create relative path for ... |
import matplotlib.pyplot as plt
import math
import numpy as np
theta = np.linspace(0, 2*math.pi, num=100)
r1 = [6 * math.sin(a) + 8 * math.cos(a) for a in theta]
r2 = [9 * math.sin(a) + 12 * math.cos(a) for a in theta]
r3 = [3 * math.sin(a) + 4 * math.cos(a) for a in theta]
plt.plot(theta, r1, theta, r2, t... |
def hp_calc(hp_stats):
max_hp = int(hp_stats['max_hp'])
cur_hp = int(hp_stats['cur_hp'])
comb_status = True
while comb_status:
action = hp_menu()
if action == '1':
cur_hp = hp_gain(cur_hp, max_hp)
elif action == '2':
cur_hp = hp_loss(cur_hp)
elif action == '3':
print('Final HP is: ', cur_h... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 7 09:47:06 2019
@author: Deepika
"""
# Initialization of variables
fname = lname = wel_msg = gen = mpname = wa_msg=''
#Initializing welcome message
wel_msg = "Good Morning !!! Welcome to the Varun Academy \n"
print(wel_msg)
# inputing user information
fname = input("... |
# http://api.mongodb.org/python/current/tutorial.html
import pymongo
# run this in the console to start mongodb on port 27017
# mongod --dbpath /Users/bencaneba/desktop/nodejs/expressmongo/node_modules/express/data
# create a MongoClient to the running mongod instance and connect to the port that mongo is running in... |
from collections import Counter
def find_it (seq):
d = Counter(seq)
for key, v in d.items():
if v%2 != 0:
return (key)
return Counter(seq)
print (find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])) |
#conding :utf-8
#匿名函数,没有名字,比较方便
a=(lambda x,y,z:x+y+z)(1,2,3)
print(a)
#匿名函数遍历1-10所有数
squares1 = list(map(lambda x: x, range(1,11)))
print(squares1)
#匿名函数遍历1-10的所有数,每个数分别乘以3
squares2 = list(map(lambda x: x +3, range(1,11)))
print(squares2)
#for循环遍历
for i in range(1,10):
print(i+5) |
string2 = 'aabcde'
def unique_chars(st):
if len(st) > 256:
return False
char_set = [False] * 128
for i in range(0, len(st)):
val = ord(st[i])
if char_set[val]:
return False
char_set[val] = True
return True
string = 'abcd'
string2 = 'aabcd'
print(unique_chars(... |
# Find second lowest
# markSheet = []
# scoreSheet = []
#
# for i in range(0, int(input())):
# name = str(input())
# marks = float(input())
# markSheet.append([name,marks]) # appending into Nested List
# scoreSheet.append(marks) # appending into normal list
#
# secondLowest = sorted(set(scoreSheet))[1] # using sets... |
import math
import turtle as tl
tl.speed(0)
def circle(R, param=False):
N = int(2 * math.pi * R / 3)
if param:
for _ in range(N):
tl.forward(3)
tl.left(360 / N)
else:
for _ in range(N):
tl.forward(3)
tl.right(360 / N)
for _ in range(3):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.