Lab Practical Solutions
Show your solutions! You can paste them into chat and I
can post them here so everyone can see them. I am hoping
to see several solutions to each problem, some of which
will be different. At the top of your code, put a comment
with your name on it like so: hart21g
.
Block B
#Anya Schrader
import re
def countWords(s):
regex=r"\b"
seeker=re.compile(regex)
no_words=0
for m in seeker.finditer(s):
no_words+=1
return no_words//2
#li
def countWords(s):
"""
countWords("I eat cake") -> 3
countWords("") -> 0
countWords("0") -> 1
countWords("To be or not to be, that is the question.") -> 10"""
word_finder = re.compile(r"\w+")
number = 0
for word in re.findall(word_finder, s):
number += 1
return number
#yete
def countWords(s):
return len(s.split())
# Melissa
def countWords(s):
return s.count(" ")+1
# Carson
def countWords(s):
x = s.split()
if s.isspace() == True:
return 0
else:
return len(x)
#Melissa
def weaveStrings(s,t):
new_string = ""
for i in range(max(len(s), len(t))):
if i < len(s):
new_string += s[i]
if i < len(t):
new_string += t[i]
return new_string
# Melissa
def isPerfectNumber(n):
if n <= 2:
return False
else:
sum = 0
for i in range(1, n):
if n%i == 0:
sum += i
if n == sum:
return True
else:
return False
#Cliff
def wordCounter(s):
counter = 1
for i in s:
if i == " ":
counter = counter + 1
return print(counter)
#Melissa
def checkFileForWord(fileName, word):
found = False
with open(fileName) as f:
if word in f.read():
found = True
return found
From Alec Nipp to Everyone: (10:25 AM)
#Alec Nipp
def areAnagrams(s,t):
""" s and t are strings
return True if s and t are anagrams, case INSENSITIVE
areAnagrams('space', 'Capes') -> True
areAnagrams('spatter', 'parsers') -> False
areAngrams('dog', 'log') -> False"""
if len(s) != len(t):
return False
s = s.lower()
t = t.lower()
if countLetters(s) == countLetters(t):
return True
else:
return False
def countLetters(s):
""" s is a string
returns a dictionary containing all letters as keys and their
frequencies as the values"""
counts = {}
for char in s:
if char in counts:
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
#messier
def weaveStrings(s,t):
outstring = ""
i = 0
while len(s) > i and len(t) > i:
outstring += s[i] + t[i]
i += 1
if len(s) == i:
outstring += t[i:]
elif len(t) == i:
outstring += s[i:]
return outstring
#li
def checkFileForWord(fileName, word):
"""
fileName is a string
if the file does not exist, return False
if the file does exist, check for word being a
substring of the file; if you find it return True and
return False otherwise"""
if os.path.exists(fileName):
with open(fileName) as f:
return re.findall(word, f.read()) != []
else:
return False
#Rujula
import os
def checkFileForWord(fileName, word):
existence=False
if os.path.exists("fileName"):
if os.path.isfile("fileName"):
file=open("fileName","r")
text=file.read()
if word in text:
existence=True
return existence
#James
def weaveStrings(s,t):
if len(s) > len(t):
for x in range(len(t)):
out += s[x] + t[x]
out += s[len(t):]
else:
for x in range(len(s)):
out += s[x] + t[x]
out += t[len(s):]
return out
#Timothy
def areAnagrams(s,t):
s = s.lower()
t = t.lower()
if len(s) == len(t):
for i in range(len(s)):
if t.find(s[i]) == -1:
return False
t.replace(s[i],"",1)
return True
return False
#Rujula
def weaveStrings(s,t):
if len(s)<=len(t):
shorter=s
longer=t
else:
shorter=t
longer=s
final=""
counter=0
for x in shorter:
final+=s[counter]
final+=t[counter]
counter+=1
final+=longer[counter:len(longer)]
return final
#morrison
def areAnagrams(s,t):
s = s.lower()
t = t.lower()
s = list(s)
t = list(t)
s.sort()
t.sort()
return s == t
print(areAnagrams("Morrison", "nosirrom"))
Block F
#pranet
def isPerfectNumber(n):
return sumOfProperDivisors(n) == n
def sumOfProperDivisors(n):
nl = []
start = n//2
for i in range(start, 0, -1):
if n%i == 0:
nl.append(i)
return(sum(nl))
#warner
def isPerfectNumber(n):
proper_divisors = []
for i in range(1, n):
if not n%i:
proper_divisors.append(i)
return sum(proper_divisors) == n
#Luke
def countWords(s):
return len(s.split())
#Sophia
def areAnagrams(s,t):
if(not(len(s) == len(t))):
return False
for i in s:
found = False
for j in range(len(t)):
if (i == t[j]) or (i.swapcase() == t[j]):
t = t[:j] + t[j+1:]
found = True
break
if(not(found)):
return False
return True
#morrison I stink
def areAnagrams(s, t):
s = s.lower()
t = t.lower()
s = list(s)
t = list(t)
s.sort()
r.sort()
return s == t
#Dhruv
def weaveStrings(s,t):
longest = s if len(s) > len(t) else t
shortest = s if longest == t else t
return ''.join([f'{s[i]}{t[i]}' if i < len(shortest) else s[i] for i in range(len(longest))])
#pranet
def areAnagrams(s, t):
init = 0
s.lower()
t.lower()
s = list(s)
t = list(t)
if len(s) != len(t):
return False
length = math.factorial(len(s))
for i in range(length):
random.shuffle(s)
if s == t:
init += 1
return True
if init != 1:
return False
#pollard
##smartest if the file is big.
def checkFileForWord(fileName, word):
with open(fileName, "r") as fp:
for line in fp:
if word in line:
return True
return False
#warner
# Paul Warner
def isPerfectNumber(n):
proper_divisors = []
for i in range(1, n):
if not n%i: ##cookie woof
proper_divisors.append(i)
return sum(proper_divisors) == n
#pranet
def weaveStrings(s,t):
nl = []
for i in s:
nl.append(i)
for k in t:
nl.append(k)
t = t[1:]
print(k)
break
return ''.join(nl)
#Adam
def weaveStrings(s,t):
helpme=0
myweave=""
if s.len() > t.len():
helpme=s.len()
else:
helpme=t.len()
for i in range (0, helpme):
if s.len()> helpme:
weave+=s[i]
if t.len()> helpme:
weave+=t[i]
return weave
#morrison
def weaveStrings(s,t)
out = ""
n = min(len(s), len(t))
for k in range(n):
out += s[k] + t[k]
out += s[n:] + t[n:]
return out
#pittenger
def weaveStrings(s,t):
if len(t) > len(s):
s, t = t, s
length = len(t)
return ''.join(s[i] + t[i] for i in range(length)) + s[length:]
#sophia
def containsEmbeddedWord(word, searchField):
j = 0
for i in searchField:
if (word[j] == i) or (word[j].swapcase() == i):
j += 1
if j == len(word):
return True
return False
# Paul Warner
#this is cute.
def areAnagrams(s,t):
s = list(s.lower())
t = list(t.lower())
for char in s:
if char in t:
t.remove(char)
return not t
#adam
def countWords(s):
shatter = s.split()
return len(shatter) #shatter.len()
#Luke
def areAnagrams(s,t):
s_list = list(s.lower())
t_list = list(t.lower())
s_list.sort()
t_list.sort()
if s_list == t_list:
return True
else:
return False
#Carl
# smart if file is not too big.
imoprt os
def checkFileForWord(fileName, word):
if os.path.exists(fileName):
with open(fileName) as f:
return word in f.read()
else:
return False
#Luke
def sumOfProperDivisors(n):
divisors_sum = 0
for i in range(1, n//2+1):
if n % i == 0:
divisors_sum += i
return divisors_sum
def isPerfectNumber(n):
if sumOfProperDivisors(n) == n:
return True
else:
return False
# morrison
def sumOfProperDivisors(n):
out = 0
for k in range(1,n):
if n%k == 0:
out += k
return out
def isPerfectNumber(n):
return n == sumOfProperDivisors(n)
#vester
#Baeden Vester
def areAnagrams(s,t):
if len(s) == len(t):
for char in s.lower():
if char not in t.lower():
return False
return True
else:
return False
#Chloe
def weaveStrings(s,t):
sList = list(s)
tList = list(t)
weaveList = []
counter = 0
while counter < len(s):
weaveList.append(s[counter])
weaveList.append(t[counter])
counter += 1
finalString = ""
for char in weaveList:
finalString += char
return finalString
#pittenger
#Carl Modified
def weaveStrings(s,t):
s, t, n = s.lower(), t.lower(), min(len(s), len(t))
return ''.join(s[i] + t[i] for i in range(n)) + s[n:] + t[n:]
#jimin yu: this is oily
import re
def containsEmbeddedWord(word, searchField):
letters = list(word)
regex = '.*'.join(map(re.escape, letters))
return re.search(regex, searchField) is not None
# jimin: this is sordid
def areAnagrams(s,t):
return (sorted(s.lower()) == sorted(t.lower()))
What Can I do with String
(:45)
Stack, Heap, and Primitive vs. Object
Recall that there are two important areas of memory in a program, the stacka and the heap.The heap is the data warehouse where objects are stored. The stack is the more limited area of memory where the call stack (works the same in Java and Python) lives.
So far we have seen the eight primitive types
Java Primitive Types | |
---|---|
Type | Description |
Integer Types | |
byte | This is an 8-bit (one byte) integer. |
short | This is a two-bit integer |
int | This is a four-bit integer |
long | This is an 8-bit integer. |
Other Java Types | |
float | This is an four-bit IEEE 754 floating point number. |
double | This is an 8-bit IEEE 754 floating-point number. We will use this type for floating point numbers in this class. |
boolean | There are two boolean constants,
true and false . |
char | This Java's character type. It has some
fluidity with int . |
Variables of primitive type store their values directly;
they do not store a memory address. The ==
operator checks for equality of this value.
jshell> int x = 5;
x ==> 5
jshell> int y = 5;
y ==> 5
jshell> x == y
$3 ==> true
You can use the ==
operator on primitive
types to check for equality.
All local variables of primitive type live strictly on the stack inside of their stack frames. They do not point to anything on the heap.
Objects (such as our Point
class live
on the heap. They can contain primitive data as state.
Everything in Java that is not a primitive type is an
Object type; in fact all data of Object type
are Object
s.. All objects live on the heap.
Local variables of Object type do not store their objects
directly. They store a JVM memory address (an integer no larger
than 8 bytes) in the heap. This is how they "point"
at their objects.
Typography Note The names of primitive types are all lower-case. The names of all Object types are capitalized. When you create a class, you are creating a new Object type. This is why you must capitalize class names; failure to do so confuses other programmers.
Primitive types do not have methods. Object types will
have one or more methods. We will explore the String
and Object
types today.
Important Object Methods These are the Object methods we will concern ourselves with in this class.
public String toString()
This method returns a String representation of an Object. As you saw inPoint.java
, you can override this for a class you are making. By default, this method returnsClassName@someHexDigits
.public boolean equals(Object o)
This method checks to see if your object is ``equal'' to another object. By default, this is equality of identity (like Python'sis
). You can override it but don't forget to do the species test.public int hashCode()
This defines a hash code for an Object so it can be inserted into a hashed data structure. All Objects are hashable. This method can be overridden.