text stringlengths 37 1.41M |
|---|
class Solution:
def is_valid(self, coordinates):
return 0 <= coordinates[0] < 8 and 0 <= coordinates[1] < 8
def queensAttacktheKing(self, queens, king):
attacking_queens = {str(queen[0]) + str(queen[1]): False for queen in queens}
directions = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (... |
import unittest
def string_compression(s):
l = list()
temp_char = ''
count = 0
for char in s:
if char == temp_char:
count += 1
else:
if temp_char != '':
l.append(temp_char + str(count))
temp_char = char
count = 1
l.ap... |
from math import sqrt
from itertools import count, islice
T = int(input())
def check_if_prime(n):
if n < 2:
print('Not prime')
return False
for number in islice(count(2), int(sqrt(n) - 1)):
if n % number == 0:
print('Not prime')
return False
print('Prime'... |
class Solution:
def wordPattern(self, pattern, s):
d_symb, d_word, words = {}, {}, s.split()
if len(words) != len(pattern): return False
for symb, word in zip(pattern, words):
if symb not in d_symb:
if word in d_word: return False
else:
... |
import re
regex = re.compile("^[a-z\.]+@gmail.com$")
accounts = dict()
N = int(input().strip())
for _ in range(N):
firstName, email = input().strip().split(' ')
if regex.match(email):
accounts[email] = firstName
sorted_names = sorted(accounts.values())
print(*sorted_names, sep="\n")
|
x, y, z = "Orange", "Banana", "Cherry"
print(x, y, z)
x = y = z = "Orange"
print(x, y, z)
x = "Sven"
y = "Kohn"
print(x + " " + y)
print(f"{x} {y}")
|
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
... |
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist)
print(thislist[1])
# will start at index 2 (included) and end at index 5 (not included)
print(thislist[2:5])
# returns items from beginning to "orange"
print(thislist[:4])
# returns items from "cherry" to the end of list
pr... |
#!/usr/bin/env python3
"""
----------------------------------------------------------------------------------------------------------------
Classes - Subclassing
- Creating a subclass
- Overwriting class methods
----------------------------------------------------------------------------------------------------------... |
#Write a recursive Python function, given a non-negative integer N, to calculate and return the sum of its digits.
#Hint: Mod (%) by 10 gives you the rightmost digit (126 % 10 is 6), while doing integer division by 10 removes the rightmost digit (126 // 10 is 12).
#This function has to be recursive; you may not use loo... |
#!/usr/bin/python
import turtle
pen = turtle.Turtle()
pen.up()
pen.backward(100)
pen.down()
def flake_side(angle, length):
pen.left(angle)
pen.forward(length)
if length > 1:
flake_point(angle, length / 3)
else:
pen.forward(length)
pen.forward(length)
pen.right(angle)
def flake_point(angle, leng... |
import sys
import math
from signaturefunctions import *
from printing_to_files import *
# This is just part of documentation:
# A signature is a tuple of strings (each an affix).
# Signatures is a map: its keys are signatures. Its values are *sets* of stems.
# StemToWord is a map; its keys are stems. Its value... |
import wordfreq
from collections import Counter
def main():
letters = Counter()
_2gram = Counter()
_3gram = Counter()
for word, freq in wordfreq.get_frequency_dict('en', wordlist='best').items():
sofar = '…' # we're including space at the beginning of the word
for letter in word.uppe... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 9 23:56:23 2017
Solving mazes using Python: Simple recursivity and A* search
We use a nested list of integers to represent the maze.
Diagonal movement not allowed
The values are the following:
0: empty cell
1: unreachable cell: e.g. wall
2: ending cell
3: visited cell
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 17 21:58:53 2017
@author: supperxxxs
"""
import numpy as np
import math
x= 'asgrsd'
y= 'rsd'
n=4
def isunique(x):
status=[0 for i in range(2**8)]
for i in range(len(x)):
if status[ord(x[i])] == 0:
status[ord(x[i])] = 1... |
import os
import sys
#A function that clears the screen
def clear_screen():
#Use the "cls" command on Windows and the "clear" command on other systems.
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
#Prints the word that the user is guessing with underscores for unknown letters.
def print_word(w... |
#!/usr/bin/env python
# His Name Is Willard Game
# Author: Dave Russell (drussell)
import random
import smithjokes
possibleValues = ['Will Smith', 'Willard Smith', 'Will', 'Willard']
wsmith = random.choice(possibleValues)
actor = random.choice(possibleValues)
if (wsmith == actor):
smithjokes.insertRandomJoke()
e... |
import random as r
sayi = r.randint(1,100)
print(" Texmin oyunu ")
print("Reqemi 0-100 arasi secin")
while True :
print("================")
tahmin = int(input("Reqemi texmin edin"))
if tahmin == sayi :
print("***************")
for i in range(10):
print("Duzgun texmin etdiniz"... |
import gym
import numpy as np
import keras
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten
def main():
# generate data
f_data, l_data = generate_data(10, 10, 0)
# build model and train it
model = getModel()
model.fit(f_data, l_data, epochs=2, verbose=1)
# play games wi... |
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
# generate randomized data set
data = make_blobs(n_samples=200, n_features=2, centers=4, cluster_std=1.2, random_state=101)
# build model and fit it
model = KMeans(n_clusters = 4)
model.fit... |
#!/usr/bin/env python
"""hungry_birds.py - example of concurrent multi-thread application"""
__copyright__ = "Copyright (C) 2015 Andrea Sindoni, Paolo Rovelli"
__author__ = "Andrea Sindoni, Paolo Rovelli"
__email__ = "paolorovelli@yahoo.it"
import threading
import time
import random
NUM_BIRDS = 7
NUM_WORMS = 13
de... |
DEFAULT_INPUT = 'day9.txt'
def day_9(loc=DEFAULT_INPUT):
with open(loc) as f:
data = f.readline()
i = 0
group_score = 0
score = 0
in_garbage = False
garbage_size = 0
while i < len(data):
char = data[i]
if in_garbage:
if char == '!':
i += 1... |
# -*- coding: UTF-8 -*-
'''
A_____A
/ = . =\ < Developed by CKB >
/ w \
current version: 1.3
update log:
ver 1.0 - initial release
ver 1.1 - fix weird acceleration
ver 1.2 - fix "ball stuck in wall" problem
ver 1.3 - add more balls, with collision
'''
from visual import *
########impor... |
import math
def main():
print('Hello world!')
print('=====================')
print('This is me.')
print('You\'re looking for.')
print('I can see it in your eyes.')
print('I can see it in your smile.')
print('You\'re all i ever wanted.')
print('And my arms are open wide.')
price=12.... |
x = 0
y = 0
total_population = 25520468
main_data = ((6, 5663322, 39.92077, 32.85411), (34, 15462452, 41.00527, 28.97696 ), (35, 4394694, 38.41885, 27.12872))
for i in range(3):
x += (main_data[i][1] * main_data[i][2] / total_population)
print ("Latitude:", x)
#for loop above, multiplies population and... |
#!/usr/bin/env python
#
#
# Here we can implement a basic set of classes to handle creating
# recommendations from a given data set
from similaritymeasures import Similarity
import operator
class Recommender():
""" What kind of recommender am I? The existential question remains. """
def __init__(self):
... |
squares = [] # Initialization
for value in range(1, 11):
square = value**2 # 1 to 10 Squares them and, puts them in the Variable square
squares.append(square) # appends values of square into the list squares.
print(squares)
# Output
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
|
from random import randint
import os, sys
# Functions
def result(points, AIpoints, Wins, Losses):
if points > AIpoints:
print(f"You win you had {points} points and computer had {AIpoints}")
Wins += 1
elif AIpoints > points:
print(f"You lose you had {points} points and computer had {AIp... |
import itertools
import networkx as nx
import numpy as np
class TaskGraph(object):
"""A directed graph defining dependencies between tasks
In the MTLabelModel, the TaskGraph is used to define a feasible subset of
all t-dimensional label vectors Y = [Y_1,...,Y_t]; for example, in a
mutually exclusive... |
def area_circulo(radio=5):
# area = PI * radio ** 2
return 3.1416 * (radio ** 2)
def main():
radio = int(input("Introduce el radio del circulo\n"))
print(area_circulo(radio))
if __name__ == "__main__":
main()
|
n = int(input("Enter no. of lines - "))
for var in range(n):
if var < n//2 :
for x in range((n//2+1)-var) :
print(" ",end='')
for y in range(var):
print("*",end='')
for y in range(var):
print("*",end='')
elif var == n//2:
continue
... |
import re
# Receives a word, that might contain a delimiter (for example '&'), which comes after a letter that is optional.
# Returns a list of all the possible ways to write the word, with or without each delimiter.
# For example: for input 'main', the uotput should be ['main', 'man'].
import math
## My versi... |
# File: pos_tagging.py
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# John Longley, November 2012
# Revised November 2013 and November 2014 with help from Nikolay Bogoychev
# Revised November 2015 by Toms Bergmanis
# PART B: POS tagging
from statements import *... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 5 20:38:39 2021
@author: Bruna Aparecida
"""
'''
-------------------------------------------****** DESAFIO ******----------------------------------------------------
Criar a classe "Carro" com no mínimo três atributos e três métodos
-----------------------... |
#!/usr/bin/env python3
"""Report if the given word is a palindrome"""
import sys
import os
def main():
"""main"""
args = sys.argv[1:]
if len(args) != 1:
print('Usage: {} STR'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
word = args[0]
rev = ''.join(reversed(word))
pri... |
#!/usr/local/bin/python3
# coding: utf-8
"""
Title: py_house_treasure.py
Author(s): Jonathan A. Gibson
Description:
Goals:
1. Be able to play multiple different house maps. Store all in "maps" directory with set CSV info to import.
2. Let user choose the house map at the command line, or choose to play a random ma... |
#!/usr/bin/python2.7
class Tree:
def __init__(self, data):
self.value = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
def get(self):
ret = self.children
ret = filter(lambda s: not s.children, ret)
for r in ret:
print r.value
def show(self, s... |
import sqlite3
connection = sqlite3.connect("pets.db")
cursor = connection.cursor()
# cursor.execute("select kind, sound from sounds")
# row = cursor.fetchone()
# (kind, sound) = row
# print (kind, sound)
#for row in cursor.execute("select kind, sound from sounds"):
# print (row)
#cursor.execute("select kind, sou... |
soma = 0
for i in range(3):
nome = input()
distancia = int(input())
soma = soma + distancia
media = float(soma/3)
print("%.1f" % media) |
#got tired of manually recalculating nothing fancy here
#KH 2016
def app_header():
print ('-------------------------------------------------')
print ('---------- Tank Weight Calculator----------------')
print ('-------------------------------------------------')
return ()
def tank_math(thi... |
import random
a = [5,6,7,8,random.randint(0,20)]
b = []
for x in a:
print(x)
b.append(x*2)
print(a)
print(b)
#total = 0
#for x in range(0, len(a)):
# total = total + a[x]
#print("Sum of all numbers in given list:", total)
#BEGINNING OF PRIME.PY
#work on this when you are done with other work
#
#implement... |
#2520 is the smallest number that can be divided by each of
#the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible
#by all of the numbers from 1 to 20?
def MasterMultiple(n):
for x in range(1, 21):
if n % x != 0:
return False
return ... |
# OOP Lesson 2
class Wallet:
def __init__(self, starting_amount):
self.cash = starting_amount
def spend(self, amount):
new_amount = self.cash - amount
print("Spending Money...")
print("${} >> ${}".format(self.cash, new_amount))
self.cash = new_amount
class SchoolSupply:
def __init__(self, cost, wa... |
def linear_search(list, key):
"""If key is in the list returns its position in the list,
otherwise returns -1."""
for i, item in enumerate(list):
if item == key:
return i
return -1 |
# Regular Expressions
log = "July 31 7:51:48 mycomputer bad_process[12345]: ERROR Perfroming package upgrade"
index = log.index('[')
# Brittle way to extracing numbers by using index function
print(log[index+1:index+6])
# re module allows for search function to find regular expressions inside strings
import re
log = ... |
# ------------------------------------------------------------------------ #
# Title: Assignment 08
# Description: Working with classes
# ChangeLog (Who,When,What):
# RRoot,1.1.2030,Created started script
# RRoot,1.1.2030,Added pseudo-code to start assignment 8
# CRoss,12.7.20,Modified code to complete assignment 8
# ... |
#!/usr/bin/env python
from math import ceil,sqrt
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
import sys
def euclidn(n):
A = [True]*(n + 1)
en = []
for i in range(2,ceil(sqrt(n)+1)):
if A[i]:
for j in range(i*i,n+1,i):
A[j] = False
e = [i for i in range(len(A)) if A[... |
import random
import time
from datetime import datetime
class Limiter:
"""Can be used to slow down processing"""
def __init__(self, fps=2):
"""Construct limiter
Args:
fps (number/tuple): Requested number of processing steps per second.
Will pause between start() a... |
# Uses python3
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current % 10, (previous + current) % 10
return current % 10
def fib(n):
if n <= 1:
return n
previous = 0
current = ... |
arr = [1, 2, 3, 4, 5, 6]
flag= -1
for i in range(0, len(arr), 2):
arr.insert(i,arr[flag])
arr.pop()
print(arr)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 14:53:59 2020
@author: Ron
"""
import random
import math
# The Agent class:
# Variables: y and x (coordinates)
# Methods: move and get for each variable
class Agent:
def __init__(self, y, x, environment, agents, cannibal):
self.y = y
self.x = x
... |
#!/usr/local/bin/python3
from weather import Weather, Unit
from sys import argv
def get_weather(city):
weather = Weather(unit = Unit.CELSIUS)
location = weather.lookup_by_location(city)
condition = location.condition
print(condition.text)
print(condition.temp + '° C')
if len(argv) > 2:
pri... |
# -*- coding: utf-8 -*-
#set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。要创建一个set,需要提供一个list作为输入集合
s1list = [1,1,1,2,2,3,3,3,4]
print('s1list = %s'%str(s1list))
s1 = set(s1list)
print(s1)
s = set([1,2,3])
print(s)
x = input('请为set添加一个元素')
s.add(int(x))
print(s)
y = input('请为set删除一个元素')
s.remove(int(y))
prin... |
# -*- coding: utf-8 -*-
def power(a,b=1):#计算b个a相乘,b为位置参数,默认是1
sum = 1
while b>0:
sum = sum * a
b = b -1
return sum
#单例
def add_end(L = None):
if L is None:
L = []
L.append('初始化')
else:
L.append('end')
return L
x = int(input('请输入第一个数'))
y = int(input ('请输入第二个数'))
if (not isinstance(x,int)) | (not isinst... |
# Vitaly Osipenkov
# ID: 324716448
from contact import Contact, ProfessionalContact, FriendContact, ProfessionalFriendContact
contacts = []
# Adds a new contact into the phone book, by chosen type of contact.
def addContact():
while True:
print("Should this contact be Simple (S), Friend (F), Profe... |
class profile(object):
email = ""
name = ""
city = ""
def __init__(self, email, name, city):
self.email = email
self.name = name
self.city = city
def to_csv(self):
return self.email + "," \
+ self.name + "," \
+ self.city
|
#Dice Simulator
import random
class Dice_Sim:
def __init__(self):
self.lst=[]
self.count=0
def Cust_Dice(self):
dice=random.randint(1,6)
#dice output will be saved in list
self.lst.append(dice)
#calling the count of 6
self.count=... |
flag = True
while flag == True:
while True:
try:
x = int(input('Enter your time: '))
break
except ValueError:
print('Enter correct time')
color_time = x % 6
if 0 <= color_time < 3:
print('Green')
elif 3 <= color_time < 4:
print('Yellow... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'reverse_words_order_and_swap_cases' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING sentence as parameter.
#
def reverse_words_order_and_swap_cases(sentence):
# Write your cod... |
"""
Charlie has been given an assignment by his Professor to strip the links and the text name from the html pages.
"""
import re
for _ in range(int(input())):
html_link_match = re.findall(r'<a href="([^"]+)[^>]*>(?:<[^>]+>)*([^<]*)', input())
for html, title in html_link_match:
print('{0},{1}'.format... |
#!/bin/python3
#
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
from collections import defaultdict
def plusMinus(arr):
# Write your code here
length = len(arr)
positive = 0
negative = 0
zeros = 0
result = []
for num in arr:
if... |
"""
Read a given string, change the character at a given index and then print the modified string.
"""
def mutate_string(string, position, character):
return '{before}{char}{after}'.format(
before=string[:position],
char=character,
after=string[position + 1:],
)
if __name__ == '__mai... |
#8.4 Open the file romeo.txt and read it line by line.
#For each line, split the line into a list of words using the split() method.
#The program should build a list of words.
#For each word on each line check to see if the word is already in the list and if not append it to the list.
#When the program completes, sort ... |
'''
Name : Bubble sort implementation using python 3.4
Author,
Md Imran Sheikh
Dept. of CSE, JUST
'''
def bubble_sort(L):
n = len(L)
for i in range(0, n):
for j in range(0, n-i-1):
if L[j] > L[j+1]:
L[j], L[j+1] = L[j+1], L[j]
return L
if __name__=="__main_... |
from queue import PriorityQueue
class Graph:
def __init__(self, num_of_vertex):
self.vertexs = num_of_vertex
self.edges = [[-1 for i in range(num_of_vertex)] for i in range(num_of_vertex)]
self.visited = []
def add_edge(self, vertex1, vertex2, weight):
self.edges[vertex... |
'''
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of ev... |
'''
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# ... |
'''
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:
Input: [4,1,2,1,2]
Output: 4
'''
# 1 count()
c... |
'''
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any t... |
'''
Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <=... |
"""
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path
from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum dept... |
'''
Given an integer n. No-Zero integer is a positive integer which doesn't contain any 0 in its decimal representation.
Return a list of two integers [A, B] where:
A and B are No-Zero integers.
A + B = n
It's guarateed that there is at least one valid solution. If there are many valid solutions you can return... |
'''
In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
The town judge trusts nobody.
Everybody (except for the town judge) trusts the town judge.
There is exactly one person that satisfies properties 1 and 2... |
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that ... |
'''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 i... |
'''
Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You ma... |
'''
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input... |
'''
Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"
Constraints:
1 <... |
'''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
'''
# 1 Basic method
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
whil... |
'''
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [... |
'''
Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly n... |
'''
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exi... |
'''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ ... |
'''
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
'''
# 1 Basic Method
class Solution:
def isPowerOfFour(self, num: int) -> bool:
if num... |
from sys import argv
import time
import itertools
import numpy as np
import time
def guess_password_generators(passwd, chars, password_length):
attempts = 0
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == passwd:
... |
def words_per_article(df, col):
'''Returns descriptive statistics for variable of interest in terms of words per article.
Returns a histogram of the frequency of words observed.
df: dataframe you wish to call
col: column/feature that is to be counted'''
lens = df[col].str.split().apply(lambda x: l... |
import time
import random
from elevatorSystem import ElevatorSystem
def simulate_floorrequest():
num_elevators = 3
first_elevator = 0
second_elevator = 1
lowest_floor = 0
highest_floor = 20
es = ElevatorSystem(num_elevators, lowest_floor, highest_floor)
index = 0
print... |
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
if size == "s":
s = 15
p = input("do you want pepperoni? Y or N ?")
if p == "y":
s +=2
c = input("do you want extra-cheese? Y or N ?")
if c == "y":
s +=1
print(f"please pay ${s}")
else:
p... |
name_fast = input('Give a Name to Your Fast but Lazy Buddy')
name_slow = input('Give a Name to Your Slow but Steady Buddy')
town = input('Give a Name to Imaginary Town')
activity = input(f'Which activity did {name_fast.title()} start doing thinking he was in the lead?')
print(f'In the old town of {town}, the fast {name... |
class Canvas:
def __init__(self, row, col):
self.matrix = [[] * col] * row
self.rectangle_hash = {}
for i in range(row):
for j in range(col):
cell = Cell(i, j )
self.matrix[i][j] = cell
def draw(self, left_top, right_bottom):
length =... |
#Aim: Write a python program to delete the last row of the dataframe.
import pandas as pd
data = {'names': ['a1', 'a2', 'a3', 'a4'], "marks": [60, 90, 50, 40]}
df = pd.DataFrame(data)
df.drop(3,inplace=True)
print(df) |
n1=int(input("enter the no"))
n2=int(input("enter the no"))
n3=int(input("enter the no"))
max=n1
if n2>max:
max=n2
if n3>max:
max=n3
print("the greather no is",max)
|
class Pet:
totalPets = 0
def __init__(self, name, age):
self.name = name
self.age = age
self.health = 60
Pet.totalPets = Pet.totalPets + 1
def speak(self):
print(self.name + " is speaking")
def feed(self, value=10):
self.health = self.health + value
... |
def reverseWordsInString(string):
lst = []
returnstring = ""
for index in string:
if index != " ":
returnstring += index
else:
lst.append(returnstring)
returnstring = ""
lst.append(returnstring)
lst = " ".join(lst[::-1])
return lst
def revers... |
def minimumCharactersForWordsAlt(words):
hashmap = {}
for word in words:
_ = {}
for letter in word:
if letter in _:
_[letter] += 1
else:
_[letter] = 1
for character in _:
if character in hashmap:
if _[cha... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
# O(N) time | O(N) space
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# init condition
tot = l1.value + l2.value
carry = int(tot / 10)
l3 = ListNo... |
def threeNumberSum(array, targetSum):
array.sort()
resarr = []
for index in range(len(array)-2):
i, j, k = index, index+1, len(array)-1
while j < k:
currentSum = array[i] + array[j] + array[k]
if currentSum == targetSum:
resarr.append([array[i], array[... |
from cs50 import get_int
# get input from the user
while True:
n = get_int("Height:")
# cheking if int is in range
if n in range(1, 9):
break
m = n + 1
# printing each row
for i in range(1, m):
# print spaces
print(" " * (n - i), end='')
# print hashes
print("#" * i, end='')
# p... |
'''Create a program that reads the length and width of a farmer’s field from the user in
feet. Display the area of the field in acres.
Hint: There are 43,560 square feet in an acre.'''
length = int(input('Enter length of area: '))
width = int(input('Enter width of area: '))
square_feet = 43.560
square = length*width/... |
def jumpingOnClouds(c):
steps=0
jump=0
end=len(c)
while jump <(end-1):
if jump+2<end and c[jump+2]==0:
jump+=2
steps+=1
else:
jump+=1
steps+=1
return steps
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.