I’m new to python, and this question appeared on a course.
JavaScript
x
18
18
1
def calculate_storage(filesize):
2
block_size = 4096
3
# Use floor division to calculate how many blocks are fully occupied
4
full_blocks = filesize // block_size
5
# Use the modulo operator to check whether there's any remainder
6
partial_block_remainder = filesize % block_size
7
# Depending on whether there's a remainder or not, return
8
# the total number of bytes required to allocate enough blocks
9
# to store your data.
10
if partial_block_remainder > 0:
11
return full_blocks+1
12
return full_blocks
13
14
print(calculate_storage(1)) # Should be 4096
15
print(calculate_storage(4096)) # Should be 4096
16
print(calculate_storage(4097)) # Should be 8192
17
print(calculate_storage(6000)) # Should be 8192
18
This was my answer. The question was this: If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size?
With the base code here:
JavaScript
1
18
18
1
def calculate_storage(filesize):
2
block_size = 4096
3
# Use floor division to calculate how many blocks are fully occupied
4
full_blocks = ___
5
# Use the modulo operator to check whether there's any remainder
6
partial_block_remainder = ___
7
# Depending on whether there's a remainder or not, return
8
# the total number of bytes required to allocate enough blocks
9
# to store your data.
10
if partial_block_remainder > 0:
11
return ___
12
return ___
13
14
print(calculate_storage(1)) # Should be 4096
15
print(calculate_storage(4096)) # Should be 4096
16
print(calculate_storage(4097)) # Should be 8192
17
print(calculate_storage(6000)) # Should be 8192
18
Advertisement
Answer
you need to multiply the return values by the block size:
JavaScript
1
18
18
1
def calculate_storage(filesize):
2
block_size = 4096
3
# Use floor division to calculate how many blocks are fully occupied
4
full_blocks = filesize // block_size
5
# Use the modulo operator to check whether there's any remainder
6
partial_block_remainder = filesize % block_size
7
# Depending on whether there's a remainder or not, return
8
# the total number of bytes required to allocate enough blocks
9
# to store your data.
10
if partial_block_remainder > 0:
11
return block_size * (full_blocks + 1)
12
return block_size * full_blocks
13
14
print(calculate_storage(1)) # Should be 4096
15
print(calculate_storage(4096)) # Should be 4096
16
print(calculate_storage(4097)) # Should be 8192
17
print(calculate_storage(6000)) # Should be 8192
18
returns:
JavaScript
1
5
1
4096
2
4096
3
8192
4
8192
5