# Comp Sci -python

Watch this thread
Announcements
Thread starter 6 years ago
#1
This thread is for every python to post their questions and answers. It is created to improve your skills by tackling each other questions
Other python beginners can post their answers

Q: Write a function called pattern_sum that receives two single digit positive integers, (k and m) as parameters and calculates and returns the total sum as:
k + kk + kkk + .... (the last number in the sequence should have m digits)
For example, if the two integers are:

(4, 5)
Your function should return the total sum of:
4 + 44 + 444 + 4444 + 44444
Notice the last number in this sequence has 5 digits. The return value should be:
49380

A:
Spoiler:
Show
Code:
```def two( a, b):
total = 0
for i in range (1, b + 1):
d = str(a) * i
total += int(d)
return total```
2
reply
Thread starter 6 years ago
#2
Q: Write a function named unique_common that accepts two lists both of which contain integers as parameters and returns a sorted list (ascending order) which contains unique common elements from both the lists. If there are no common elements between the two lists, then your function should return the keyword None

For example, if two of the lists received by the function are:

([5, 6, -7, 8, 8, 9, 9, 10], [2, 4, 8, 8, 5, -7])
You can see that elements 5, -7, and 8 are common in both the first list and the second list and that the element 8 occurs twice in both lists. Now you should return a sorted list (ascending order) of unique common elements like this:
[-7, 5, 8]
if the two lists received by the function are:
([5, 6, 7, 0], [3, 2, 3, 2])
Since, there are no common elements between the two lists, your function should return the keyword
None

A:
Spoiler:
Show

Code:
```def unique_common(lst, lst1):
copy = list()
for i in lst:
if i in lst1:
if i not in copy:
copy.append(i)
copy.sort()
if not copy:
return None
return copy```
0
reply
Thread starter 6 years ago
#3
Q: Write a function named find_gcd that accepts a list of positive integers and returns their greatest common divisor (GCD). Your function should return 1 as the GCD if there are no common factors between the integers. Here are some examples:

if the list was

[12, 24, 6, 18]
then your function should return the GCD:
6

A:
Spoiler:
Show
Code:
```def gcd(lst):
copy =list()
x = min(lst)
copy1 =[]
for j in lst:
x = min(lst)
while x >0:
if x == 0:
break
if j % x == 0:
copy.append(x)
x -= 1
for i in copy:
if copy.count(i) == len(lst):
if i in copy1:
continue
else:
copy1.append(i)
if not copy1:
return 1
return max(copy1)```
0
reply
Thread starter 6 years ago
#4
Q: Write a function that accepts an input string consisting of alphabetic characters and removes all the trailing whitespace of the string and returns it without using any .strip() method. For example if:

input_string = " Hello "
then your function should return an output string such as:
output_string = " Hello"

A:
Spoiler:
Show
def trail(a):
b = None
for i in range((len(a))-1, 0, -1):
if a[i] != " ":
b = i
break
c = a[:b+1]
return c
0
reply
Thread starter 6 years ago
#5
Q: Write a function which accepts an input string consisting of alphabetic characters and spaces and returns the string with all the spaces removed. Do NOT use any string methods for this problem.

A:
Spoiler:
Show

def space(astring):
str1 = ""
for i in astring:
if i != " ":
str1 += i
return str1
0
reply
Thread starter 6 years ago
#6
Q:Write a function which accepts an input string and returns a string where the case of the characters are changed, i.e. all the uppercase characters are changed to lower case and all the lower case characters are changed to upper case. The non-alphabetic characters should not be changed. Do NOT use the string methods upper(), lower(), or swap().
A:
Spoiler:
Show
def change(string1):
word =""
lst = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U' , 'V', 'W', 'X', 'Y', 'Z']
lst1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in string1:
if i in lst:
index1 = lst.index(i)
word += lst1[index1]
elif i in lst1:
index2 = lst1.index(i)
word += lst[index2]
else:
word += i
return word
0
reply
Thread starter 6 years ago
#7
Q:
Write a function that takes a string consisting of alphabetic characters as input argument and returns True if the string is a palindrome. A palindrome is a string which is the same backward or forward. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character.

A:
Spoiler:
Show
# Type your code here
def drome(str1):
a = 0
b = -1
str1 = str1.lower()
lst = str1

for i in range(len(lst), 0, -1):
if not lst:
return True
elif lst[a] == lst[ b]:
lst = lst[a + 1: b]
b += -1
a += 1

return False
0
reply
Thread starter 6 years ago
#8
Q: Write a function that accepts a string and a character as input and returns the count of all the words in the string which start with the given character. Assume that capitalization does not matter here. You can assume that the input string is a sentence i.e. words are separated by spaces and consists of alphabetic characters.

