text stringlengths 37 1.41M |
|---|
"""
The training grounds for the AI
"""
# Imported Modules
from check_ai import CheckersAI
from checkers_3 import Checkers
# Global Variables
aiPlayers = []
# Pits two AI against each other in a game of Checkers
def aiMatch(player1,player2):
players = [player1,player2]
game = Checkers()
while not game.gam... |
#Consider the following dataset. How do you use the Candidate Elimination algorithm when the first example is negative?
#Implement the algorithm for the same.
from os import sep
import numpy as np
import pandas as pd
#algo
def candidate_elimination(concepts, target):
specific_h = concepts[1].copy()
genera... |
from array import *
x = int(input("Tal 1:"))
y = int(input("Tal 2:"))
arr = array("i", [x, y])
arr.reverse()
print(arr)
|
#######################################
# Automate the boring Stuff with Python
#######################################
# Chapter 1
# Self learning from Python Documentation
#######################################
# Absolute
"""
print('find absolute of the number')
print('Enter any number\n')
num1 = input()
print("Ab... |
def bruteForce(W,berat,nilai,deep,n,kondisi):
if deep == n:
cost = 0
val = 0
x = ''
for i in range(n):
if kondisi[i] :
cost = cost + berat[i]
val = val + nilai[i]
x = x + str(i+1) + ' '
if cost <= W and cost != 0:
... |
from task_5 import*
genre_list=[]
diffrent_genre=[]
dublicate_genre=[]
genre_dict={}
def analyse_movies_genre(movies_list):
for name in movies_list:
# print (name)
movie_genre=name["genre"]
genre_list.append(movie_genre)
# print (genre_list)
for a in genre_list:
for b in a:
... |
#fibonacci series
print("\twelcome to the program")
print("we are going to find the fibonancy series as per your input number of terms\n")
x=0
y=1
n = int(input("enter the term till which you want to find the fibonancy series="))
i=3
print(x,y,sep=',',end=',')
while i<=n:
sum=x+y
x=y
y=sum
if i<n:
pr... |
#find the type of triangle
print("\twelcome to the progarm")
print("we will find the type of triangle by your input angle")
print("you ust input the angle of triangle in degree\n")
a = int(input("enter the first angle ="))
b = int(input("enter the second angle ="))
c = int(input("enter the third angle ="))
sum =... |
#function
print("\n\t..........|| WELCOME TO THE PROGRAM ||.............")
print("PLEASE ENTER THE INTEGERS FOR THE LIST.\n")
list_numbers=[]
num=int(input("ENTER NUMBER OF INTEGERS IN THE LIST :- "))
for i in range(num):
item=int(input("ENTER THE INTEGER {} = ".format(i+1)))
list_numbers.append(item)
def asc... |
#to count the number of upper case letters and lower case letters and numbers of digits
print("\n\t......WELCOME........")
print("lets count number of upper case and lower case alphabets and number of digits present in your entered string.\n")
string=input("enter the string :- ")
i=0
count_lower=0
count_upper=0
count_... |
#to check weather entered character is an alphabet
print("\n\t.......WELCOME TO THE PROGRAM.........")
print("we will check wether your entered chacrcter is an alphabet.\n")
x=input("Enter an charcter :- ")
if (ord(x)>=65 and ord(x)<=90)or(ord(x)>=97 and ord(x)<=122):
print("The character '",x,"' is an aplhabet.")
el... |
#examples for function
print("\n\t..........|| WELCOME TO THE PROGRAM ||.............")
print("\n")
def swap_num(a,b):
c=a
a=b
b=c
print("\nINSIDE FUNCTION :\n a :- {}\nb :- {}".format(a,b))
a=int(input("enter a = "))
b=int(input("enter b = "))
print("\nBEFORE FUNCTION CALL :\n a :- {}\nb :- {}".format... |
#calculation of total marks and average marks and result as pass or fail
print("\n\t...........WELCOME..........\n")
print("please enter all the marks of class 12th out of 100 properly to find the proper result.\nALL THE BEST......\n")
sub_eng=float(input("ENTER THE MARKS OF ENGLISH = "))
assert sub_eng >=0 and s... |
#find the slope of 2d curve
print("\twelcome to the program")
print("you have to enter two different cordinates of the curve.\n")
print("enter the cordinate 1")
x1=float(input("enter the x value="))
y1=float(input("enter the y value="))
print("\nenter the cordinate 2")
x2=float(input("enter the x value="))
y2=f... |
#dictionary
print("\n\t..........|| WELCOME TO THE PROGRAM ||.............")
student_dict={'Name': 'UMESH', 'ENGLISH': 94, 'MATH': 95, 'PHYSICS': 95, 'CHEMISTRY': 95, 'COMPUTER': 100, 'Result': '<<..PASS..>>'}
# accesing the iteams
n=student_dict['Name']
print(n,"\n")
for i in student_dict: #accesing thr... |
def vowel_count(string):
#list of vowels
vowels= {"a":0,"e":0,"i":0,"o":0,"u":0}
#loops through vowels
#appends value if key appears more than once
for key, value in vowels.items():
for i in string:
if i == key:
vowels[key]+= 1
return vowels
print(vowel_c... |
#!/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swaps_total = 0 # count the total number of swaps done to sort the list
for i in range(0,len(a)): # bubble sort: conduct loops for (the num of element) times
num_of_swaps = 0 ... |
def minmax(state, depth=2):
def ft_max(state, alpha, beta, d):
if state.is_terminal() or d >= depth:
return state.heuristic_value
node_value = float('-inf')
for i, move in enumerate(state.available_moves):
node_value = max(node_value, ft_min(state.next_state(move),alpha, beta, d+1))
if node_value >= be... |
revenue = int(input("Введите сумму выручки фирмы в $: "))
costs = int(input("Введите сумму издержек фирмы в $: "))
profit = None
loss = None
if revenue - costs >= 0:
profit = revenue - costs
print(f"Ваша прибыль составляет: {profit}$")
else:
loss = costs - revenue
print(f"Сумма ваших убытков составляет... |
class Room():
def __init__(self, chart, name, description, x = 0, y = 0):
self.name = name
self.description = description
self.x = x
self.y = y
self.coordinates = [self.x, self.y]
self.map = chart
#items in the room
self.items = {}
... |
string = "Hello World"
new_string = ''
for i in string:
if i == 'e':
new_string += 'o'
elif i == 'o':
new_string += 'e'
else:
new_string += i
string = new_string
print(string)
|
INT_MAX = 999
#This function calculates the closest vertex to visit next
def min_wt(nv, evalues, vlist):
min, min_index = INT_MAX, 0
for i in range(nv):
if vlist[i] == False and evalues[i] < min:
min = evalues[i]
min_index = i
return min_index
#Performs Prims' method for finding MCST
def prims(nv, graph):
... |
list = [1,2,3,4,5,6,7,8,9,10]
for i in list:
print (i, end="") #end statement is used so that python doesn't print all numbers in new lines.
|
def run():
# for contador in range(1001):
# if contador%2 != 0:
# continue
# print(contador)
# for i in range(10000):
# print(i)
# if i==5678:
# break
# texto=input('Escribe un texto: ').upper()
# for letra in texto:
# if letra=='O':
... |
class Coordenada:
def __init__(self, x, y):
self.x = x
self.y = y
def calcular_distancia(self, coordenada):
a = abs(self.x - coordenada.x)
b = abs(self.y - coordenada.y)
return (a**2 + b**2)**0.5 |
from math import floor
def legendre(n, p):
pow = 0
k = 1
while True:
val = floor(n / p**k)
if val == 0:
return pow
pow += val
k += 1
MOD = 1000000009
N = 100000000
if __name__ == '__main__':
primes = []
ans = 1
with open('primes', 'r') as primes_f... |
orderedList = [1,2,3,4]
reverseOrderedList = orderedList.reverse()
numbers = open("numbers.txt")
#numbersList = numbers.split('\n')
#print(numbers.readline())
numList = []
for number in numbers:
numList.append(int(number))
print(int(number))
print(numList)
reversedList = numList.reverse()
sor... |
#%%
import os
import csv
# Path to collect data from the Resources folder
wrestling_csv = 'C://Users/josrh/Desktop/Stuff/ClassRepo/Module-8/wrestling_functions/Resources/WWE-Data-2016.csv'
# Define the function and have it accept the 'wrestlerData' as its sole parameter
def print_percentages(wrestlerData):
Name = ... |
#!/usr/bin/env python
# coding: utf-8
# In[22]:
#Memozining Approach for Knapsack Problem
#Defining a -1 matrix
t=[[-1 for i in range(capacity+1)] for x in range(n+1)]
#Defining the knapsack function
def knapsack(value,weight,capacity,n):
#If there is no capacity or no item
if(value==0... |
# Convert the keys and values of a dictionary to elements of a tuple
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
# Clean way
def dict_to_tuple(dictionary):
return tuple(my_dict.items())
print dict_to_tuple(my_dict)
|
# Instructions at https://www.hackerrank.com/challenges/defaultdict-tutorial
"""
Run this program with a redirect to an input file like so:
$ python defaultDict.py < test.txt
"""
# Instructions at https://www.hackerrank.com/challenges/defaultdict-tutorial
#
import sys
from collections import defaultdict
# Both of t... |
# Make a generator that outputs the fibonacci sequence starting at a and b
# and ending before an number s
def fibonacci_generator(a, b, s):
# Validate inputs
inputList = [a, b, s]
print(inputList)
for value in inputList:
try:
# Necessary because int(0.11) won't throw a ValueError ... |
import random
import numpy as np
import matplotlib.pyplot as plt
class Sampling:
def __init__(self, a=0, b=20, fator=10.):
self.a = a
self.b = b
self.nome = "Amostragem aleatória"
#increasing the number os samples without any changes to the sampling's region of this example
X = [x/fator for x in range(int(... |
numbers = [int(el) for el in input().split(', ')]
positive = []
negative = []
even = []
odd = []
for num in numbers:
if num >= 0:
positive.append(num)
else:
negative.append(num)
for n in numbers:
if n % 2 == 0:
even.append(n)
else:
odd.append(n)
print(f"Positive: {', ... |
def numbers_searching(*args):
first_el = args[0]
last_el = args[-1]
missing_number = 0
temp_list = set(args)
duplicated_numbers = []
final_list = []
if first_el < last_el:
for index in range(len(args)):
if args[index] + 1 == args[index+1]:
continue
... |
def get_magic_triangle(n):
matrix = []
matrix.append([1])
matrix.append([1, 1])
def is_valid(n, m, i):
if m < 0 or n < 0 or m > n:
return 0
try:
wanted = matrix[n][m]
return wanted
except IndexError:
return 0
for i in range(2... |
password_1 = input("Enter your new password: ")
if len(password_1) < 6 or len(password_1) > 12:
print("Password must be between 6 and 12 characters.")
exit()
password_2 = input("Enter your password again: ")
if password_1 == password_2:
print("Password Changed")
else:
print("Passwords don't match.") |
import csv
from .. import definitions
def airport_statistics():
"""Returns a tuple containing airport IATA codes, a dictionary containing their
probabilities of being the origin of a flight, and their conditional probabilities
for being the destination of a flight given the origin."""
file = open(def... |
## Loads preprocessed train and test data
# and applies a heuristic to the data
import json
import numpy as np
from movie_lengths_lib import *
# Computes predicted values for each training sample - chooses the average value for the respective movie type
# Computes and returns the score computed as in sklearn.linear_m... |
def intersection(arrays):
'''
takes in nested list of numbers
'''
dict_list = []
main_dict = {}
# Turning each array into dict
for index, array in enumerate(arrays):
dict1 = {}
for num in array:
dict1.update({num: None})
# Adding newly created dict to ma... |
import numpy as np
'''
mean
my_array = numpy.array([ [1, 2], [3, 4] ])
print(numpy.mean(my_array, axis = 0)) #Output : [ 2. 3.]
print(numpy.mean(my_array, axis = 1))) #Output : [ 1.5 3.5]
print(numpy.mean(my_array, axis = None)) #Output : 2.5
print(numpy.mean(my_array)) #Output :... |
h=int(input('Enter hours: '))
r=int(input('Enter rate: '))
p=int(h)*int(r)
print('Pay: %d'%p)
|
#!/usr/bin/env python
import csv
def pivotCSVFile( fileName ):
''' This function takes in a filename, reads the file, adds the dates as keys to a dictionary so
that they are unique, and aggregates all texts that correspond to that date into one resulting value
'''
# Temp dictionary to store values
... |
import pandas as pd
import numpy as np
years = range(1880,2015)
print("Reading data")
def read_one_year(year):
path = 'data/yob%d.txt' % year
one_year_data = pd.read_csv(path, names=['Name','Gender','Births'])
one_year_data['Year'] = year
return one_year_data
names_data = pd.concat([read_one_year(ye... |
# class Product:
# def __init__(self , pid , name , price):
# self.pid = pid
# self.name = name
# self.price = price
class Product:
def __init__(self , data):
self.data = data
class Stack:
size = 0
total = 0
items = 0
def __init__(self):
# print(">> St... |
#in order to run a python file from the command line you have to go to the
#file location and type "pyhton filename.py" for it to run
#A command-line based blackjack game
import random
#why as tuples and not as lists?
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', '... |
import pandas as pd
import re
from typing import List, Set, Dict, Tuple, Optional
class Point:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def __eq__(self, other: object) -> bool:
if not isinstance(other, Point):
return NotImplemented
return ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
my_string = raw_input("")
my_string = my_string.upper()
count = 0
my_list = []
for c in my_string:
if c in my_list:
next
else:
if ord(c) < 91 and ord(c) > 64:
my_list.append(c)
count = count + 1
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
first_line = raw_input("")
L = long(first_line.split()[0])
S1 = long(first_line.split()[1])
S2 = long(first_line.split()[2])
diagonal = L*math.sqrt(2)
q = raw_input("")
for i in range(0, int(q)):
qi = raw_input("")
diagonal_s... |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Student:
def __init__(self, name, ID, GPA):
self.name = name
self.ID = ID
self.GPA = GPA
class CircularLinkedList:
def __init__(self):
self.__head = None
d... |
#!/bin/env python
def f(*args):
for (i,arg) in enumerate(args):
print "in function 'f':args[%d]=%s\n" % (i,str(arg))
if __name__ == "__main__":
f(1,1,2)
a=(1,2,3)
f(a)
|
# reading,wrting files in python
#basic syntax
with open('test.txt', 'r') as f:
print(f.read())
# f.close()
# dealing with image and other files by reading in byte mode
with open('Morpheus.png', 'rb') as rf:
with open('morpheus_copy.png','wb') as wf:
chunksize = 1024
rf_chunk = rf.read(c... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
import numpy as np
import random
import matplotlib.pyplot as plt
import pandas as pd
# ## Neighbors Operations
# ### Sawipping function
# In[5]:
def swapping_fun(elements ,N):
swap1=random.randint(0,N-1)
swap2=random.randint(0,N-1)
wh... |
def Fizzbuzz(n):
line = ''
if n % 3 == 0:
line += "Fizz"
if n % 5 == 0:
line += "Buzz"
if not line:
line += str(n)
return line
|
'''
Some more advanced usage of functions
'''
import statistics as st
import time
def describe(sample):
'''Function that returns 3 separate values'''
return st.mean(sample), st.median(sample), st.mode(sample)
# Call with 3 separate variables
my_sample = [10, 2, 4, 7, 9, 3, 9, 8, 6, 7]
mean, median, mode = des... |
'''
Mad lib game example with string manipulation
'''
def mad_lib():
''' Very simple Mad lib game example'''
color = input ("What's your favorite color? ")
plural_noum = input ("Enter a noum! ")
celebrity = input ("And what's your favorite celebrity? ")
print (f"Roses are {color}")
print (f"{pl... |
# this will be an example of dice roll game
from random import randint
def leftDice():
dice1 = randint(1,6)
print(dice1)
return dice1
def rightDice():
dice2 = randint(1,6)
print(dice2)
return dice2
leftDice()
rightDice()
|
# -*- coding: utf-8 -*-
"""
(a) Compute the minhash signature for each column if we use the following three hash functions:
h1(x) = 2x + 1 mod 6; h2(x) = 3x + 2 mod 6; h3(x) = 5x + 2 mod 6.
(b) Which of these hash functions are true permutations?
(c) How close are the estimated Jaccardsimilarities for the six pair... |
def print_message():
print('I\'m sorry, I did not understand your selection. Please enter the corresponding letter for your response.')
def get_size():
res = input('What size drink can I get for you? \n[a] Small \n[b] Medium \n[c] Large \n> ')
if res == 'a':
return 'small'
elif res == 'b':
return ... |
import requests
import bs4
movie = input("What movie do you want to search?")
person = input("Which actor/actress do you want to know if they're in a movie?")
r = requests.get("http://www.omdbapi.com/?t=" + movie)
if person in r.json()["Actors"]:
print("Yes! Person in movie")
else:
print("No, person not in movie"... |
import copy
import math
if __name__ == "__main__":
s = input("Please input the number: ")
n = int(input("Please input the time of adding: "))
num = copy.deepcopy(s)
sum = 0
for i in range(n):
sum += int(num)
num += s
print("The result is {0}.".format(sum))
|
total = 0
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if i != j and j != k and i != k:
print(i, end="")
print(j, end="")
print(k)
total += 1
print(total)
#end=""表结尾是什么,默认空格 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : number_off.py
# @Author: A
# @Date : 2019/1/24
# @Contact : qq1694522669@gmail.com
if __name__ == "__main__":
n = int(input("please input a number:"))
a = []
for i in range(n):
a.append(1)
c = 0
l = 0
total = len(a)
while tot... |
import math
def prime(n):
# print(math.ceil(math.sqrt(n)))
for i in range(2, math.ceil(math.sqrt(n)) + 1):
if n % i == 0:
return False
else:
continue
return True
if __name__ == "__main__":
print(2, end=" ")
for i in range(3, 98):
if prime(i):
... |
if __name__ == "__main__":
str = input("Please input the string: ")
ccount = 0
ncount = 0
spacecount = 0
ocount = 0
for i in str:
if i.isalpha():
ccount += 1
elif i.isdigit():
ncount += 1
elif i.isspace():
spacecount += 1
else:
... |
MAX = lambda x, y: x * (x >= y) + y * (y > x)
MIN = lambda x, y: x * (x <= y) + y * (y < x)
if __name__ == "__main__":
a = int(input("Please input the first number:"))
b = int(input("Please input the second number:"))
print(MAX(a, b))
print(MIN(a, b))
|
def downprint(a, deep):
if deep != len(a):
downprint(a, deep + 1)
print(a[deep], end=" ")
if __name__ == "__main__":
a = [i for i in input().split(" ")]
downprint(a, 0)
|
def str_bin_add(s1, s2):
if int(s1) < int(s2):
s1, s2 = s2, s1
s3 = ''
carry = 0
for i in range(len(s1)):
if i < len(s2):
if int(s1[-1-i]) + int(s2[-1-i]) + carry < 2:
s3 = str(int(s1[-1-i]) + int(s2[-1-i]) + carry) + s3
carry = 0
e... |
import numpy as np
import matplotlib.pyplot as plt
"""
q2.py
This program builds a logistic regression model for binary classification of given dataset
@author: Anushree Sitaram Das (ad1707)
"""
def getData(filename):
"""
load dataset from csv file
:param filename:
:return:
"""
data = np.gen... |
import numpy as np
import matplotlib.pyplot as plt
class Bandit():
def __init__(self, arms: int):
"""
Base bandit constructor
:param amrs: probability distribution of each arm
"""
# quantity of arms
self.narms = arms
# times each arm was used
self.na... |
def rivalries():
"""
Determines if it is possible to separate a list of people into two separate groups
based on a list of rivalries between some of the people. Returns yes and possible groups if so, no otherwise.
"""
from collections import defaultdict
file_name = input("Enter name of file inpu... |
'''
Create a function named divisors/Divisors that takes an integer n > 1
and returns an array with all of the integer's divisors(except for 1
and the number itself), from smallest to largest. If the number is
prime return the string '(integer) is prime'
Example:
divisors(12); #should return [2,3,4,6]
divisors(25); ... |
#-------------------------------------------------------------------------------
# Author: UO266321
# Created: 26/10/2018
#-------------------------------------------------------------------------------
"""
Comentario en
varias lineas
"""
#----------------------------------------------------------------------... |
def rob(nums):
table = []
if len(nums) == 0:
return 0
# 4 2 2 4
# 4 4 6 8
# nums[i-2] + value or nums[i-1]
for i, value in enumerate(nums):
if i == 0:
table.append(value)
elif i == 1:
if value > nums[i-1]:
table.append(value)
... |
# -*- coding:utf-8 -*-
# @Time:2020/7/27 17:55
# @Author:martin
# @File:__init__.py.py
# if __name__ == '__main__':
#
# for a in range(1, 10):
# for b in range(a, 10):
# print("%d * %d= %d"%(a, b, a*b ),end=" ")
# print("")
#
# if __name__ == '__main__':
# for a in range(1, 10):
#... |
# snake water gun
# rule
# Snake vs. Water: Snake drinks the water hence wins.
# Water vs. Gun: The gun will drown in water, hence a point for water
# Gun vs. Snake: Gun will kill the snake and win.
# play 10 time
import random
print(" ---------------")
print("|Snake Water Gun|")
print(" ---------------")
listShap... |
# letter = input()
# upperalphabet = ['0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
# 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# loweralphabet = ['0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
# 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v... |
import datetime
def weekday_name(number: int) -> str:
"""
Return a string representing a weekday
(one of "mon", "tue", "wed", "thu", "fri", "sat", "sun")
number : an integer in range [0, 6]
>>> weekday_name(3)
'thu'
"""
week_day = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun... |
from typing import List
def sieve_flavius(elements_number: int) -> List[int]:
list_of_numbers = []
for i in range(1, elements_number):
list_of_numbers.append(i)
for item in list_of_numbers:
if item % 2 == 0:
list_of_numbers.remove(item)
variable = 1
while variable < len(... |
def dyvo_insert(sentence, flag):
"""
Inserting word "диво" before every word that starts with flag.
>>> dyvo_insert("кит", "ки")
диво кит
>>> dyvo_insert("Кит кота по хвилях катав - кит у воді, кіт на киті.", "ки")
"""
# index = sentence.find(flag)
# final_string = sentence[:index] + 'ди... |
"""[sumary]
"""
def digit_sum(num: int) -> int:
"""Retturn sum of number digits
:param num: [description]
type num: int
"""
def add_digits(num):
total = 0
while num > 0:
num, rem = divmod(num, 10)
total += rem
return total
... |
def firstday(year,month):
# Refer to the website above for better understanding of the program
dict1={1:1,2:4,3:4,4:0,5:2,6:5,7:0,8:3,9:6,10:1,11:4,12:6}
last1=int(str(year)[len(str(year))-2:])
last=(last1//4)+1
last=last+dict1[month]
if isleap(year) and (month==1 or month==2) :
last=las... |
import re
def number_of_sentences(s):
"""
str -> str
Return number of sentence in the string. If argument is not a string function should
return None.
>>> number_of_sentences("Revenge is a dish that tastes best when served cold.")
1
>>> number_of_sentences("Never hate your enemie... |
def motzkin_sum_numbers(length):
"""
>>> motzkin_sum_numbers(15)
[1, 0, 1, 1, 3, 6, 15, 36, 91, 232, 603, 1585, 4213, 11298, 30537]
"""
new_list = []
len = list(range(1, length))
new_list.append(1)
for i in len:
# element_in_list = bin(i)
element_in_list = int((i-1)*(2 * ... |
# merge 2 sorted arrays
# given A=[]
# B=[]
# output- A=A+B
def mergearr(A,B,m,n):
while m >0 and n>0:
if A[m-1]>B[n-1]:
A[m+n-1]=A[m-1]
m=m-1
else:
A[m+n-1]=B[n-1]
n=n-1
while n >0:
A[m+n-1]=B[n-1]
n=n-1
return A
... |
import pandas as pd
import numpy as np
# Import cricket data
cricket = pd.read_csv('./Data/cricket_matches.csv')
# Only include if home team was the winner
cricket_home_winners = cricket[(cricket['home'] == cricket['winner'])]
# Pull out the rows where the winners were the home team based on inning
cricket_home_inni... |
"""Fibonacci iterative implementation
https://stackoverflow.com/questions/14661633/finding-out-nth-fibonacci-number-for-very-large-n/
"""
def fibonacci(n: int) -> int:
"""Implement Fibonacci iteratively
Raise:
- TypeError for given non integers
- ValueError for given negative integers
"""
if... |
import os
# patient_name = "John Smith"
# patient_age = 20
# patient_isNew = True
os.system('cls')
# print("Name: " + patient_name)
# print("Age: " + str(patient_age))
# print("New Patient: " + str(patient_isNew))
# === STRINGS ====
# course = "Python Programming"
# print("String Length: " + str(len(course)))
# p... |
# https://www.hackerrank.com/challenges/building-a-list
t = int(input())
for tests in range(t):
n = input()
s = input()
o = []
length = "0"+str(len(s))+"b"
for i in range(1<<len(s)):
op = ""
binary = format(i,length)
for j in range(len(binary)):
if binary[j]=='1':... |
lphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
global h
global n
global w
global pol
global poh
n=0
height = []
while n<=25:
print ('Height of the ', end ="")
print (alphabet[n] , end = '')
h = int(input('... |
import math
import os
import random
import re
import sys
def alternatingCharacters(s):
ch = list(s)
res = ch[0]
count = 0
#print(ch)
for c in range(len(ch)-1):
#print(ch[c],ch[c+1])
if ch[c] != ch[c+1]:
res = res + ch[c+1]
else:
count += 1
return(... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 10:45:10 2019
@author: Gerardo Armenta
Instructor: Dr. Olac Fuentes
TA: Anindita Nath, Maliheh Zargaran, Erik Macik, Eduardo Lara
Purpose: part1: To write a program that discovers trigonometric identities using a randomized
algorithm to detect equalities ... |
# Задание №7 - сделано
entered_number = int(input('Please enter an integer number: '))
factorial_of_entered_number = 1
while entered_number > 0:
factorial_of_entered_number = factorial_of_entered_number * entered_number
entered_number -= 1
print('Factorial of entered number = ', factorial_of_entered_numbe... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ... |
def date(day,month,year):
x=[31,28,31,30,31,30,31,31,30,31,30,31]
if year%4==0:
if year%100==0:
if year%400==0:
x[1]=29
else:
x[1]=29
d=sum(x[:month-1])
total=d+day
return(total)
|
c=['red','blue','green','white','black','purple','orange','pink','brown','gray']
a=int(input("yek adad az 0 ta 4: "))
b=int(input("yek adad az 5 ta 9: "))
print(c[a:b])
|
s=0
while s<=5:
s=int(input('enter number: '))
print('the last number you entered was s',s)
|
print('Who do you whant to invite to the party')
q=input('1: ')
w=input('2: ')
e=input('3: ')
r=input('Do you whant to add another yes/no ')
s=3
while r=='yes':
s=s+1
t=input(s )
r=input('Do you whant to add another yes/no ')
print(s)
|
"""
Filename globbing like the python glob module with minor differences:
* glob relative to an arbitrary directory
* include . and ..
* check that link targets exist, not just links
"""
import fnmatch
import os
import re
from pathlib import Path
from typing import Union, List
from . import util
_glob_check = re.co... |
len1 = float(input('please input len1: '))
len2 = float(input('please input len2: '))
len3 = float(input('please input len3: '))
def cntPeremeter(l1, l2, l3):
return l1 + l2 + l3
def cntArea(l1, l2, l3):
p = (l1 + l2 + l3)/2
return (p*(p-l1)*(p-l2)*(p-l3)) ** 0.5
if (len1 < len2 + len3) and \
(len2 < len1 + len3)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.