Tuesday, 13 September 2022

How to Convert a List to a String in Python

 

The join function is one of the simplest methods to convert a list to a string in python. The main point to keep in mind while using this function is that the join function can convert only those lists into string that contains only string as its elements. 

list=['hello', 'how', 'are', 'you']

print(list)  # this will print the list

str=' '.join(list)

print(str)

'hello how are you'  # this is a string


Now, there may be cases where a list will contain elements of data type other than string. In such cases ,the join function can not be used directly. For a cases, like these, str() function will first be used to convert the other data type into a string and then further, the join function will be applied.

list=['1','2','3']

str1=' '.join (str(e) for e in list)

print(str1)   # this will print a string


Wednesday, 24 November 2021

Regular Expressions(REG-EX)

 

Reg -ex for  finding a pattern of digits which might resemble a telephone number in a format :

XXX-XXX-XXXX  OR  YYY.YYY.YYYY

\d{3}[.,-]\d{3}[.,-]\d{4}


Regex for some string ending with something for .eg here 1

.*1$


Regex for some string starting with something,  for .eg here 2

^2.*


Regex for some string containing  something,  for .eg here test

.*test


One of the many web-sites for testing reg-ex  is :

https://regex101.com/

Thursday, 13 February 2020

*********** PYTHON ASSIGNMENTS ********************


1-
Define a Python function remdup(l) that takes a nonempty list of integers l and removes all duplicates in l, keeping only the first occurrence of each number. For instance:

Solution

def remdup(duplicate):
  finalist=[];
  for num in duplicate:
    if num not in finalist:
        finalist.append(num);

  return finalist;

testcases:

>>> remdup([3,1,3,5,5,5]) [3, 1, 5] >>> remdup([7,3,-1,-5,-3]) [7, 3, -1, -5] >>> remdup([5,7,5,3,7,10]) [3, 5, 7, 10]



2-
Write a Python function sumsquare(l) that takes a nonempty list of integers and returns a list [odd,even], where odd is the sum of squares all the odd numbers in l and even is the sum of squares of all the even numbers in l.

Solution:

def sumsquare(list):
  flist=[];
  odd=0;
  even=0;
  for num in list:
    if num%2==0:
        even=even + num*num;
    else: 
        odd=odd+num*num;
  flist.append(odd);
  flist.append(even);
  return flist;

testcases:
>>> sumsquare([1,3,5])
[35, 0]

>>> sumsquare([2,4,6])
[0, 56]

>>> sumsquare([-1,-2,3,7])
[59, 4]

***************************************************************************************