A:
Spoiler:
Show
def start(str1, chr1):
word = ""
num = 0
str1 =str1.lower()
chr1 = chr1.lower()
lst = str1.split()
for i in lst:
word = word.join(i)
if chr1 == word[0]:
num += 1
word = ""
return num
0
reply
6 years ago
#9
One liners.

(Original post by bigmansouf)
Q: Write a function called pattern_sum that receives two single digit positive integers, (k and m) as parameters and calculates and returns the total sum as:
k + kk + kkk + .... (the last number in the sequence should have m digits)
Code:
```def pattern_sum(k, m):
return sum([int(str(k) * a) for a in range(1, m + 1)])```
(Original post by bigmansouf)
Q: Write a function named unique_common that accepts two lists both of which contain integers as parameters and returns a sorted list (ascending order) which contains unique common elements from both the lists. If there are no common elements between the two lists, then your function should return the keyword None
Code:
```def unique_common(a, b):
return sorted(list(set(a).intersection(set(b)))) or None```
(Original post by bigmansouf)
Q:Write a function that takes a string consisting of alphabetic characters as input argument and returns True if the string is a palindrome. A palindrome is a string which is the same backward or forward. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character.
Code:
```def case_insensitive_palindrome(s):
return s.lower() == s.lower()[::-1]```
(Original post by bigmansouf)
Q: Write a function which accepts an input string consisting of alphabetic characters and spaces and returns the string with all the spaces removed. Do NOT use any string methods for this problem.
Code:
```def strip_whitespace(s):
return reduce(lambda x, y: x + y, [x for x in s if x != " "])```
(Original post by bigmansouf)
Q: Write a function that accepts a string and a character as input and returns the count of all the words in the string which start with the given character. Assume that capitalization does not matter here. You can assume that the input string is a sentence i.e. words are separated by spaces and consists of alphabetic characters.
Code:
```def count_first_letter(s, c):
return len([word for word in s.split(' ') if word[0] == c])```
.
0
reply
Thread starter 6 years ago
#10
(Original post by Push_More_Button)
One liners.
.
Amazing

how long did it take you to mastr python
how do you get to one liners style of coding
because i have seen it on stack overflow but not in most beginners python book

which books can help me improve my skills

thank you
0
reply
Thread starter 6 years ago
#11
Q: Write a function named count_consonants that receives a string as parameter and returns the total count of the consonants in the string. Consonants are all the characters in the english alphabet except for 'a', 'e', 'i', 'o', 'u'. If the same consonant repeats multiple times you should count all of them. Note that capitalization and punctuation does not matter here i.e. a lower case character should be considered the same as an upper case character.

A:
Code:
```def cons(str1):
str1 = str1.replace(" ", "").lower()
print str1
a = ["a", "e", "i", "o", "u"]
count = 0
for i in str1:
if  i in a:
continue
count += 1
return count```
0
reply
6 years ago
#12
(Original post by bigmansouf)
Amazing

how long did it take you to mastr python
how do you get to one liners style of coding
because i have seen it on stack overflow but not in most beginners python book

which books can help me improve my skills

thank you
I've been using Python for over two years now and it's by far my favourite language so I've practised with it lots. I'm also currently working as a Python Developer so I use it rather often.

There's a lot of great functionality in the standard library and it's possible to do quite a lot with it which is obviously helpful for writing nice short bits of Pythonic code, but in pretty much all cases readability trumps one liners or magic in the real world as it's easier to maintain and modify so don't aim to write one liners, try to write nice readable Pythonic code.

Best tip I can give you is practise and to read up on what's possible to do with the standard library and data structures. (Lists and dictionaries are super powerful btw if you look at them as more than a simple data storage)
0
reply
6 years ago
#13
(Original post by bigmansouf)
Q: Write a function named find_gcd that accepts a list of positive integers and returns their greatest common divisor (GCD). Your function should return 1 as the GCD if there are no common factors between the integers. Here are some examples:

if the list was

[12, 24, 6, 18]
then your function should return the GCD:
6

A:
Spoiler:
Show
Code:
```def gcd(lst):
copy =list()
x = min(lst)
copy1 =[]
for j in lst:
x = min(lst)
while x >0:
if x == 0:
break
if j % x == 0:
copy.append(x)
x -= 1
for i in copy:
if copy.count(i) == len(lst):
if i in copy1:
continue
else:
copy1.append(i)
if not copy1:
return 1
return max(copy1)```
You can also use Euclid's algorithm and the fact that gcd(a,b,c) = gcd(a, gcd(b,c)). This way, the runtime won't be harmed by suspicious inputs, such as two very large primes.
0
reply
Thread starter 6 years ago
#14
(Original post by Jooooshy)
You can also use Euclid's algorithm and the fact that gcd(a,b,c) = gcd(a, gcd(b,c)). This way, the runtime won't be harmed by suspicious inputs, such as two very large primes.
thanks
0
reply
Thread starter 6 years ago
#15
(Original post by Push_More_Button)
I've been using Python for over two years now and it's by far my favourite language so I've practised with it lots. I'm also currently working as a Python Developer so I use it rather often.

