text
stringlengths
37
1.41M
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ",that was a grest trick!") print("I can't wait to see your next tridk, " + magician.title() + '.\n') print("Thank you,everyone.That was a great magic show!") #pizza pizzas = ['pizzas1', 'pizzas2', 'pizzas3'] for piz...
""" File: sierpinski.py Name: --------------------------- This file recursively prints the Sierpinski triangle on GWindow. The Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski. It is a self similar structure that occurs at different levels of iterations. """ import math from campy.graphics.gwind...
def root_1(a = 10, p = 3, delta = 0.001, nn = 20, i = 1): 'pth root of a - thru\' successive bifurcation' #delta is the acceptable accuracy #p is the exponent - integer #nn is the maximum number of iterations acceptable #i is the initial interval used for searching b, bp, n = 1, 1, 0 while bp < a: b += i bp = b*...
from enum import Enum class Element(Enum): STREET = " " BUILDING = "X" PERSON = 2 def format_block(element_enum): if element_enum == Element.STREET: return " " elif element_enum == Element.BUILDING: return "X" elif element_enum == Element.PERSON: return "2" else: ...
import pandas as pd import matplotlib.pyplot as plt plt.style.use('bmh') df = pd.read_csv(r"C:\Users\mauro\Desktop\Renata\Project Python\Projects_done\SuperStore_dataset\SampleSuperstore.csv", index_col=[0]) print(df.head()) # Shape, type and verify if it has value null print('Shape = {}'.format(df.s...
""" - author: Johannes Hötter (https://github.com/johannes-hoetter) - version: 1.0 - last updated on: 05/12/2018 Converts the Data from Source Format to Target / Machine Learning Format """ import pandas as pd # for dataframe operations import datetime # to convert columns in the dataframe try: import _pickle as ...
""" Uses Vadar Sentiment Analysis to calculate the polarity of text. """ import numpy as np import pandas as pd import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import constants as c nltk.download('vader_lexicon') def polarity(dataframe, review_column): """ Takes a dataframe and the c...
import time n = int(input('Height: ')) while (n < 1 or n > 10): n= int(input('Height: ')) #prints nxn bricks for i in range(n): for j in range(n): print('#',end='') print() time.sleep(0.1) print() time.sleep(2) #prints left-sided brick steps for i in range(n): for j in ...
from collections import Counter import time def greedy2(money,coins): result = 0 #checking if input is a string or value is negative while True: if (money.isalpha() or float(money) < 0): money= input("Change: ") else: break money = float(money) #accepts...
''' 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 在任何情况下,若函数不能进行有效的转换时,请返回 0。 说明:...
#Galilean Moons of Jupiter def radius(): radius_dict = {'Io': 1821.6, 'Europa': 1560.8, 'Ganymede': 2634.1, 'Callisto': 2410.3} return radius_dict def sur_gravity(): sur_gravity_dict = {'Io': 1.796, 'Europa': 1.314, 'Ganymede': 1.428, 'Callisto': 1.235} return sur_gravity_dict def orbital_per(): ...
#time calculator import sys seconds = int(input('Enter the number of seconds: ')) if(seconds < 0): sys.exit('Enter a right number') elif(seconds == 0): print('Seconds = 0') elif(0 < seconds < 60): print('Seconds = '+str(seconds)) elif(60 <= seconds < 3600): minutes = int(seconds / 60) second...
#high score def main(): file = open('scores.txt','r') read = file.readline() count = 0 highest = 0 name = '' while read != '': a = read.split(' ') count += 1 read = file.readline() a[1] = int(a[1]) if a[1] > highest: highest = a[1] ...
#calculating factorial import sys num = int(input('Enter a non-negative integer to find the factorial: ')) product = 1 if num < 0: sys.exit("Can't find factorial of a negative number") if num == 0: product = 0 while num > 0: product = product * num num -= 1 print('The factorial of the number is',p...
#Date printer def date_print(date): date = date.split('/') if date[0] == '01': print('January', date[1] + ',', date[2]) elif date[0] == '02': print('February', date[1] + ',', date[2]) elif date[0] == '03': print('March', date[1] + ',', date[2]) elif date[0] == '04': ...
#money counting game quarters = int(input('Enter the number of quarters: ')) dime = int(input('Enter the number of dimes: ')) nickels = int(input('Enter the number of nickels: ')) penny = int(input('Enter the number of pennies: ')) amount = quarters * 0.25 + dime * 0.1 + nickels * 0.05 + penny * 0.01 if amount < 1: ...
#string repeater string = input('Enter the string: ') number = int(input('Enter the number of times you want to print the string: ')) def string_print(x, y): for num in range(y): print(x,end='') if __name__ == '__main__': string_print(string,number)
#file line viewer def readFile(): fileName = input('Enter the file name along with the extension: ') file = open(fileName, 'r') fileInfo = list() total_lines = 0 while True: line = file.readline() line = line.rstrip('\n') if line == '': break total_lines...
#loan payment calculator def payment_calculator(rate, amount, months): payment_per_month = (rate * amount)/(1 - (1 + rate)**-months) print('The month payment amount will be $',format(payment_per_month, '.2f')) def main(): rate = float(input('Enter the rate of interest as a decimal (e.g. 2.5% 5 0.025): '...
#falling distance def falling_distance(time): g = 9.8 distance = 1/2 * g * time**2 return distance def main(): for x in range(10): time = float(input('Enter the time: ')) print('The distance(in metres) that the object has fallen in that time:', format(falling_distance(time),'.2f')) ...
# rainfall statistics def get_input(): user_input = list() for num in range(12): data = float(input('Enter the amount of rainfall in ' + str(num+1) + ' month: ')) user_input.append(data) return user_input def calculations(user_input): print('The total rainfall for the year was:', sum...
import employee_Class import pickle def get_data(): name = input('Enter the name: ') ID = input('Enter the ID: ') department = input('Enter the department: ') job_title = input('Enter the job_title: ') return name, ID, department, job_title def save_data(employee_dict): output_file = open('e...
import patientClass import procedureClass def procedure(): name = input('Enter the name of the procedure: ') date = input('Enter the date when the procedure was performed: ') name_practitioner = input('Enter the name of the practitioner who performed the procedure: ') charges = input('Enter the charge...
#kilometer converter kilometer = float(input('Enter the distance in km: ')) miles = kilometer * 0.6214 print('The distance in miles is:',miles,'mph')
#ocean levels year = 25 print('Year\tLevel Rise') level = 1.6 for num in range(1,year+1): print(num,'\t\t',format(level,'.2f'),'mm') level += 1.6
sum = 0 for i in range(1,1000): if i%3==0: #Check whether i is divisible by 3 sum+=i elif i%5==0: #Check whether i is divisible by 5 sum+=i print "Sum of all the multiples of 3 or 5 below 1000:", sum
class Solution: """ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Examp...
""" This file contains a number of built in strategies that can be passed to the Player class as arguments for strategy_func, wager_func, or insurance_func """ import random import pandas as pd from pathlib import Path CUR_PATH = Path(__file__).resolve().parent # read in strategy files BASIC_HARD = pd.read_csv( ...
def checkIfItsPrime(number): denominator = 1 max_number_of_nice_numbers = 2 current_number_of_nice_numbers = 0 number_given_was_prime = False while denominator <= number: remainder = number % denominator if remainder == 0: current_number_of_nice_numbers += 1 i...
import math import re def check (): ans = input () if ans == "y": main () elif ans != "n": print ("Напишіть y якщо хочете продовжити роботу чи n якщо потрібно завершити роботу") check() def read (): while True: a = input () if bool (re.match(r'(?:[0]\.\d+)|(?:[1-9](?:\d+)?(?:\.\d+)?)\Z', a)): if ((fl...
import math import re def check (): ans = input () if ans == "y": main () elif ans != "n": print ("Напишіть y якщо хочете продовжити роботу чи n якщо потрібно завершити роботу") check() def read (): a = input () while not bool(re.match(r'(?:[0]\.\d+)|(?:[1-9](?:\d+)?(?:\.\d+)?)\Z', a)): print ("Введіть ч...
""" Our new calculator is censored and as such it does not accept certain words. You should try to trick by writing a program to calculate the sum of numbers. Given a list of numbers, you should find the sum of these numbers. Your solution should not contain any of the banned words, even as a part of another word. T...
""" The Hamming distance between two binary integers is the number of bit positions that differs (read more about the Hamming distance on Wikipedia). For example: 117 = 0 1 1 1 0 1 0 1 17 = 0 0 0 1 0 0 0 1 H = 0+1+1+0+0+1+0+0 = 3 You are given two positive numbers (N, M) in decimal form. You should ca...
multipler = range(1, 101) for x in multipler: f = open("demofile2.txt", "a") f.write(" \n Table for " + str(x) ) print(" \n Table for " + str(x) ) for y in range(1,13): result = x*y f.write("\n" + str(x) + "X" + str(y) + "=" + str(result) ) print(str(x) + "X" + str(y) + "=" + s...
def grader(score, subject): counts = len(score) initial = 0 print('\n') print(subject) while initial < counts: print(score[initial]["name"]) if score[initial]['score'] >= 50 and score[initial]['score'] <= 60: print(" You barly escaped " + " " + str(score[initial]['score...
class Solution: # @return a string def convertToTitle(self, num): out = [] while num > 0: print num temp = num % 26 num = num // 26 if temp == 0: out.append('Z') num = num-1 else: out.appe...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def get_paths_num(self, root, path_numbers, num): if root.left is None an...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param two ListNodes # @return the intersected ListNode def getLength(self, head): current = head length = 0 while current != None:...
#http://rosalind.info/problems/hamm/ #two given DNA strings rosalind = open('rosalind_hamm.txt') string = {} string[0] = rosalind.readline()[:-1] string[1] = rosalind.readline() hamming_distance = 0 for n in range(len(string[0])): if string[0][n] == string[1][n]: pass else: hamming_distance ...
# -*- coding: utf-8 -*- """ Command line argument format is python simProject.py <printer format> <number of trials> Dependencies: NumPy and SciPy Notes: With regards to floors so the numbers don't get confusing 0 is Cathedral ground floor, 1-38 are floors 1-38 -1 is the basement, -2 is outside the buildin...
# Averages three numbers using an array and a loop from cs50 import get_int # Get scores scores = [] for i in range(3): scores.append(get_int("Score: ")) # Print average print(f"Average: {sum(scores) / len(scores)}")
#as still have to use start and end variables, using recursion only saves the need for #two variables. def binarySearch(sortedList, lowerNumber, upperNumber, midpoint): #(1) '''takes a sorted list of integers. Two integers that specify the interval we are searching for. And an integer calculated by t...
def division(fiveCount, number): '''This function calculates the amount of trailing 0s in the factorial of the number that is inputted. The first argument should be an integer and the second should be a float. ''' #checks for base case. if number >= 0 and number < 1: return fiveCount ...
from queue import Queue from threading import Thread import time _sentinel = object() # A thread that produces data def producer(out_q): n = 10 while n > 0: # Produce some data out_q.put(n) time.sleep(2) n -= 1 # Put the sentinel on the queue to indicate completion ou...
numbers = {n: i + 1 for (i, n) in enumerate(list(map(int, input().split(","))))} current = list(numbers.keys())[-1] for index in range(len(numbers), 30000000): previous = current current = index - numbers.get(current) if current in numbers else 0 numbers[previous] = index print(current) """ Advent of Cod...
print ("How old are you ?"), age = input() print ("How tall are you?"), height = input() print ("How much do you weigh?"), weight = input() #print ("So you are %r of age with %r of height and %r of weight awesome" % (age, height, weight)) #print("So you are {0} of age {1} of height and {2} and of weight Awesome!!!"...
from sys import argv script, first, second, third = argv print ("The script is called:", script) print ("The first argument you have passed is", first) print ("The second argument you have passed is", second) print ("Third argument you have passed is", third) ''' import sys print ("number of arguments", len(sys.ar...
print("HelloWorld") print("Hi,Nice to see you") print("I like typing this.") print('!Yay, I would say') print('i would "say" hi') print('I would say "NO......."') print(1,2,3,4,sep=' LED ') print ('The number enter here will be in new line',1,2,3,4, sep='\n') #my_name = 'Zed A. Shaw' #print ("Let's %s talk about us." ...
year=int(input("enter the year")) i=0 while i<1: if year%4==0 or year%100==0 or year%400==0: print(year,"is a leap year") else: print(year,"is not a leap year") i+=1
i=1 a=1 while i<=3: j=1 while j<=3: print(a,end=" ") a=a+1 j=j+1 print() i=i+1
i=1 while i<=100: if i%2==0: print(-i) else: print(i) i=i+1 # i=891 # while i<931: # z=i-890 # if z%3==0: # print(z) # i=i+1
i=1 sum=0 while i<=10: user=int(input("entr the number")) sum=sum+user i=i+1 print(sum)
# # Copyright 2020-21 by # # University of Alaska Anchorage, College of Engineering. # # All rights reserved. # # Contributors: ................ and # Christoph Lauter # # # class DFA: """Deterministic Finite Automaton Either positional arguments or keyword arguments are supported, bu...
class Solution: def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 longest = [1 for _ in range(len(nums))] for index, num in enumerate(nums): for i in range(index): if num ...
""" 注意求解目标:Player1 能否赢 Player2,并不在意Player1 和 Player2实际得的分数 这样就可以把问题抽象成: 针对给定数列,Player1 比 Player2 最多能多获取多少分 """ class Solution: def PredictTheWinner(self, nums): """ :type nums: List[int] :rtype: bool """ score_diff = [[None for _ in range(0, len(nums))] for _ in range(0, len...
"""This is the main file you'll edit. """ try: from game import board_from_heights except ModuleNotFoundError: pass # 4 possible rotations for any piece. ROTATIONS = [0, 1, 2, 3] def make_move(rows, columns, heights, shape_name, x, rotation): """Takes a the tetris board as column heights an...
import random def lotteryfull(): print('Lotto') print('-----') print('Hello', capital, 'your Lotto numbers are:', random.sample(range(1, 60), 6)) print('Euro Millions') print('-------------') print('Your Euro Millions numbers are:', random.sample(range(1, 51), 5), 'your Lucky Stars numbers ar...
from flask import Flask, render_template, request # import json to load JSON data to a python dictionary import json # urllib.request to make a request to api import urllib.request app = Flask(__name__) @app.route('/', methods =['POST', 'GET']) def weather(): if request.method == 'POST': city...
#reading a file contents from a folder my_file = 'notes.txt' guest_file ='guests.txt' with open(my_file) as nano: contents = nano.read() print('\nDisplaying contents of the file notes.txt:\n' + contents.rstrip()) print("There are " + str(len(contents)) + " characters in the file notes.txt") #Program that navig...
graph_list = {1: set([2,3,4]), 2: set([1,5]), 3: set([1,6,7]), 4: set([1,8]), 5: set([2, 9]), 6: set([3, 10]), 7: set([3]), 8: set([4]), 9: set([5]), 10: set([6])} root_node = 1 from collection...
import Tkinter as tk window = tk.Tk() window.tittle = ("my window") window.geometry = ("200x200") var1 = tk.StringVar() l = tk.Label(window,bg = "blue",height = 2,textvariable = var1) l.pack() def print_selection(): value = lb.get(lb.curselection()) var1.set(value) bt1 = tk.Button(window,text = "print selec...
import random print("number guessing game") number=random.randint(1,9) numberofchances=0 print("guess a number between 1 to 9") while numberofchances<5: guess=int(input("enter your guess")) if guess==number: print("congratulation! you got it right") break elif guess<number: ...
#!/usr/bin/env python # coding: utf-8 # In[1]: print("Hello world") # In[8]: print("Welcome to letsupgrade python Essentials") # In[11]: print("'$is american currency"') # In[12]: print(" we can do, if we want") # In[16]: print("im\nsanket") # In[24]: name= "sanket" age= "19" marks= "95.67" prin...
def floodFillUtil(screen, x, y, prevC, newC): # Base cases if (x<0 or x>m or y<0 or y>m or screen[x][y]!=prevC or screen[x][y]==newC): return # Replace the color at (x, y) screen[x][y] = newC # Recur for north, east, south and west floodFillUtil(screen, x + 1, y, prevC,...
num = 2520 while True: if(num % 11 == 0 and num % 12 == 0 and num % 13 == 0 and num % 14 == 0 and num % 15 == 0 and num % 16 == 0 and num % 17 == 0 and num % 18 == 0 and num % 19 == 0 and num % 20 == 0): print("Answer: {}".format(num)) break num += 2520
#lista1 + lista2 - serve para concatenar listas. # lista * 5 - imprime a lista cinco vezes. # <valor> in lista - verifica se o elemento existe dentro da lista. # lista.append(x) - acrescentar itens na lista. # lista.insert(posição, x) - acrescentar itens na posição tal. # lista.index(x) - Busca de posição por valor....
# LOOP WHILE # Estrutura de repetição que permite executar um bloco de códico, enquanto a condição for verdadeira # Sintaxe; # while (condição): # bloco de códico. # # ex: #controle = "" #while (controle != "s"): # print("a.Pagar") # print("b.Receber") # print("c.Transferir") # print("s.Sair") # ...
class BishopMove: def howManyMoves(self, r1, c1, r2, c2): if r1 == r2 and c1 == c2: return 0 if r1 > r2: k = r1 - r2 else: k = r2 - r1 if c1 > c2: num2 = c1 - c2; else: num2 = c2 - c1; if num2 == k: ...
""" This document contains a set of functions needed to perform analyses. The functions described here are all functions that perform analyses in some way necessary to calculate the final score on configurations of garbage containers. The loading of data functions and the algorithms themselves are in the other provide...
import random class Cell: def __init__(self, row: int, col: int, max_number: int): self.row = row self.col = col self.possibilities = list(range(1, max_number + 1)) self.value = 0 def __str__(self): return f"({self.value} {self.possibilities})" def __repr__(self):...
# ---------------------------------------------------------------------- # Name: Permutation in String # Author(s): Trinity Nguyen # ---------------------------------------------------------------------- """ Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. ...
# ---------------------------------------------------------------------- # Name: Maximum Sum Circular Subarray # Author(s): Trinity Nguyen # ---------------------------------------------------------------------- """ Given a circular array C of integers represented by A, find the maximum possible su...
def solve(input): listOfMoves=[] step = 0 actualIndex=0 futureIndex=0 right=0 for line in input.splitlines(): listOfMoves.append(int(line)) right = len(listOfMoves)-1 while(True): futureIndex=actualIndex+listOfMoves[actualIndex] if(futureIndex<0 or f...
import hw1 from cse163_utils import assert_equals def test_total(): """ Tests the total method """ # The regular case assert_equals(15, hw1.total(5)) # Seems likely we could mess up 0 or 1 assert_equals(1, hw1.total(1)) assert_equals(0, hw1.total(0)) # Test the None case asse...
from storage import Storage class PasswordHandler: def __init__(self): self.storage_instance = Storage() self.storage = self.storage_instance.read_storage() def create_line(self, key, password): self.storage[key] = password return f'{key}:{password} was added to the storage' ...
a = input ("Enter character: ") if a == "a": print(1) elif a == "b": print(2) elif a == "c"
def quicksort(nums): if len(nums) <= 1: return nums else: return quicksort([i for i in nums if i < nums[0]]) + [i for i in nums if i == nums[0]] + quicksort([i for i in nums if i > nums[0]]) nums = [3,1,4,5,2,4] print(quicksort(nums)) def partition(nums,l,r): pivot = nums[l] while l < r:#因为取...
from string import digits, ascii_lowercase, ascii_uppercase def tentoany(n, base): chars = digits+ascii_lowercase+ascii_uppercase a,b = divmod(n,base) if a: return tentoany(a,base)+chars[b] else: return chars[b] def anytoten(n, base): chars = digits+ascii_lowercase+ascii_uppercase if not n: ...
l = [1,2,3] e1 = 2 e2 = 10 def search_element(x,y): if y in x: return x.index(y) # 이 부분에 대해서 제대로 작성하지 못함 else: return False print(search_element(l,e1)) print(search_element(l,e2))
def reverse_text(x1,x2,x3,x4,x5): i = 1 if len(xi) % 2 == 0: return xi if len(xi) % 2 == 1: return reverse(xi) i += 1 print(reverse_text('tiger','lion','bear','snake','leopard'))
''' Problem: Rotate Matrix Description: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? Solved: Halve. Don't know how to do it in-place, did see a 1-line solution on the internet: zip(*matrix[::-1]) ''' d...
''' Problem: Queue via stacks Description: Implement a MyQueue class which implements a queue using two stacks. Solved: True ''' class MyQueue: to_add = None to_remove = None last_pop = False def __init__(self, size): self.to_add = Stack() self.to_remove = Stack() def add(self, el...
''' Problem: Sum Lists Description: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. FOLLOW UP: Suppose ...
''' Problem: Power Set Description: Write a method to return all subsets of a set. Notes: Not sure how to flatten the list Solved: True ''' import copy def all_subsets(array, subsets, curr_solution): if not array: return curr_solution else: left_tree = all_subsets(array[1:], subsets, curr_solu...
''' Problem: Zero Matrix Description: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to O. Solved: True ''' def parse_matrix(m): indexes = [] for i in range(len(m)): for j in range(len(m[i])): if m[i][j] == 0: indexes.app...
''' Problem: Sort Stack Description: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. Solv...
''' Problem: Is Unique Description: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Solved: True ''' def is_unique(word): d = {} for c in word: if c in d: return 'Not unique!' d[c] = 0 return 'Uni...
#This program will display how many calories of cookies you eat #Since the whole bag contains 30 cookies and all 30 cookies are 900 calories #We will multiply the amount of cookies eaten by 900 #And then divide that number by 30 # # #Name: Zachary Baltrus #Assignment: Homework 1 # #CIT 1400 #This line of code will be ...
# Game: Heads or Tails # This program will have a user enter heads or tails # The computer will then generate 0 or 1, which will be heads or tails. # Then the computer will report if the user is correct or incorrect. # The program will then ask the user if they want to play again. # # # Homework 5 # Zachary Baltrus # #...
# Electrical Engineering Problem # This program will calculate the power by having # the user enter the current of the resistance # # # Lab 6 # Zachary Baltrus # # CIS 1400 # First this is defining all of the Lists to be set to their base value resistanceList = [16, 27, 39, 56, 81] currentList = [] powerL...
a = int ( input() ) i = 0 for i in range(a): b = int ( input() ) t = 2 ** b t = int(t / 12 / 1000) print (t,"kg")
#PART (1/5): Latitude and Longitude #In this part, we are going to visualize the location of the birds. We are going to plot latitude and longitude along y and x-axis respectively and visualize the location data present in the csv file. import pandas as pd import matplotlib.pyplot as plt import numpy as np birddata...
import random def random_numbers(): numbers = set() while len(numbers) < 5: random_number = random.randint(0, 90) numbers.add(random_number) return numbers winning_numbers = random_numbers() my_numbers = random_numbers() my_winning_numbers = winning_numbers.intersectio...
def bfs(graph): visited = set() frontier = [0] while len(frontier) > 0: next_elm = frontier.pop(0) if next_elm in visited: continue visited.add(next_elm) for neighbour in graph[next_elm]: frontier.append(neighbour) return len(visited) def main()...
#leetCode problem 500 #Keyboard Row r1 = list('qwertyuiopQWERTYUIOP') r2 = list('asdfghjklASDFGHJKL') r3 = list('zxcvbnmZXCVBNM') #print (r1[10]) def fn1 (l): list_char = [] flag = False final = [] print (l) for i in range (0, len(l)): list_char.append(list(l[i])) x ...
# 035 # An array of number [1,3,4,6] will be called nums # A number 5, will be called target # return should be 2, since in an array # [ 1 , 3 , 4 , 6 ] // BTW array is sorted # 0 1 2 3 //position # thus return 2 since 5 is >3 and <4, thus should be added to pos 2 def solution(nums, target): if target > n...
#LeetCode 344 #reverse String def fn (s): list_s = list(s) reversed_list = list_s[::-1] return "".join(reversed_list) test_1 = "hello" print(fn(test_1))
#!/usr/bin/env python """ n_queens.py N-queens solver (`CSPy` usage example). """ import itertools import numpy as np import matplotlib.pyplot as plt from cspy import Variable, Constraint, CSP ############## # PARAMETERS # ############## N = 8 VARIABLES = 'pieces' # either 'squares' or 'pieces'. For effic...
def first_and_last(lists): count = 0 for i in lists: if len(i)>=2 and i[0]==i[-1]: count = count + 1 print(count) lists = list(input("Enter the elements of list:: ").split()) first_and_last(lists)
def sort(str): words = str.split() print(words) b=words.sort() print(b) return (b) a=input('enter words separated by comma:'.split(',')) print(sort(a))