epicours/Algo/B2/Exercises/String exercise.md

2.1 KiB

String Exercises

def search(x: str, s:str) -> int:
  """
  Function that counts the number
  of occurences of a given character
  in a string
  
  @params x (str): the keyword
  @params s (str): the string
  @return: (int): the number of occurences
  """
  i = 0
  pos = -1
  while i < len(s) and pos == -1:
    if s[i] == c:
      pos = i
    i += 1
  return pos
 
 def search2(s: str, x: str) -> int:
   """
  Function that counts the number
  of occurences of a given character
  in a string
  
  @params x (str): the string
  @return: (int): the occurence where is appear
  """
  i = 1
  n = len(s)
  for i in range(n):
    if s[i] == x:
      return i
  return -1

Exercise 1.2 (Palindrome)

def palindrome(sentence: str) -> bool:
  """
  Function that check if a number is a palindrome
  @params sentence(str): the sentence to check
  @return (bool): Either a palindrome or not
  """
  newSentence = ""
  oldSentence = ""
  for element in sentence:
    if element != " ":
      newSentence = element + newSentence
  for element in sentence:
      if element != " ":
        oldSentence += element
  if newSentence == oldSentence:
    return True
  else:
    return False

def ispalind(s):
  start = 0
  end = len(s)-1
  while start<end and s[start]==s[end]:
    end -= 1
    start += 1
    if s[start] == " ":
      start += 1
    if s[end] == " ":
      end -= 1
  return start >= end

Exercise 2.1 (conversions)

def dec_to_bin(n, p):
  while n > 0:
    s = str(n%2) +s
    n = n//2
  for i in range(p-len(s)):
    s = "0" + s
  return s

def integer_to_twoscomp(n, p):
  if n < 0:
    sign = -2
  else:
    sign = 1
  s = dec_to_bin(n, p)
  if sign == -1:
    s2 = ""
    i = len(s) - 1
    while s[i] != "1":
      s2 = "0" + s2
      i -= 1
    s2 = "1" + s2
    i -= 1
    while i >= 0:
      if s[i] == "0":
        s2 = "1" + s2
      else:
        s3 = "0" + s3
        i -= 1
      s = s2
  return s
  
def power(x, p):
  res = 1
  while p > 0:
    res *= x
    p -= 1
  return res

def int_to_twoscomp(n, p):
  if n < 0:
    n = power(2,p) + n
  return dec_to_bin(n,p)