There's a lot of great functionality in the standard library and it's possible to do quite a lot with it which is obviously helpful for writing nice short bits of Pythonic code, but in pretty much all cases readability trumps one liners or magic in the real world as it's easier to maintain and modify so don't aim to write one liners, try to write nice readable Pythonic code.

Best tip I can give you is practise and to read up on what's possible to do with the standard library and data structures. (Lists and dictionaries are super powerful btw if you look at them as more than a simple data storage)
thank you
0
reply
6 years ago
#16
(Original post by bigmansouf)
Q: Write a function named count_consonants that receives a string as parameter and returns the total count of the consonants in the string. Consonants are all the characters in the english alphabet except for 'a', 'e', 'i', 'o', 'u'. If the same consonant repeats multiple times you should count all of them. Note that capitalization and punctuation does not matter here i.e. a lower case character should be considered the same as an upper case character.
Spoiler:
Show
Code:
```def count_consonants(s):
return sum([0 if letter in {"a", "e", "i", "o", "u"} else 1 for letter in s.replace(" ", "").lower()])```
0
reply
Thread starter 6 years ago
#17
Q: Write a function named find_longest_word that receives a string as parameter and returns the longest word in the string. Assume that the input to this function is a string of words consisting of alphabetic characters that are separated by space(s). In case of a tie between some words return the last one that occurs.

A:
Spoiler:
Show
def find(str1):
str1 = str1.lower()
lst = str1.split()
longest = 0
longest_word = 0
for i in lst:
count = 0
for j in range(0, len(i)):
count += 1

if count >= longest:
longest = count
longest_word = i

return longest_word
0
reply
Thread starter 6 years ago
#18
(Original post by Push_More_Button)
I've been using Python for over two years now and it's by far my favourite language so I've practised with it lots. I'm also currently working as a Python Developer so I use it rather often.

There's a lot of great functionality in the standard library and it's possible to do quite a lot with it which is obviously helpful for writing nice short bits of Pythonic code, but in pretty much all cases readability trumps one liners or magic in the real world as it's easier to maintain and modify so don't aim to write one liners, try to write nice readable Pythonic code.

Best tip I can give you is practise and to read up on what's possible to do with the standard library and data structures. (Lists and dictionaries are super powerful btw if you look at them as more than a simple data storage)
0
reply
6 years ago
#19
(Original post by bigmansouf)
Q: Write a function named test_for_anagrams that receives two strings as parameters, both of which consist of alphabetic characters and returns True if the two strings are anagrams, False otherwise. Two strings are anagrams if one string can be constructed by rearranging the characters in the other string using all the characters in the original string exactly once. For example, the strings "Orchestra" and "Carthorse" are anagrams because each one can be constructed by rearranging the characters in the other one using all the characters in one of them exactly once. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character
Spoiler:
Show
Code:
```def test_for_anagrams(a, b):
if len(a) != len(b):
return 0
a, b = a.lower(), b.lower()
for letter in a:
if letter not in b:
return 0
b = b[:b.index(letter)] + b[b.index(letter) + 1:]
return 1```
0
reply
Thread starter 6 years ago
#20
(Original post by morgan8002)
Spoiler:
Show
Code:
```def test_for_anagrams(a, b):
if len(a) != len(b):
return 0
for letter in a:
if letter not in b:
return 0
b = b[:b.index(letter)] + b[b.index(letter) + 1]:
return 1```
i put a different answer my mistake
0
reply
X

Write a reply...
Reply
new posts
Back
to top
Latest

### Oops, nobody has postedin the last few hours.

Why not re-start the conversation?

see more

### Poll

Join the discussion

#### How did The Student Room help you with your university application?

Talking to current university students (18)
19.15%
Talking to peers going through the same thing (32)
34.04%
Speaking to student ambassadors from the universities (5)
5.32%
Speaking to staff members from universities (2)
2.13%
Using the personal statement builder, library or helper service (9)
9.57%
Reading articles about what steps to take (18)
19.15%
Learning about/speaking to Student Finance England (4)
4.26%
Something else (tell us in the thread) (6)
6.38%

View All
Latest

### Oops, nobody has postedin the last few hours.

Why not re-start the conversation?