3-
We represent scores of batsmen across a sequence of matches in a two level dictionary as follows:
{'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}
Each match is identified by a string, as is each player. The scores are all integers. 
Define a Python function orangeecap(d) that reads a dictionary d of this form and identifies the player with the highest total score. Your function should return a pair (playername,topscore) where playername is a string, the name of the player with the highest score, and topscore is an integer, the total score of playername.
The input will be such that there are never any ties for highest total score.

Solution:
def orangeecap(d): total={} for match,player in d.items(): for n in list(player.keys()): total[n]=0 for match in d.keys(): if n in d[match].keys(): total[n]=total[n]+d[match][n] o=[] o=o+sorted(total.items(), key = lambda kv:(kv[1], kv[0])) return(o[-1]);

**************************************************************************************

4-
Accept two strings as input and form a new string by removing all chars from the second string which are present in the first string. 
Print this new string as output.  Assume  all input strings are in lower case.

SOLUTION
=========
str1=input()
str2=input()
str3=''
L1=[]
L2=[]
L3=[]
for i in str1:
 L1.append(i)
for i in str2:
 L2.append(i)
for i in L1:
 for j in range(0,len(L2)):
  if i in L2:
    L2.remove(i)
str3=''.join(L2)
print(str3)

Sample in/op
testcase:1
an
adnan

d
 
testcase:2
aeiou
this is a python program
ths s  pythn prgrm
********************************************************************************

5-
Accept a positive integer n as input and print the sum of all prime numbers in the range [1, n], endpoints inclusive.

SOLUTION:
n=int(input())
L=[]

for i in range(2,n+1):
  flag=True
  for j in range(2,i+1):
   if(i%j)==0 and j<i:
     flag=False
  if flag:
   L.append(i)
#print(L)
sum=0
for i in L:
  sum=sum+i
print(sum)

testcase:1
10
17
testcase:2
100
1060

*******************************************************************

6-
The input should be four integers in four lines. The output should be a single line with all the integers separated by  single space in ascending order.


SOLUTION:
L=[]
n1=int(input())
L.append(n1)
n2=int(input())
L.append(n2)
n3=int(input())
L.append(n3)
n4=int(input())
L.append(n4)
L.sort()
for i in L:
  print(i,end=' ')
print() 

*********************************************************************

7-
Take as input 4 input lines. First and third line =names of persons . While second and fourth lines refer to  date of births of  the persons. Output should be the name of the younger person .

SOLUTION:
==========
from datetime import datetime, timedelta
n1=input()
d1=input()
n2=input()
d2=input()
L1=[]
L1=d1.split('-')
L2=[]
L2=d2.split('-')
dob1=datetime(int(L1[2]),int(L1[1]),int(L1[0]))
dob2=datetime(int(L2[2]),int(L2[1]),int(L2[0]))
ct=datetime.today()
age1=ct-dob1
age2=ct-dob2
if (age1>age2):
  print(n2)
if (age2>age1):
  print(n1)
if(age1==age2):
  if(n1>n2):
    print(n2)
  else:
    print(n1)

*******************************************************************


8-
Program to find the median of the given sample list: marks

SOLUTION:

marks=[23,25,43,12,2,1]
final=[]
while(len(marks)>0):
 least=marks[0]
#sorting the list marks
 for i in range(len(marks)):
  if marks[i]<least:
   least=marks[i]
 final.append(least)
 marks.remove(least)
print(final)  #sorted list
#median calculation
if(len(final)%2!=0):
  value=((len(final)+1)//2)
  #print(value)
  median=final[value-1]
  print(median)
else:
  value1=(len(final)//2)-1
  value2=((len(final)//2)+1)-1
  median=(final[value1]+final[value2])/2
  print(median)

************************************************************

9- 
Reading of Matrix from input. Use ',' in split if comma is given as separator and we can also use ' ' in split if the space is given as separator in the question .

dim=int(input())
A=[]
for i in range(dim):
 l=[int(eleme) for eleme in input().split(",")]
 A.append(l)
B=[]
for i in range(dim):
 l=[int(eleme) for eleme in input().split(",")]
 B.append(l)
 print(A)
 print(B)

********************************************************************

10-
Print identity matrix in the comma separated format

SOLUTION:

n=int(input())
for i in range(n):
  for j in range(n):
    if(i!=j) and j<n-1: # this has been put to avoid comma at the end #                               #of every row
      print('0',end=",")
    if(i!=j) and j==n-1:
      print('0',end="")
    if(i==j) and j<n-1:
      print('1',end=",")
    if(i==j) and j==n-1:
      print('1',end="")
  print()   # this print is to change line after every row

Input:
2
Output:
1,0
0,1

************************************************************************

11-
 Accept a positive integer as input and print the digits present in it from left to right. Each digit should be printed as a lower case word on a separate line.

d={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',0:'zero'}
#print(d)
n=int(input())
lst=[]
while(n>0):
  num=n%10
  lst.append(d[num])
  n=n//10
 # method to reverse the list
l=[]
for i in lst:
    # reversing the list
    l.insert(0, i)
for i in range(len(l)):
 print(l[i])


InputExpected Output
123
one
two
three
************************************************************************

12
Write a function named value_to_keys that accepts a dictionary d and a variable named val as arguments. It should return the list of all keys in the dictionary that have value equal to val. If the value is not present in the dictionary, the function should return the empty list.

def value_to_keys(d, val):
  l=[]
  for x in d:
  if(d[x]==val):
    l.append(x)
  return(l)

*************************************************************************

13-
Accept a ten-digit number as input. Find the number of places where the numbers 0 and 1 have been replaced by letters(o and l respectively). If there are no such replacements, print the string No mistakes. If not, print the number of mistakes   and in the next line, print the correct phone number.

n=input()
l=[]
for i in range(len(n)):
  l.append(n[i])
count=0
for i in l:
  if(i=='l') or (i=='o'):
    count=count+1
for  x in range(len(l)):
  if(l[x]=='l'):
      l[x]='1'
  if(l[x]=='o'):
      l[x]='0'

if(count!=0):
  print(count ,"mistakes")
  st=''.join(l)
  print(st)
else:
  print("No mistakes")
===============================================

Test  1

InputExpected Output 
987o35l7o4
3 mistakes
9870351704
 
 

Test  2

InputExpected Output 
9874618291
No mistakes
 
===============================================

******************************************************************

14-

Write a recursive function named counter that accepts the following arguments:

  • L: list of words.
  • word: a word, could be any string.

This function should return the number of occurrences of word in L.


def counter(L,word):

  c=0

  n=len(L)

  if n==0:

   return 0

  if L[0]==word:

     return 1+count(L[1:n],word)

  else:

    return count(L[1:n],word)


L=['a','sd','adnan','tom','tom','harry']

print(count(L,'tom'))

OUTPUT:

2




Monday, 2 July 2018

Urdu Resources For Real Beginners Who Know Hindi


1-Search for the following String in YouTube :These are series of Lectures by Nihal Usmani .They are really good 
.
.
.and so on . There are 11-12 lectures
=====================================================================
2-
In addition, 
There is a portal https://aamozish.com/ 
It has all the learning material for free ,along with phonetics and Quizzes.



Monday, 7 August 2017

NEW CAR Pre-delivery Inspection (PDI) & Check List




The Team-BHP PDI Checklist is now available as a PDF file which you can carry with you.
The file is available for download at the following link :
https://www.team-bhp.com/advice/pre-delivery-inspection-pdi-check-list




Thursday, 12 November 2015

Unable to Download WhatsApp on My Samsung MObile

Unable to Download WhatsApp on My Samsung Mobile


I am getting an Error Retrieving Information from the server when I try to Search WhatsApp from PlayStore and hit Install, then Accept And  Download.

This what I tried first

1-Unlink and relink my google account .
2-Got to Settings-->Applications-->All.
3-Clear Data for the following
      Google PlayStore
      Data Manager
      Google Service FrameWork
4-Open Playstore .Follow the popups . Try installing Whatsapp.

But it didn't work for me .

So I opened the browser and went to http://www.whatsapp.com/android/  and downloaded the whatsapp software and then Installed it .

This worked for me .

Thanks

Monday, 31 August 2015

HOW TO CONVERT NOTES FROM IMAGE TO TEXT


HOW TO  CONVERT FROM IMAGE TO TEXT


Sometimes we find many good books written in PDF format online .
There are many things in the books which we need to keep separately as notes for our future reference or for printing only the important content relevant to us .

We cannot do this as the PDF file is often COPY and PRINT protected .


Just for making notes  what I do is :

1-Open the book section which you want to jot down.
2-Open the Snipping Tool on your Windows Laptop /Dsktop.
3-Hit New on Snipping Tool .and select the text which you want to note.
4-Hit Save on the Snipping Tool.Save it as something like Notes1.png.
5-Now open any online ocr. I used  http://www.onlineocr.net/
6-Select the file as  Notes1.png and give other details on  http://www.onlineocr.net/ and hit CONVERT, your image gets converted to text


PS:This work-around is only for making small notes and not converting the whole PDF book.