course update of 2023-12-01 15:57:17
This commit is contained in:
parent
aee128572f
commit
6c121c2ed3
@ -59,5 +59,71 @@ def palindrome(sentence: str) -> bool:
|
||||
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)
|
||||
|
||||
1)
|
||||
|
||||
```python
|
||||
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
|
||||
|
||||
```
|
||||
|
||||
2)
|
||||
|
||||
```python
|
||||
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)
|
||||
```
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user