Given an integer n, return any array containing n unique integers such that they add up to 0.
# Example 1: Input: n = 5 | Output: [-7,-1,1,3,4]# Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].# Example 2: Input: n = 3 | Output: [-1,0,1]# Example 3: Input: n = 1 | Output: [0]
# Constraints: 1 <= n <= 1000
## time complexity: O(1 or n)## space complexity: O(1)defsumZero(self,n:int):""" :type n: int :rtype: List[int] """# time complexity: O(1); create one range of digits# space complexity: O(1); one unit of space# What's going on here? Let's say n = 5.# Return a range of numbers which starts at 1-5, ends at 5, steps every 2# So that means it starts at -4, ends at 5, steps every 2# And it would return: [-4, -2, 0, 2, 4]returnrange(1- n, n, 2)
# Min Moves to Obtain String Without 3 Identical Consecutive Letters
# You are given a string S consisting of N letters ‘a’ and/or ‘b’.# In one move, you can swap one letter for the other (‘a’ for ‘b’ or ‘b’ for ‘a’).# Write a function solution that, given such a string S, returns the minimum number# of moves required to obtain a string containing no instances of three identical# consecutive letters.
# time complexity: O(n) because of the one while loop# space complexity: O(1) since this all takes up only one unit of spacedefcalculate_current_moves(start_sub,end_sub): sub_length = end_sub - start_sub# get current number of moves to add to total current_moves = sub_length //3# add current number of moves to totalreturn current_movesdefcalculate_min_moves(string):# initialize start and end of first possible subsequence start_sub =0 end_sub =1# initialize counter for number of moves moves =0# initialize string length length =len(string)# loop until index of subsequence end gets to end of stringwhile end_sub < length:# if index of subsequence end is at least one after startif string[end_sub]!= string[start_sub]:# add current number of moves to total moves +=calculate_current_moves(start_sub, end_sub)# move to end of current subsequence start_sub = end_sub# new end of subsequence = 1 after current start end_sub +=1# in cases where sub-sequence ends the string# add current number of moves to total moves +=calculate_current_moves(start_sub, end_sub)return moves
# checks whether IP digits are valid or notdefis_valid(possible_ip):# splitting at period ip_address = possible_ip.split(".")# checking for corner casesfor subaddress in ip_address:# get length of subaddress length_subaddress =len(subaddress)# get int of subaddress int_subaddress =int(subaddress)# get first digit of subaddress first_digit = subaddress[0]# if length > 3 OR subaddress int is outside 0-255 OR# if length > 1 AND subaddress int is 0 OR# if length > 1 AND subaddress int is NOT 0 and first digit is 0# return false for invalid ipif length_subaddress >3or int_subaddress <0or int_subaddress >255:returnFalseelif length_subaddress >1and int_subaddress is0:returnFalseelif length_subaddress >1and int_subaddress isnot0and first_digit is"0":returnFalse# else return true for valid ipreturnTrue
# converts string to IP addressdefconvert_string_to_ip(string):# get string length length =len(string)# if string of digits > 12, it's not an IP; return empty arrayif length >12:return []# else set current possible ip as string AND current_possible_ip = string# initialize empty valid ip list valid_ip_list = []# loop through possible ips:# first period loopfor i inrange(1, length -2):# second period loopfor j inrange(i +1, length -1):# third period loopfor k inrange(j +1, length):# add first period to ip to check begin_to_k = current_possible_ip[:k] k_to_end = current_possible_ip[k:] current_possible_ip = begin_to_k +"."+ k_to_end# add second period to ip to check begin_to_j = current_possible_ip[:j] j_to_end = current_possible_ip[j:] current_possible_ip = begin_to_j +"."+ j_to_end# add third period to ip to check begin_to_i = current_possible_ip[:i] i_to_end = current_possible_ip[i:] current_possible_ip = begin_to_i +"."+ i_to_end# if current combination is valid, add to valid ip list is_ip_valid =is_valid(current_possible_ip)if is_ip_valid: valid_ip_list.append(current_possible_ip)# reset current possible id to original string before looping again current_possible_ip = string# return valid ip listreturn valid_ip_listA ="25525511135"# B = "25505011535"print(convert_string_to_ip(A))# print(convert_string_to_ip(B))
# Given a string, what is the minimum number of adjacent swaps required to convert a string into# a palindrome.# If not possible, return -1."""Example 1: Input: "mamad" | Output: 3Example 2: Input: "asflkj" | Output: -1Example 3: Input: "aabb" | Output: 2Example 4: Input: "ntiin" | Output: 1 Explanation: swap 't' with 'i' => "nitin""""
# time complexity: O(n^2)# space complexity: O(1)defmin_swap(string):# convert string to list list_of_string =list(string)# check if list_of_string can be palindrome odd =0 letter = [0] *26for i in list_of_string:# get unicode char of current letter unicode_i =ord(i)# get unicode char of letter 'a' unicode_a =ord("a")# get alphabet index alphabet_index = unicode_i - unicode_a# get current letter count for each letter in string letter[alphabet_index]+=1for l in letter:if l &1==1: odd +=1if odd >1:return-1 i, j, res =0,len(list_of_string)-1,0while i < j:if list_of_string[i]== list_of_string[j]: i, j = i +1, j -1continue t = j -1# find same letter with list_of_string[i] from right to leftwhile t > i and list_of_string[t]!= list_of_string[i]: t -=1# if t == i, means this is the only letter in the list_of_string, should be swap to the middle# otherwise should be swap to the position of j target =len(list_of_string)//2if t == i else jwhile t < target:# swap tmp = list_of_string[t] list_of_string[t]= list_of_string[t +1] list_of_string[t +1]= tmp res, t = res +1, t +1return resprint(min_swap("racecra"))
# Longest Substring Without 3 Contiguous Occurrences of Letter
# Given a string s containing only a and b, find longest substring of s such that# s does not contain more than two contiguous occurrences of a and b.
## time complexity: O(n)## space complexity: O(1)"""Example 1: Input: "aabbaaaaabb" | Output: "aabbaa"Example 2: Input: "aabbaabbaabbaa" | Output: "aabbaabbaabbaa""""deflongest_substring(s):# initialize final string final_string ="" length =len(s) x =0# loop through swhilelen(s)>=2: beginning = s[0] middle = s[1]iflen(s)>2: end = s[2]# if current index + 1 != value of current indexif beginning != middle:# add value of current index to final string final_string = final_string + beginning# if current index + 1 == value of current indexelif beginning == middle:# check current index + 2# if current index + 2 == value of current indexif beginning == end:# add value of current & current + 1 to final string final_string = final_string + beginning + middle# return stringreturn final_string# if current index + 2 != value of current indexelse:# add value of current & current + 1 to final string final_string = final_string + beginning + middle# add 1 to index s = s[2:]eliflen(s)==2: final_string = final_string + beginning + middle# return stringreturn final_string
# Mixed sorting"""Given a list of integers nums, sort the array such that:All even numbers are sorted in increasing orderAll odd numbers are sorted in decreasing orderThe relative positions of the even and odd numbers remain the sameExample 1Inputnums = [8, 13, 11, 90, -5, 4]Output[4, 13, 11, 8, -5, 90]ExplanationThe even numbers are sorted in increasing order, the odd numbers are sorted in decreasing number, and the relative positions were [even, odd, odd, even, odd, even] and remain the same after sorting."""
# solutionimport unittestdefmixed_sorting(nums): positions = [] odd = [] even = [] sorted_list = []for i in nums:if i %2==0: even.append(i) positions.append("E")else: odd.append(i) positions.append("O") even.sort() odd.sort() odd.reverse() j, k =0,0for i inrange(len(nums)):if positions[i]=="E":while j <len(even): sorted_list.append(even[j]) j +=1breakelse:while k <len(odd): sorted_list.append(odd[k]) k +=1breakreturn sorted_list
# Lexicographically Smallest String
# Lexicographically smallest string formed by removing at most# one character.
# Example 1: Input: "abczd" | Output: "abcd"
## time complexity: O(n)## space complexity: O(1)deflexi_smallest(s): length =len(s) length_one_short = length -1for x inrange(length_one_short): i_one_short = x -1 x_one_long = x +1if s[x]> s[x_one_long]:return s[:x]+ s[x_one_long:]return s[:-1]
# abcdprint(lexi_smallest("abczd"))
# String Without 3 Identical Consecutive Letters
# Write a function solution that, given a string S of N lowercase English letters,# returns a string with no instances of three identical consecutive letters,# obtained from S by deleting the minimum possible number of letters."""Examples:Given S = “eedaaad” , the function should return “eedaad” . One occurrence of letter a is deleted.Given S = “xxxtxxx” , the function should return “xxtxx” . Note that letter x can occur more than three times in the returned string, if the occurrences are not consecutive.Given S = “uuuuxaaaaxuuu” , the function should return “uuxaaxuu”."""
# Write an efficient algorithm for the following assumptions:# N is an integer within the range [1..200,000]# string S consists only of lowercase letters (a-z)
## time complexity: O(n)## space complexity: O(1)defno_three_consecutive(s): final_string = s[0:2] length =len(s)# loop through original stringfor x inrange(2, length): string_x = s[x] string_x_one_short = s[x -1] string_x_two_short = s[x -2]if string_x == string_x_one_short and string_x == string_x_two_short:# don't append if previous chars are samecontinueelse: final_string += string_xreturn final_string
# You are given a string s of length n containing only characters a and b.# A substring of s called a semi-alternating substring if it does not# contain three identical consecutive characters.# Return the length of the longest semi-alternating substring.
# Example 1: Input: "baaabbabbb" | Output: 7# Explanation: "aabbabb"# Example 2: Input: "abaaaa" | Output: 4# Explanation: "abaa"
# time complexity: O(n)# space complexity: O(1)deflongest_semialternating_ss(s): length =len(s)ifnot s or length ==0:return0if length <3:return length beginning =0 end =1# first character comparison_char = s[0]# count the occurrence of the first char count_first_char =1 max_length =1while end < length: end_char = s[end]if end_char == comparison_char:# add one to char count count_first_char +=1# if char found at least two timesif count_first_char ==2: x = end - beginning +1if x > max_length: max_length = xelif count_first_char >2:# reset beginning pointer beginning = end -1else: comparison_char = end_char count_first_char =1if end - beginning +1> max_length: max_length = end - beginning +1 end +=1return max_length
# alternate solutiondeflongest_semi(s): max_length =0 left =0for right inrange(len(s)):if right - left +1>=3and s[right]== s[right -1]== s[right -2]: left = right -1 max_length =max(max_length, right - left +1)return max_length
# Alexa is given n piles of equal or unequal heights.# In one step, Alexa can remove any number of boxes from# the pile which has the maximum height and try to make# it equal to the one which is just lower than the maximum# height of the stack.# Determine the minimum number of steps required to make all of# the piles equal in height.
# Example 1: Input: piles = [5, 2, 1] | Output: 3"""Explanation: Step 1: reducing 5 -> 2 [2, 2, 1] Step 2: reducing 2 -> 1 [2, 1, 1] Step 3: reducing 2 -> 1 [1, 1, 1]So final number of steps required is 3."""
## time complexity: O(n)## space complexity: O(1)defmin_steps_equal_piles(piles): steps =0 length =len(piles)if piles == []:return0else:# get sorted list sorted_piles =set(piles) sorted_piles =sorted(sorted_piles)# get min, max and 2nd max minimum = sorted_piles[0] second_largest = sorted_piles[-2] max_pile = sorted_piles[-1]# subtract from max to equal 2nd max# repeat until all equal second maxfor x inrange(length):if piles[x]== max_pile: difference = max_pile - second_largest piles[x]= piles[x]- difference steps +=1# loop again to make second max equal to minfor x inrange(length):if piles[x]!= minimum: difference = piles[x]- minimum piles[x]= piles[x]- difference steps +=1# return # of stepsreturn steps
# 3print(min_steps_equal_piles([5, 2, 1]))
# Day of Week That Is k Days Later
# Days of the week are represented as three-letter strings.# "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"# Write a javaScript function solution that, given a string# S representing the day of the week and an integer K# (between 0 and 500), returns the day of the week that# is K days later.
# For example, given S = "Wed" and K = 2, the function# should return "Fri".# Given S = "Sat" and K = 23, the function should return# "Mon".
## time complexity: O(1)## space complexity: O(1)defk_days_later(s,k): days_of_week = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] remainder = k %7 s_index = days_of_week.index(s) move_forward = remainder + s_indexif move_forward <7:return days_of_week[move_forward]else: correct_day_index = move_forward -7return days_of_week[correct_day_index]
# Max Inserts to Obtain String Without 3 Consecutive 'a'
# Write a function solution that, given a string S# consisting of N characters, returns the maximum# number of letters 'a' that can be inserted into# S (including at the front and end of S) so that# the resulting string doesn't contain 3 consecutive# letters 'a'.
# If string S already contains the substring "aaa", then# your function should return -1."""Examples:1. Given S = "aabab", the function should return 3, because a string "aabaabaa" can be made.2. Given S = "dog", the function should return 8, because a string "aadaaoaagaa" can be made.3. Given S = "aa", the function should return 0, because no longer string can be made.4. Given S= "baaaa", the function should return -1, because there is a substring "aaa"."""
# In a given grid, each cell can have one of three values:
# the value 0 representing an empty cell;# the value 1 representing a fresh orange;# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
# Return the minimum number of minutes that must elapse until no cell has a fresh orange.# If this is impossible, return -1 instead.
# Input: [[2,1,1],[1,1,0],[0,1,1]]# Output: 4
# Input: [[2,1,1],[0,1,1],[1,0,1]]# Output: -1# Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only# happens 4-directionally.
# Input: [[0,2]]# Output: 0# Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
# 1 <= grid.length <= 10# 1 <= grid[0].length <= 10# grid[i][j] is only 0, 1, or 2deforanges_rotting(grid): minute_count =0defcreate_set(grid,target_value): result =set()for y inrange(len(grid)):for x inrange(len(grid[0])):if grid[y][x] == target_value: result.add((x, y))return result# create a set of rotten & fresh orange locations rotten_os =create_set(grid, 2) fresh_oranges =create_set(grid, 1) length_fresh =len(fresh_oranges)# For each time interval iterationwhile length_fresh >0: going_bad =set()# loop through fresh oranges and create a set going badfor x, y in fresh_oranges: up_cell = (x -1, y) down_cell = (x +1, y) left_cell = (x, y -1) right_cell = (x, y +1)if ( up_cell in rotten_osor down_cell in rotten_osor left_cell in rotten_osor right_cell in rotten_os ): currently_going_bad = (x, y) going_bad.add(currently_going_bad)# if none are going bad, it's impossible length_gb =len(going_bad)if length_gb ==0:return-1# remove oranges going bad from fresh and add to rotten fresh_oranges.difference_update(going_bad) rotten_os.update(going_bad) minute_count +=1 length_fresh =len(fresh_oranges)return minute_count
# If i can exchange 3 empty bottles for one full bottle, given that i have 18 full milk bottles# initially, how many milk bottles can i drink?
# Generalize this for 'n' bottlesdefbottles(n): bottles_to_drink =int((3* n -1) /2)return bottles_to_drinkprint(bottles(18))
# find the largest BST subtree in a given binary tree# https://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
# Given a Binary Tree, write a function that returns the size of the largest subtree which# is also a Binary Search Tree (BST).
# If the complete Binary Tree is BST, then return the size of whole tree.classBinarySearchTree:def__init__(self,value): self.value = value self.left =None self.right =Nonedeflargest_BST(self):# Set the initial values for calling# largestBSTUtil() Min = [999999999999] # For minimum value in right subtree Max = [-999999999999] # For maximum value in left subtree max_size = [0] # For size of the largest BST is_bst = [0]largestBSTUtil(node, Min, Max, max_size, is_bst)return max_size[0]# largestBSTUtil() updates max_size_ref[0]# for the size of the largest BST subtree.# Also, if the tree rooted with node is# non-empty and a BST, then returns size of# the tree. Otherwise returns 0.deflargestBSTUtil(node,min_ref,max_ref,max_size_ref,is_bst_ref):# Base Caseif node ==None: is_bst_ref[0]=1# An empty tree is BSTreturn0# Size of the BST is 0 Min =999999999999# A flag variable for left subtree property# i.e., max(root.left) < root.data left_flag =False# A flag variable for right subtree property# i.e., min(root.right) > root.data right_flag =False ls, rs =0,0# To store sizes of left and# right subtrees# Following tasks are done by recursive# call for left subtree# a) Get the maximum value in left subtree# (Stored in max_ref[0])# b) Check whether Left Subtree is BST or# not (Stored in is_bst_ref[0])# c) Get the size of maximum size BST in# left subtree (updates max_size[0]) max_ref[0]=-999999999999 ls =largestBSTUtil(node.left, min_ref, max_ref, max_size_ref, is_bst_ref)if is_bst_ref[0]==1and node.data > max_ref[0]: left_flag =True# Before updating min_ref[0], store the min# value in left subtree. So that we have the# correct minimum value for this subtree Min = min_ref[0]# The following recursive call does similar# (similar to left subtree) task for right subtree min_ref[0]=999999999999 rs =largestBSTUtil(node.right, min_ref, max_ref, max_size_ref, is_bst_ref)if is_bst_ref[0]==1and node.data < min_ref[0]: right_flag =True# Update min and max values for the# parent recursive callsif Min < min_ref[0]: min_ref[0]= Minif node.data < min_ref[0]:# For leaf nodes min_ref[0]= node.dataif node.data > max_ref[0]: max_ref[0]= node.data# If both left and right subtrees are BST.# And left and right subtree properties hold# for this node, then this tree is BST.# So return the size of this treeif left_flag and right_flag:if ls + rs +1> max_size_ref[0]: max_size_ref[0]= ls + rs +1return ls + rs +1else:# Since this subtree is not BST, set is_bst# flag for parent calls is_bst_ref[0] = 0;return0
# The complete tree is not BST as 45 is in# right subtree of 50. The following subtree# is the largest BST# 60# / \# 55 70# / / \# 45 65 80print("Size of the largest BST is", largestBST(root))
# This code is contributed by PranchalK
# Return Strings That Do Not Contain Identical Neighbors
# Consider all words of length N, consisting only of letters "b' and/or "c",# that do not contain two identical neighbouring letters.# For example, "aba' is such a word but "abb" is not (two letters "b" occur# next to each other).# We are interested in finding the K alphabetically smallest words of length# N that do not contain two identical neighbouring letters.# For example, the first four words consisting of two letters are: "ab',# "ac•, "ba", "bc•.# All correct two-letters words are: "ab", "ac", "ba•, "bc", "ca•, "cb".
# Find and fix bug(s) in a given implementation of a function:
# class Solution { public String[] solution(int N, int K) }
# that, given integers N and K, retums an array of strings: the first# K words of the alphabetically sorted sequence of words of length# N, in which no two neighbouring letters are the same. If K is# bigger than the sequence's length, the entire sequence is returned.
# Examples:# 1 . Given N = 2 and K = 4, the function should retum tab", "ac", "ban,# 'bc'] as explained above.# 2. Given N = 3 and K = 20, the function should retum ['aba", •abc",# •aca", •acb", "bab", "bac", 'bca", "bcb', "cab", •cac•, "cba",# "cbcl.# 3. Given N = 5 and K = 6, the function should retum ['ababa", "ababc•,# "abaca', "abacb", "abcab", •abcac"].
# The attached code is still incorrect for some inputs.# Despite the error(s), the code may produce a correct answer for the# example test cases.# The goal of the exercise is to find and fix the bug(s) in the# implementation.# You can modify at most two lines.
# Assume that:# N is an integer within the range [1..101;# K is an integer within the range [1..100].
# In your solution, focus on correctness."""Find the size of longest subset of A, in which any 2 elements' different is divisible by M."""t = turtle.Turtle()t.circle(50)"""Problem:The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factorof a given number N?e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17."""
# def solution(n: int) -> int:defsolution(n:int=600851475143) ->int:"""Returns the largest prime factor of a given number n.>>> solution(13195) 29>>> solution(10) 5>>> solution(17) 17>>> solution(3.4) 3>>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one.>>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one.>>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int.>>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """try: n =int(n)except (TypeError,ValueError):raiseTypeError("Parameter n must be int or passive of cast to int.")if n <=0:raiseValueError("Parameter n must be greater or equal to one.") i =2 ans =0if n ==2:return2while n >2:while n % i !=0: i +=1 ans = iwhile n % i ==0: n = n / i i +=1returnint(ans)if__name__=="__main__":# print(solution(int(input().strip())))import doctest doctest.testmod()print(solution(int(input().strip())))
# Python3 program to add two numbersnumber1 =input("First number: ")number2 =input("\nSecond number: ")
# Adding two numbers# User might also enter float numberssum=float(number1)+float(number2)
# Display the sum# will print value in floatprint("The sum of {0} and {1} is {2}".format(number1, number2, sum))defsumOfSeries(n): x = n * (n +1) /2return (int)(x * x)
# Driver Functionn =5print(sumOfSeries(n))
# Program to find the ASCII value of the given characterc ="p"print("The ASCII value of '"+ c +"' is", ord(c))"""Problem:The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factorof a given number N?e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17."""
# def solution(n: int) -> int:defsolution(n:int=600851475143) ->int:"""Returns the largest prime factor of a given number n.>>> solution(13195) 29>>> solution(10) 5>>> solution(17) 17>>> solution(3.4) 3>>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one.>>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one.>>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int.>>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """try: n =int(n)except (TypeError,ValueError):raiseTypeError("Parameter n must be int or passive of cast to int.")if n <=0:raiseValueError("Parameter n must be greater or equal to one.") i =2 ans =0if n ==2:return2while n >2:while n % i !=0: i +=1 ans = iwhile n % i ==0: n = n / i i +=1returnint(ans)if__name__=="__main__":# print(solution(int(input().strip())))import doctest doctest.testmod()print(solution(int(input().strip())))import timepwd ="AKS2608"# any password u want to setdefIInd_func(): count1 =0for j inrange(5): a =0 count =0 user_pwd =input("")# password you rememberfor i inrange(len(pwd)):if user_pwd[i]== pwd[a]:# comparing remembered pwd with fixed pwd a +=1 count +=1if count ==len(pwd):print("correct pwd")breakelse: count1 +=1print("not correct")if count1 ==5: time.sleep(30)IInd_func()IInd_func()
# This program adds two numbersnum1 =1.5num2 =6.3
# Add two numberssum= num1 + num2
# Display the sumprint("The sum of {0} and {1} is {2}".format(num1, num2, sum))classNode:def__init__(self,data): self.data = data self.next =NoneclassLinked_List:def__init__(self): self.head =NonedefInsert_At_Beginning(self,new_data): new_node =Node(new_data)if self.head isNone: self.head = new_nodereturn new_node.next = self.head self.head = new_nodedefAdd_two_no(self,First,Second): prev =None temp =None carry =0while First isnotNoneor Second isnotNone: first_data =0if First isNoneelse First.data second_data =0if Second isNoneelse Second.data Sum = carry + first_data + second_data carry =1if Sum >=10else0 Sum = Sum if Sum <10else Sum %10 temp =Node(Sum)if self.head isNone: self.head = tempelse: prev.next = temp prev = tempif First isnotNone: First = First.nextif Second isnotNone: Second = Second.nextif carry >0: temp.next =Node(carry)defDisplay(self): temp = self.headwhile temp:print(temp.data, "->", end=" ") temp = temp.nextprint("None")if__name__=="__main__": First =Linked_List() Second =Linked_List() First.Insert_At_Beginning(6) First.Insert_At_Beginning(4) First.Insert_At_Beginning(9) Second.Insert_At_Beginning(2) Second.Insert_At_Beginning(2)print("First Linked List: ") First.Display()print("Second Linked List: ") Second.Display() Result =Linked_List() Result.Add_two_no(First.head, Second.head)print("Final Result: ") Result.Display()
# This program adds two numbersnum1 =1.5num2 =6.3
# Add two numberssum= num1 + num2
# Display the sumprint("The sum of {0} and {1} is {2}".format(num1, num2, sum))a =5b =6c =7# a = float(input('Enter first side: '))# b = float(input('Enter second side: '))# c = float(input('Enter third side: '))
# calculate the semi-perimeters = (a + b + c) /2
# calculate the areaarea = (s * (s - a) * (s - b) * (s - c)) **0.5print("The area of the triangle is %0.2f"% area)a =5b =6c =7# a = float(input('Enter first side: '))# b = float(input('Enter second side: '))# c = float(input('Enter third side: '))
# calculate the semi-perimeters = (a + b + c) /2
# calculate the areaarea = (s * (s - a) * (s - b) * (s - c)) **0.5print("The area of the triangle is %0.2f"% area)
# Python Program to find the area of triangle when all three side-lengths are known!a =5b =6c =7
# Uncomment below to take inputs from the user# a = float(input('Enter first side: '))# b = float(input('Enter second side: '))# c = float(input('Enter third side: '))
# Program to convert binary to decimaldefbinaryToDecimal(binary):""">>> binaryToDecimal(111110000) 496>>> binaryToDecimal(10100) 20>>> binaryToDecimal(101011) 43 """ decimal, i, n =0,0,0while binary !=0: dec = binary %10 decimal = decimal + dec *pow(2, i) binary = binary //10 i +=1print(decimal)binaryToDecimal(100)from threading import Threadfrom Background import Backgroundfrom PIL.Image importopenas openImagefrom PIL.ImageTk import PhotoImageclassBird(Thread):""" Classe para criar um pássaro """ __tag ="Bird" __isAlive =None __going_up =False __going_down =0 __times_skipped =0 __running =False decends =0.00390625 climbsUp =0.0911458333def__init__(self,background,gameover_function,*screen_geometry,fp="bird.png",event="<Up>",descend_speed=5 ):# Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamávelifnotisinstance(background, Background):raiseTypeError("The background argument must be an instance of Background." )ifnotcallable(gameover_function):raiseTypeError("The gameover_method argument must be a callable object.")# Instância os parâmetros self.__canvas = background self.image_path = fp self.__descend_speed = descend_speed self.gameover_method = gameover_function# Recebe a largura e altura do background self.__width = screen_geometry[0] self.__height = screen_geometry[1]# Define a decida e subida do pássaro com base na altura do background self.decends *= self.__height self.decends =int(self.decends +0.5) self.climbsUp *= self.__height self.climbsUp =int(self.climbsUp +0.5)# Invoca o método construtor de Thread Thread.__init__(self)# Calcula o tamanho do pássaro com base na largura e altura da janela self.width = (self.__width //100) *6 self.height = (self.__height //100) *11# Carrega e cria a imagem do pássaro no background self.__canvas.bird_image = self.getPhotoImage( image_path=self.image_path, width=self.width, height=self.height, closeAfter=True, )[0] self.__birdID = self.__canvas.create_image( self.__width //2, self.__height //2, image=self.__canvas.bird_image, tag=self.__tag, )# Define evento para fazer o pássaro subir self.__canvas.focus_force() self.__canvas.bind(event, self.jumps) self.__isAlive =TruedefbirdIsAlive(self):""" Método para verificar se o pássaro está vivo """return self.__isAlivedefcheckCollision(self):""" Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo """# Recebe a posição do pássaro no background position =list(self.__canvas.bbox(self.__tag))# Se o pássaro tiver ultrapassado a borda de baixo do background, ele será declarado mortoif position[3]>= self.__height +20: self.__isAlive =False# Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado mortoif position[1]<=-20: self.__isAlive =False# Dá uma margem de erro ao pássaro de X pixels position[0]+=int(25/78* self.width) position[1]+=int(25/77* self.height) position[2]-=int(20/78* self.width) position[3]-=int(10/77* self.width)# Define os objetos a serem ignorados em colisões ignored_collisions = self.__canvas.getBackgroundID() ignored_collisions.append(self.__birdID)# Verifica possíveis colisões com o pássaro possible_collisions =list(self.__canvas.find_overlapping(*position))# Remove das possíveis colisões os objetos ignoradosfor _id in ignored_collisions:try: possible_collisions.remove(_id)except:continue# Se houver alguma colisão o pássaro morreiflen(possible_collisions)>=1: self.__isAlive =Falsereturnnot self.__isAlivedefgetTag(self):""" Método para retornar a tag do pássaro """return self.__tag@staticmethoddefgetPhotoImage(image=None,image_path=None,width=None,height=None,closeAfter=False ):""" Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @param image_path: Diretório da imagem @param width: Largura da imagem @param height: Altura da imagem @param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma """ifnot image:ifnot image_path:return# Abre a imagem utilizando o caminho dela image =openImage(image_path)# Será redimesionada a imagem somente se existir um width ou heightifnot width: width = image.widthifnot height: height = image.height# Cria uma nova imagem já redimensionada newImage = image.resize([width, height])# Cria um photoImage photoImage =PhotoImage(newImage)# Se closeAfter for True, ele fecha as imagensif closeAfter:# Fecha a imagem nova newImage.close() newImage =None# Fecha a imagem original image.close() image =None# Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem originalreturn photoImage, newImage, imagedefjumps(self,event=None):""" Método para fazer o pássaro pular """# Verifica se o pássaro saiu da área do background self.checkCollision()# Se o pássaro estiver morto, esse método não pode ser executadoifnot self.__isAlive ornot self.__running: self.__going_up =Falsereturn# Declara que o pássaro está subindo self.__going_up =True self.__going_down =0# Move o pássaro enquanto o limite de subida por animação não tiver excedidoif self.__times_skipped < self.climbsUp:# Move o pássaro para cima self.__canvas.move(self.__tag, 0, -1) self.__times_skipped +=1# Executa o método novamente self.__canvas.after(3, self.jumps)else:# Declara que o pássaro não está mais subindo self.__going_up =False self.__times_skipped =0defkill(self):""" Método para matar o pássaro """ self.__isAlive =Falsedefrun(self):""" #Método para iniciar a animação do passáro caindo """ self.__running =True# Verifica se o pássaro saiu da área do background self.checkCollision()# Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05if self.__going_down < self.decends: self.__going_down +=0.05# Executa a animação de descida somente se o pássaro estiver vivoif self.__isAlive:# Executa a animação de descida somente se o pássaro não estiver subindoifnot self.__going_up:# Move o pássaro para baixo self.__canvas.move(self.__tag, 0, self.__going_down)# Executa novamente o método self.__canvas.after(self.__descend_speed, self.run)# Se o pássaro estiver morto, será executado um método de fim de jogoelse: self.__running =False self.gameover_method()from itertools import productdeffindPassword(chars,function,show=50,format_="%s"): password =None attempts =0 size =1 stop =Falsewhilenot stop:# Obtém todas as combinações possíveis com os dígitos do parâmetro "chars".for pw inproduct(chars, repeat=size): password ="".join(pw)# Imprime a senha que será tentada.if attempts % show ==0:print(format_ % password)# Verifica se a senha é a correta.iffunction(password): stop =Truebreakelse: attempts +=1 size +=1return password, attemptsdefgetChars():""" Método para obter uma lista contendo todas as letras do alfabeto e números. """ chars = []# Acrescenta à lista todas as letras maiúsculasfor id_ inrange(ord("A"), ord("Z") +1): chars.append(chr(id_))# Acrescenta à lista todas as letras minúsculasfor id_ inrange(ord("a"), ord("z") +1): chars.append(chr(id_))# Acrescenta à lista todos os númerosfor number inrange(10): chars.append(str(number))return chars
# Se este módulo não for importado, o programa será testado.# Para realizar o teste, o usuário deverá inserir uma senha para ser encontrada.if__name__=="__main__":import datetimeimport time# Pede ao usuário uma senha pw =input("\n Type a password: ")print("\n")deftestFunction(password):global pwif password == pw:returnTrueelse:returnFalse# Obtém os dígitos que uma senha pode ter chars =getChars() t = time.process_time()# Obtém a senha encontrada e o múmero de tentativas password, attempts =findPassword( chars, testFunction, show=1000, format_=" Trying %s" ) t = datetime.timedelta(seconds=int(time.process_time() - t))input(f"\n\n Password found: {password}\n Attempts: {attempts}\n Time: {t}\n")defbubblesort(list):# Swap the elements to arrange in orderfor iter_num inrange(len(list) -1, 0, -1):for idx inrange(iter_num):if list[idx]> list[idx +1]: temp = list[idx] list[idx]= list[idx +1] list[idx +1]= templist= [19,2,31,45,6,11,121,27]bubblesort(list)print(list)defbubble_sort(Lists):for i inrange(len(Lists)):for j inrange(len(Lists) -1):# We check whether the adjecent number is greater or notif Lists[j]> Lists[j +1]: Lists[j], Lists[j +1]= Lists[j +1], Lists[j]
# Lets the user enter values of an array and verify by himself/herselfarray = []array_length =int(input(print("Enter the number of elements of array or enter the length of array")))for i inrange(array_length): value =int(input(print("Enter the value in the array"))) array.append(value)bubble_sort(array)print(array)defres(R1,R2):sum= R1 + R2if option =="series":returnsumelse:return (R1 * R2) / (R1 + R2)Resistance1 =int(input("Enter R1 : "))Resistance2 =int(input("Enter R2 : "))option =str(input("Enter series or parallel :"))print("\n")R =res(Resistance1, Resistance2)print("The total resistance is", R)defres(R1,R2):sum= R1 + R2if option =="series":returnsumelse:return (R1 * R2) / (R1 + R2)Resistance1 =int(input("Enter R1 : "))Resistance2 =int(input("Enter R2 : "))option =str(input("Enter series or parallel :"))print("\n")R =res(Resistance1, Resistance2)print("The total resistance is", R)from tkinter import*import calendarroot =Tk()# root.geometry("400x300")root.title("Calendar")
# from numpy import asarrayimport timedefhit(key): pyautogui.press(key)returndefisCollide(data):# for cactusfor i inrange(329, 425):for j inrange(550, 650):if data[i, j]<100:hit("up")return# Draw the rectangle for birds# for i in range(310, 425):# for j in range(390, 550):# if data[i, j] < 100:# hit("down")# return# returnif__name__=="__main__":print("Hey.. Dino game about to start in 3 seconds") time.sleep(2)# hit('up')whileTrue: image = ImageGrab.grab().convert("L") data = image.load()isCollide(data)# print(aarray(image))# Draw the rectangle for cactus# for i in range(315, 425):# for j in range(550, 650):# data[i, j] = 0# # # # # Draw the rectangle for birds# for i in range(310, 425):# for j in range(390, 550):# data[i, j] = 171# image.show()# breakimport pyautogui # pip install pyautoguifrom PIL import Image, ImageGrab # pip install pillow
# from numpy import asarrayimport timedefhit(key): pyautogui.press(key)returndefisCollide(data):# for cactusfor i inrange(329, 425):for j inrange(550, 650):if data[i, j]<100:hit("up")return# Draw the rectangle for birds# for i in range(310, 425):# for j in range(390, 550):# if data[i, j] < 100:# hit("down")# return# returnif__name__=="__main__":print("Hey.. Dino game about to start in 3 seconds") time.sleep(2)# hit('up')whileTrue: image = ImageGrab.grab().convert("L") data = image.load()isCollide(data)# print(aarray(image))# Draw the rectangle for cactus# for i in range(315, 425):# for j in range(550, 650):# data[i, j] = 0# # # # # Draw the rectangle for birds# for i in range(310, 425):# for j in range(390, 550):# data[i, j] = 171# image.show()# breakimport pickleimport tensorflow as tfmodel = tf.keras.models.Sequential( [ tf.keras.layers.Conv2D(16, (3, 3), activation="relu", input_shape=(200, 200, 3) ), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(16, (3, 3), activation="relu"), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(16, (3, 3), activation="relu"), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation="relu"), tf.keras.layers.Dense(1, activation="sigmoid"), ])model.summary()from tensorflow.keras.optimizers import RMSpropmodel.compile(optimizer=RMSprop(lr=0.001), loss="binary_crossentropy", metrics=["acc"])from tensorflow.keras.preprocessing.image import ImageDataGeneratortrain_datagen =ImageDataGenerator(rescale=1/255)train_generator = train_datagen.flow_from_directory("../Classification_human-or-horse", target_size=(200, 200), batch_size=222, class_mode="binary",)model.fit_generator(train_generator, steps_per_epoch=6, epochs=1, verbose=1)filename ="myTf1.sav"pickle.dump(model, open(filename, "wb"))from tkinter import Tkfrom tkinter.filedialog import askopenfilenamefrom keras.preprocessing import imageimport numpy as npTk().withdraw()filename =askopenfilename()print(filename)img = image.load_img(filename, target_size=(200, 200))x = image.img_to_array(img)x = np.expand_dims(x, axis=0)images = np.vstack([x])classes = model.predict(images, batch_size=10)print(classes[0])if classes[0]>0.5:print(filename +" is a human")else:print(filename +" is a horse")
# libraraiesimport pytubeimport sysclassYouTubeDownloder:def__init__(self): self.url =str(input("Enter the url of video : ")) self.youtube = pytube.YouTube( self.url, on_progress_callback=YouTubeDownloder.onProgress ) self.showTitle()defshowTitle(self):print("title : {0}\n".format(self.youtube.title)) self.showStreams()defshowStreams(self): self.streamNo =1for stream in self.youtube.streams:print("{0} => resolution:{1}/fps:{2}/type:{3}".format( self.streamNo, stream.resolution, stream.fps, stream.type ) ) self.streamNo +=1 self.chooseStream()defchooseStream(self): self.choose =int(input("please select one : ")) self.validateChooseValue()defvalidateChooseValue(self):if self.choose inrange(1, self.streamNo): self.getStream()else:print("please enter a correct option on the list.") self.chooseStream()defgetStream(self): self.stream = self.youtube.streams[self.choose -1] self.getFileSize()defgetFileSize(self):global file_size file_size = self.stream.filesize /1000000 self.getPermisionToContinue()defgetPermisionToContinue(self):print("\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps, ) )ifinput("do you want it ?(defualt = (y)es) or (n)o ")=="n": self.showStreams()else: self.main()defdownload(self): self.stream.download()@staticmethoddefonProgress(stream=None,chunk=None,remaining=None): file_downloaded = file_size - (remaining /1000000)print(f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r", )defmain(self):try: self.download()exceptKeyboardInterrupt:print("Canceled. ") sys.exit(0)if__name__=="__main__":try:YouTubeDownloder()exceptKeyboardInterrupt:passexceptExceptionas e:print(e)number =int(input())counter =0while number >0: number = number //10print(number) counter +=1print("number of digits :", counter)
# dictionary initialization using {}mydict ={"a":1,"b":2}
# add new (key,value) pairmydict["c"]=3
# modify existing (key,value) pairmydict["a"]=5
# remove (key,value) pairmydict.pop("a")
# get length of the dictionaryprint(len(mydict))
# iteration through keysfor key in mydict.keys():print(key)
# iteration through valuesfor value in mydict.values():print(value)
# iteration through (key,value) pairsfor key, value in mydict.items():print(key, value)
#!/usr/bin/env python2# -*- coding:utf8 -*-"""A simple Python 3.4+ script to send a text message to a Free Mobile phone.- Warning: it only works in France to a French number, using the mobile operator Free Mobile.- Warning: some initial configuration is required before running this script (see the error messages).- Copyright 2014-20 Lilian Besson- License MIT.Examples--------$ FreeSMS.py --helpGives help$ FreeSMS.py "I like using Python to send SMS to myself from my laptop -- and it's free thanks to Free Mobile !"Will send a test message to your mobile phone.- Last version? Take a look to the latest version at https://github.com/Naereen/FreeSMS.py- Initial Copyright : José - Juin 2014 (http://eyesathome.free.fr/index.php/tag/freemobile/)- License: MIT License Copyright (c) 2014-21 Lilian Besson (Naereen), https://github.com/Naereen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""from__future__import print_function
# Use sys.version to be compatible with Python 2import sys
# Use os.getenv to see try to emulate os.path.expanduser if neededimport os
# Use time to sleep and get string for today current hourimport time
# Use JSON to pretty print a dictionaryimport json
# Use base64 to not keep plaintext files of the number, username and password in your homeimport base64today = time.strftime("%H:%M:%S %Y-%m-%d")try:from os.path import expanduserexceptImportError:print("Warning, os.path.expanduser is not available, trying to use os.getenv('USER') = {} ...".format( os.getenv("USER") ) )defexpanduser(s):""" Try to simulate the os.path.expanduser function. """return"/home/"+ os.getenv("USER")+"/"+ sif sys.version_info < (3,0):from urllib import urlencodefrom urllib2 import urlopen, HTTPErrorelse:from urllib3.request import urlencodefrom urllib.request import urlopenfrom urllib.error import HTTPErrortry:try:from ansicolortags import printcexceptImportError:print("Optional dependancy (ansicolortags) is not available, using regular print function." )print(" You can install it with : 'pip install ansicolortags' (or sudo pip)..." )from ANSIColors import printcexceptImportError:print("Optional dependancy (ANSIColors) is not available, using regular print function." )print(" You can install it with : 'pip install ANSIColors-balises' (or sudo pip)..." )defprintc(*a,**kw):""" Fake function printc. ansicolortags or ANSIColors are not installed... Install ansicolortags from pypi (with 'pip install ansicolortags') """print(*a, **kw)deftestSpecialFile(name,number=""):""" Test if the hidden file '~/.smsapifreemobile_name.b64' exists and decodes (base64) correctly. """assert name in ["number","user","password", ],"Error: unknown or incorrect value for 'name' for the function openSpecialFile(name) ..."# printc("<cyan>Testing the hidden file <white>'<u>~/.smsapifreemobile_{}.b64<U>'<cyan>...<white>".format(name)) # DEBUGtry:withopen(expanduser("~/") +".smsapifreemobile_"+ name + number +".b64" )as f: variable = base64.b64decode(f.readline()[:-1])while variable[-1]=="\n": variable = variable[:-1]returnTrueexceptOSError:returnFalsedefopenSpecialFile(name,number=""):""" Open the hidden file '~/.smsapifreemobile_name.b64', read and decode (base64) and return its content. """assert name in ["number","user","password", ],"Error: unknown or incorrect value for 'name' for the function openSpecialFile(name) ..."printc("<cyan>Opening the hidden file <white>'<u>~/.smsapifreemobile_{}.b64<U>'<cyan>, read and decode (base64) and return its content...<white>".format( name ) )try:withopen(expanduser("~/") +".smsapifreemobile_"+ name + number +".b64" )as f: variable = base64.b64decode(f.readline()[:-1])while variable[-1]=="\n": variable = variable[:-1]return variableexceptOSError:printc("<red>Error: unable to read the file '~/.smsapifreemobile_{}.b64' ...<white>".format( name ) )printc("<yellow>Please check that it is present, and if it not there, create it:<white>" )if name =="number":print("To create '~/.smsapifreemobile_number.b64', use your phone number (like '0612345678', not wiht +33), and execute this command line (in a terminal):" )printc("<black>echo '0612345678' | base64 > '~/.smsapifreemobile_number.b64'<white>".format() )elif name =="user":print("To create '~/.smsapifreemobile_user.b64', use your Free Mobile identifier (a 8 digit number, like '83123456'), and execute this command line (in a terminal):" )printc("<black>echo '83123456' | base64 > '~/.smsapifreemobile_user.b64'<white>".format() )elif name =="password":print("To create '~/.smsapifreemobile_password.b64', go to this webpage, https://mobile.free.fr/moncompte/index.php?page=options&show=20 (after logging to your Free Mobile account), and copy the API key (a 14-caracters string on [a-zA-Z0-9]*, like 'H6ahkTABEADz5Z'), and execute this command line (in a terminal):" )printc("<black>echo 'H6ahkTABEADz5Z' | base64 > '~/.smsapifreemobile_password.b64<white>' ".format() )numbers = []
#: Number (not necessary)# number = base64.b64decode(open(expanduser('~') + ".smsapifreemobile_number.b64").readline()[:-1])# if number[-1] == '\n':# number = number[:-1]number =openSpecialFile("number")numbers.append(number)iftestSpecialFile("number", "2"): number2 =openSpecialFile("number", "2") numbers.append(number2)
# Detect languagelanguage = os.getenv("LANG")language = language[0:2]if language else"fr"
# Maximum size that can be sent# XXX Reference: https://en.wikipedia.org/wiki/Short_Message_Service#Message_size# "6 to 8 segment messages are the practical maximum"MAX_SIZE =4*159STR_MAX_SIZE ="4*159"if language =="fr": errorcodes ={400:"Un des paramètres obligatoires est manquant.",402:"Trop de SMS ont été envoyés en trop peu de temps.",403:"""Le service n'est pas activé sur l'espace abonné, ou login / clé incorrect.Allez sur '<black>https://mobile.free.fr/moncompte/index.php?page=options&show=20<white>' svp, et activez l'option correspondate.""",500:"Erreur côté serveur. Veuillez réessayez ultérieurement.",1:"Le SMS a été envoyé sur votre mobile ({}).".format(number)iflen(numbers)<=1else"Le SMS a été envoyé sur vos numéros ({}).".format(numbers),"toolong":"<red>Attention<white> : le message est trop long (+ de <black>{}<white> caracters, soit plus de 3 SMS).".format( STR_MAX_SIZE ),}else: errorcodes ={400:"One of the necessary parameter is missing.",402:"Too many SMSs has been sent in a short time (you might be a spammer!).",403:"""Access denied: the service might not be activated on the online personnal space, or login/password is wrong.Please go on '<black>https://mobile.free.fr/moncompte/index.php?page=options&show=20<white>' please, and enable the corresponding option.""",500:"Error from the server side. Please try again later.",1:"The SMS has been sent to your mobile ({}).".format(number)iflen(numbers)<=1else"The SMS has been sent to all your mobile numbers ({}).".format(numbers),"toolong":"<red>Warning<white>: message is too long (more than <black>{}<white> caracters, so more than 3 SMS).".format( STR_MAX_SIZE ),}defsend_sms(text="Empty!",secured=True,sleep_duration=0):""" Sens a free SMS to the user identified by [user], with [password]. :user: Free Mobile id (of the form [0-9]{8}), :password: Service password (of the form [a-zA-Z0-9]{14}), :text: The content of the message (a warning is displayed if the message is bigger than 480 caracters) :secured: True to use HTTPS, False to use HTTP. Returns a boolean and a status string. """# DONE split the text into smaller pieces if length is too big (automatically, or propose to do it ?)iflen(text)> MAX_SIZE:printc(errorcodes["toolong"]) nb_sub_messages =len(text)/ MAX_SIZEprintc("\n<red>Warning<white>: message will be split in <red>{} piece{}<white> of size smaller than <black>{} characters<white>...".format( nb_sub_messages +1, "s"if nb_sub_messages >0else"", MAX_SIZE ) )printc(" <magenta>Note that new lines and other information can be lost!<white>" )for i, index inenumerate(range(0, len(text), MAX_SIZE)): answer =send_sms(text[index : index + MAX_SIZE])printc("For piece #{} of the message, the answer is:\n <magenta>{}<white>...\n".format( i +1, answer[1] ) )return answer# raise ValueError(errorcodes["toolong"])# Read user and password users = []#: Identification Number free mobile user =openSpecialFile("user") users.append(user)iftestSpecialFile("user", "2"): user2 =openSpecialFile("user", "2") users.append(user2) passwords = []#: Password password =openSpecialFile("password") passwords.append(password)iftestSpecialFile("password", "2"): password2 =openSpecialFile("password", "2") passwords.append(password2)printc("\n<green>Your message is:<white>\n<yellow>"+ text +"<white>") url ="https"if secured else"http"# Sending to all the numbers results = []for (user, password) inzip(users, passwords): dictQuery ={"user": user,"pass": password,"msg": text} string_query = json.dumps(dictQuery, sort_keys=True, indent=4) string_query = string_query.replace(password, "*"*len(password))printc("\nThe web-based query to the Free Mobile API (<u>{}://smsapi.free-mobile.fr/sendmsg?query<U>) will be based on:\n{}.".format( url, string_query ) )if sleep_duration >0:printc("\nSleeping for <red>{}<reset><white> seconds before querying the API...".format( sleep_duration ) )try: time.sleep(sleep_duration)exceptKeyboardInterruptas e:printc("<red>You interrupted the process of sending this message, skipping to next one (or stopping now)...<reset><white>" )else:printc("\nDone sleeping for <red>{}<reset><white> seconds, it's time to query the API !".format( sleep_duration ) ) query =urlencode(dictQuery) url +="://smsapi.free-mobile.fr/sendmsg?{}".format(query)try:urlopen(url) results.append((0, errorcodes[1]))except HTTPError as e:ifhasattr(e, "code"): results.append((e.code, errorcodes[e.code]))else:print("Unknown error...") results.append((2, "Unknown error..."))# Now we return the list of resultsreturn resultsdefmain(argv):""" Main function. Use the arguments of the command line (sys.argv). """# TODO use docopt to handle the command line arguments! Cf. http://docopt.org/# TODO can docopt handle a cli documentation with ansicolortags tags in it? Cf. http://ansicolortags.rtfd.io/# Manual handing of the command line argumentsif"-h"in argv or"--help"in argv:printc("""<green>FreeSMS.py<white> --help|-h | -f file | [--sleep] body of the messageA simple Python script to send a text message to a Free Mobile phone.The message should be smaller than 480 caracters.<u>Examples:<U><black>$ FreeSMS.py --help<white>Print this help message!<black>$ FreeSMS.py -f MyMessageFile.txt<white>Try to send the content of the file MyMessageFile.txt.<black>$ FreeSMS.py "I like using Python to send me SMS from my laptop -- and it"s free thanks to Free !"<white>Will send a test message to your mobile phone.<black>$ FreeSMS.py --sleep 1 "This option makes the script sleep for one minute"<white>Sleep one minute.<magenta>Copyright 2014-21 Lilian Besson (License MIT)<white><b>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.<reset><white>""" )return [(0,None)] sleep =False sleep_duration =15# in secondsif"--sleep"in argv: sleep =True index = argv.index("--sleep")if index +1<len(argv):try: sleep_duration =int(argv[index +1])except:printc("<red>Unable to get a sleep duration value from the command line argument ('{}' does not convert to an integer).".format( argv[index +1] ) )# DEBUGelse: argv.pop(index)# remove sleep_duration argv.pop(index)# remove "--sleep"if"-f"in argv:try:withopen(argv[argv.index("-f") +1], "r")as filename: text ="".join(filename.readlines())[:-1]exceptExceptionas e:print(e)print("Trying to use the rest of the arguments to send the text message...") text =" ".join(argv)else:if argv:# Text of the SMSifisinstance(argv, list): text =" ".join(argv)elifisinstance(argv, str): text = argvelse:printc("<Warning>argv seems to be of unknown type (not list, not str, but {}) ...".format(type(argv) ) ) text = argv text = text.replace("\\n", "\n")# Durty hack to have true new lines in the messageelse: text ="""Test SMS sent from {machinename} with FreeSMS.py (the {date}). (a Python 2.7+ / 3.4+ script by Lilian Besson, open source, you can find the code at https://github.com/Naereen/FreeSMS.py or https://perso.crans.org/besson/bin/FreeSMS.py) For any issues, reach me by email at jarvis[at]crans[dot]org !"""# FIXED Check that this is working correctly! machinename ="jarvis"# Default name!try: machinename =open("/etc/hostname").readline()[:-1]exceptOSError:print("Warning: unknown machine name (file '/etc/hostname' not readable?)..." ) machinename ="unknown machine" text = text.format(date=today, machinename=machinename) text = text.replace("[at]", "@").replace("[dot]", ".") answers =send_sms(text, sleep_duration=sleep_duration)return answersif__name__=="__main__":# from doctest import testmod # DEBUG ?# testmod(verbose=False) # DEBUG ? results =main(sys.argv[1:]) first_result = results[0] code, message = first_result sys.exit(int(code))defadd(param1,param2):return param1 + param2