Tutorialspoint

Python to convert a list of characters into a string

letters = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
sentence = ''.join(letters)
print(sentence)

Python to count upper and lower case

def countUpperAndLowerCase(sentence):
    upper = 0
    lower = 0
    for i in sentence:
        if i >= 'A' and i <= 'Z':
            upper += 1
        elif i >= 'a' and i <= 'z':
            lower += 1
    print("Upper case: " + str(upper))
    print("Lower case: " + str(lower))

countUpperAndLowerCase("Hello World")

Python to replace a word with asterisks in a sentence

def replaceWithAsterisk(sent, word):
    # Use the replace function to find and replace the word with 
    # same number of asterisks as the length of the word.
    return sent.replace(word, "*" * len(word))

sent = "Go feed all the ducks in the lake"
censored_sent = replaceWithAsterisk(sent, "ducks")

print(censored_sent)

Python to replace characters

def replaceUsingMapAndLambda(sent, a1, a2):
    # We create a lambda that only works if we input a1 or a2 and swaps them.
    newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
    return ''.join(newSent)

print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))

Python Dictionary to sum ASCII values

sent = "hi people of the world"
words = sent.split(" ")

result = {}

# Calculate sum of ascii values for every word
for word in words:
    result[word] = sum(map(ord,word))

totalSum = 0
# Create an array with ASCII sum of words using the dict
sumForSentence = [result[word] for word in words]

print ('Sum of ASCII values:')
print (' '.join(map(str, sumForSentence)))

print ('Total of all ASCII values in sentence: ',sum(sumForSentence))

Python to sort out words in ascending order

sent = "mary has a very beautiful dog"
# Split on space.
my_arr = sent.split(" ")
print(my_arr)

# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)

# This time, my_arr won't change in place, rather, it'll be sorted 
# and a new instance will be assigned to new_arr
print(my_arr)

Python lexicographical order

my_arr = [
   "hello",
   "apple",
   "actor",
   "people",
   "dog"
]
print(my_arr)

# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)

# This time, my_arr won't change in place, rather, it'll be sorted 
# and a new instance will be assigned to new_arr
print(my_arr)

Python words starting with capital letters

import re

# Find and capture all capital letters in a group and make that replacement
# using the \1 preceded by a space. Strip the string to remove preceding 
# space before first letter.
separated_str = re.sub("([A-Z])", " \\1", "AReallyLongVariableNameInJava").strip()
print(separated_str)

NumPy array from the numerical ranges

import numpy as np 
# dtype set 
x = np.arange(5, dtype = float)
print x

UnitTest Framework Skip Test

import unittest

class suiteTest(unittest.TestCase):
   a = 50
   b = 40
   
   def testadd(self):
      """Add"""
      result = self.a+self.b
      self.assertEqual(result,100)

   @unittest.skipIf(a>b, "Skip over this routine")
   def testsub(self):
      """sub"""
      result = self.a-self.b
      self.assertTrue(result == -10)
   
   @unittest.skipUnless(b == 0, "Skip over this routine")
   def testdiv(self):
      """div"""
      result = self.a/self.b
      self.assertTrue(result == 1)

   @unittest.expectedFailure
   def testmul(self):
      """mul"""
      result = self.a*self.b
      self.assertEqual(result == 0)

if __name__ == '__main__':
   unittest.main()

1 2 3 4 5 6 7 ... 63 Next
Advertisements
Loading...