Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list.
A node in a singly linked list should have two attributes: val
and
next. val is the value of the current node
next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list.
Assume all nodes in the linked list are 0-indexed.
Implement these functions in your linked list class:
classListNode:def__init__(self,val=None): self.val = val self.next =NoneclassMyLinkedList:def__init__(self):""" Initialize your data structure here. """ self.head =Nonedefget(self,index:int) ->int:""" Get the value of the index-th node in the linked list. If the index is invalid, return -1. """if index >=0and index <=1000: counter =0 node = self.headwhile node:if counter == index:return node.val node = node.next counter +=1return-1defaddAtHead(self,val:int) ->None:""" Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. """if self.head !=None: newnode =ListNode(val) newnode.next = self.head self.head = newnodeelse: self.head =ListNode(val)defaddAtTail(self,val:int) ->None:""" Append a node of value val to the last element of the linked list. """if self.head !=None: newnode =ListNode(val) node = self.headwhile node:if node.next ==None: node.next = newnodebreak node = node.nextelse: self.head =ListNode(val)defaddAtIndex(self,index:int,val:int) ->None:# Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.if index >=0and index <=1000: node = self.head counter =1if index ==0:if self.head !=None: newnode =ListNode(val) newnode.next = self.head self.head = newnodeelse: self.head =ListNode(val)else:while node:if index == counter: newnode =ListNode(val) temp = node.next node.next = newnode node.next.next = tempbreak node = node.next counter +=1else:passdefdeleteAtIndex(self,index:int) ->None:#Delete the index-th node in the linked list, if the index is valid. node = self.head counter =1if node.next !=None:if index ==0: temp = node.next self.head = tempelse:while node:if index == counter and node.next !=None: node.next = node.next.nextbreak node = node.next counter +=1
Define Count Vowels Function
Count the number of vowels in the user input string using for loop and while loop
Now, let’s define a function named countVowels() which accepts one argument as a string where we need to count Vowels in it.
So, declare a variable count and initialize to 0 which keeps the track of vowel count.
count = 0
Now before counting the vowels, first make sure the string is completely lowercase because we are checking vowels from the list where we declared vowel in lowercase only.
So keep it in mind to the first convert string to lowercase and for that, we are going to use lower() function of Python.
sentence = sentence.lower()
So, we have converted the string to lowercase, now traverse through the string and compare each character of string in the list of vowels whether the character is present in the list or not.
If the character is present in the list, then we simply increment the count variable by 1 otherwise continue to the loop without incrementing the count variable.
And at last, after traversing through the string, return the count variable back to the function call.
for c in sentence:
if c in ['a', 'e', 'i', 'o', 'u']:
count += 1
return count
Define the Main Condition
Now, we have defined the Count Vowel function above which calculates the count of the number of vowels in the string.
So after this, ask the user to enter string which needs to pass to this above function and then print the count for the vowel.
if __name__ == '__main__':
userInput = str(input("Enter the string to check for vowels: "))
count = countVowels(userInput)
print('Vowel Count: ',count)
Code
#Using While Loop'''def countVowels(sentence): count = 0 sentence = sentence.lower() i = 0 while(i<len(sentence)): if sentence[i] in ['a', 'e', 'i', 'o', 'u']: count += 1 i+=1; return count'''#Using For LoopdefcountVowels(sentence): count =0 sentence = sentence.lower()for c in sentence:if c in ['a','e','i','o','u']: count +=1return countif__name__=='__main__': userInput =str(input("Enter the string to check for vowels: ")) count =countVowels(userInput)print('Vowel Count: ',count)
Output
Define Binary Number to Decimal Function
Let’s create a new function to Convert Binary to a Decimal Number named binaryToDecimal() which accepts Binary as an argument.
So let’s store the argument in the separate variables to use that at last while printing what the actual data is.
Along with this, create two new variables “decimal” and “i” and initialized both to 0.
binary1 = binary
decimal, i = 0, 0
Now create a while loop that loops till the number which we received as an argument not become 0.
So the logic behind converting is that first in each iteration, we need to get the last digit of Number either 1 or 0 and then multiply that last digit with the power of 2 and counter i.
So, the base condition for this function is if the number is equal to 0, then we return output as 0 because of how we calculate the Series if the number is 0.
if number == 0: return 0
Now, let’s declare two variables named fibonacci0 for number 0 and initialize it to 0 and fibonacci1 for number 1 and initialize it to 1.
fibonacci0, fibonacci1 = 0, 1
Now create a FOR Loop to calculate till the n-th term, so the logic is simple as that assigns the sum of fibonacci0 and fibonacci1 to fibonacci1 and assigns fibonacci0 the value of fibonacci1 at last step.
And after calculating n-th term, simply returns the fibonacci1 because which keeps tracks till the n-th term.
def fibonacci_without_recursion(number):
if number == 0: return 0
fibonacci0, fibonacci1 = 0, 1
print(fibonacci0, end = ' ')
for i in range(2, number + 1):
print(fibonacci1, end = ' ')
fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1
return fibonacci1
Define the Main Method
Now let’s create a main method where we need to call these both methods that we have created above for calculating Fibonacci Series using Recursion as well as by For Loops.
First, ask for the user input to enter any number. If the number is less than 0, then simply returns an error message printing that the “Number must be Positive Number“.
if __name__ == '__main__':
userInput = int(input('Enter the number upto which calculate fibonnaci series: '))
if(userInput<0):
print("Number must be Positive Number")
else:
print("\nUsing Recursion:")
for i in range(userInput + 1):
print(fibonacci_with_recursion(i),end=' ')
print("\n\nUsing LOOP:")
print(fibonacci_without_recursion(userInput))
Source Code
def fibonacci_with_recursion(number):
if number <= 1:
return number
else:
return (fibonacci_with_recursion(number - 1) + fibonacci_with_recursion(number - 2))
def fibonacci_without_recursion(number):
if number == 0: return 0
fibonacci0, fibonacci1 = 0, 1
print(fibonacci0, end = ' ')
for i in range(2, number + 1):
print(fibonacci1, end = ' ')
fibonacci1, fibonacci0 = fibonacci0 + fibonacci1, fibonacci1
return fibonacci1
if __name__ == '__main__':
userInput = int(input('Enter the number upto which calculate fibonnaci series: '))
if(userInput<0):
print("Number must be Positive Number")
else:
print("\nUsing Recursion:")
for i in range(userInput + 1):
print(fibonacci_with_recursion(i),end=' ')
print("\n\nUsing LOOP:")
print(fibonacci_without_recursion(userInput))