The Python code was taken as a basis: enter link description here
Errors occur in each cycle
A lot of errors (please help fix it):
enter image description here
Code:
var t = readLine()!
var s = readLine()!
var len_s = s.count
var t_lis = Set(t)
let character:[Character] = Array(s)
var c_s:[Character: Int] = Dictionary(uniqueKeysWithValues: zip(character, Array(repeating: 1, count: character.count)))
let character2:[Character] = Array(t_lis)
var c_t:[Character: Int] = Dictionary(uniqueKeysWithValues: zip(character2, Array(repeating: 1, count: character2.count)))
var c_res = [String: String]()
var summ = 0
for e in c_s{
c_res[e] = [c_s[e], min( c_s[e], c_t[e] )]
summ += c_res[e][1]}
for i in 0..<((t.count-s.count)+1) {
if summ == len_s-1{
print(i)
break
}
for j in c_res{
if t[i] = c_res[j]{
if c_res[t[i]][1] > 0{
c_res[t[i]][1] -= 1
summ -= 1
}}}
for l in c_res {
if (i+len_s < t.count && t[i+len_s]) = c_res{
if c_res[ t[i+len_s] ][1] < c_res[ t[i+len_s] ][0]{
c_res[ t[i+len_s] ][1] += 1
summ += 1
}}}
}
For reference, here is the original Python code that OP linked to:
t = input('t = ')
s = input('s = ')
len_s = len(s)
t_lis = list(t)
c_s = Counter(s)
c_t = Counter(t_lis[:len_s])
c_res = dict()
summ = 0
for e in c_s:
c_res[e] = [c_s[e], min( c_s[e], c_t[e] )]
summ += c_res[e][1]
for i in range( len(t)-len(s)+1 ):
if summ == len_s-1:
print(i)
break
if t[i] in c_res:
if c_res[t[i]][1] > 0:
c_res[t[i]][1] -= 1
summ -= 1
if i+len_s < len(t) and t[i+len_s] in c_res:
if c_res[ t[i+len_s] ][1] < c_res[ t[i+len_s] ][0]:
c_res[ t[i+len_s] ][1] += 1
summ += 1
else:
print(-1)
First I want to mention that the Python code that was linked to is pretty bad. By that, I mean that nothing is clearly named. It's totally obtuse as to what it's trying to accomplish. I'm sure it would be clearer if I spoke Russian or whatever the languge on that page is, but it's not either of the ones I speak. I know Python programming has a different culture around it than Swift programming since Python is often written for ad hoc solutions, but it really should be refactored, with portions extracted into well-named functions. That would make it a lot more readable, and might have helped you in your translation of it into Swift. I won't try to do those refactorings here, but once the errors are fixed, if you want to use it in any kind of production environment, you really should clean it up.
As you acknowledge, you have a lot of errors. You ask what the errors mean, but presumably you want to know how to fix the problems, so I'll address both. The errors start on this line:
c_res[e] = [c_s[e], min( c_s[e], c_t[e] )]
The first error is Cannot assign value of type '[Any]' to subscript of type 'String'
This means you are building an array containing elements of type Any and trying to assign it to c_res[e]. c_res is Dictionary with keys of type String and values of type String. So assuming e were a String, which it isn't - more on that in a sec - then c_res[e] would have the type of the value, a String.
The natural question would be why is the right-hand side an array of Any. It comes down to the definition of the array isn't legal, and the compiler is choking on it (basically, a by-product of other errors). The reason is because min expects all of its parameters to be of a single type that conforms to the Comparable protocol, but c_s[e] and c_s[e] are illegal... and that's because they are both Dictionary<Character, Int>, so they expect an index of type of Character, but e isn't a Character. It's a tuple, (Character, Int). The reason is to be found on the preceding line:
for e in c_s{
Since c_s is Dictionary<Character, Int> it's elements are tuples containing a Character and an Int. That might be surprising for a Python programmer new to Swift. To iterate over the keys you have to specify that's what you want, so let's correct that:
for e in c_s.keys {
With that fixed, previous errors go away, but a new problem is exposed. When you index into a Dictionary in Swift you get an optional value, because it might be nil if there is no value stored for that key, so it needs to be unwrapped. If you're sure that neither c_s[e] nor c_t[e] will be nil you could force-unwrap them like this:
c_res[e] = [c_s[e]!, min( c_s[e]!, c_t[e]! )]
But are you sure? It's certainly not obvious that they must be. So we need to handle the optional, either with optional binding, or optional coallescing to provide a default value if it is nil.`
for (e, csValue) in c_s {
let ctValue = c_t[e] ?? Int.max
c_res[e] = [csValue, min(csValue, ctValue]
summ += c_res[e][1]
}
Note that we've gone back to iterating over c_s instead of c_s.keys, but now we're using tuple binding to assign just the key to e and the value to csValue. This avoids optional handing for c_s elements. For the value from c_t[e] I use optional coallescing to default it to the maximum integer, that way if c_t[e] is nil, min will still return csValue which seems to be the intent.
But again we have exposed another problem. Now the compiler complains that we can't assign Array<Int> to c_res[e] which is expected to be a String... In Swift, String is not an Array<Int>. I'm not sure why c_res is defined to have values of type String when the code puts arrays of Int in it... so let's redefine c_res.
var c_res = [String: [Int]]()
var summ = 0
for (e, csValue) in c_s {
let ctValue = c_t[e] ?? Int.max
c_res[e] = [csValue, min(csValue, ctValue)]
summ += c_res[e][1]
To paraphrase a Nirvana lyric, "Hey! Wait! There is a new complaint!" Specifically, e is type Character, but c_res is Dictionary<String, Array<Int>>, so let's just make c_res a Dictionary<Character, Array<Int>> instead.
var c_res = [Character: [Int]]()
var summ = 0
for (e, csValue) in c_s {
let ctValue = c_t[e] ?? Int.max
c_res[e] = [csValue, min(csValue, ctValue)]
summ += c_res[e][1]
}
Yay! Now we've resolved all the errors on the line we started with... but there's now one on the next line: Value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'
Again this is because when we index into a Dictionary, the value for our key might not exist. But we just computed the value we want to add to summ in our call to min, so let's save that off and reuse it here.
var c_res = [Character: [Int]]()
var summ = 0
for (e, csValue) in c_s {
let ctValue = c_t[e] ?? Int.max
let minC = min(csValue, ctValue)
c_res[e] = [csValue, minC]
summ += minC
}
Now we finally have no errors in the first loop. Remaining errors are in the nested loops.
For starters, the code uses = to test for equality. As with all languages in the C family, Swift uses == as the equality operator. I think that change, which is needed in couple of places, is pretty straight forward, so I won't show that iteration. Once those are fixed, we get one of my favorite (not) errors in Swift: Type of expression is ambiguous without more context on this line:
if t[i] == c_res[j] {
These ambiguity errors can mean one of a few things. The main reason is because elements of the expression match several definitions, and the compiler doesn't have a way to figure out which one should be used. That flavor is often accompanied by references to the possible matches. It also seems to happen when multiple type-check failures combine in a way the compiler can't give a clearer error. I think that's the version that's happening here. The source of this problem goes back to the outer loop
for i in 0..<((t.count-s.count)+1) {
which makes the loop variable, i, be of type, Int, combined with using i to index into t, which is a String. The problem is that you can't index into String with an Int. You have to use String.Index. The reason comes down to String consisting of unicode characters and using UTF-8 internally, which means that it's characters are of different lengths. Indexing with an Int in the same way as you would for an element of an Array would require O(n) complexity, but indexing into a String is expected to have O(1) complexity. String.Index solves this by using String methods like index(after:) to compute indices from other indices. Basically indexing into a String is kind of pain, so in most cases Swift programmers do something else, usually relying on the many methods String supports to manipulate it. As I'm writing this, I haven't yet put together what the code is supposed to be doing, which makes it hard to figure out what String methods might be helpful here, so let's just convert t to Array[Character], then we can use integers to index into it:
var t = [Character](readLine()!)
That still gives an ambiguous expression error though, so I looked at the equivalent line in the Python code. This revealed a logic error in translation. Here's the Python:
if t[i] in c_res:
if c_res[t[i]][1] > 0:
c_res[t[i]][1] -= 1
summ -= 1
There is no loop. It looks like the loop was introduced to mimic the check to see if t[i] is in c_res, which is one way to do it, but it was done incorrectly. Swift has a way to do that more succinctly:
if c_res.keys.contains(t[i]) {
if c_res[t[i]][1] > 0 {
c_res[t[i]][1] -= 1
summ -= 1
}
}
But we can use optional binding to clean that up further:
let tChar = t[i]
if let cResValue = c_res[tChar] {
if cResValue[1] > 0 {
c_res[tChar][1] -= 1
summ -= 1
}
}
But again we have the problem of indexing into a Dictionary returning an optional which needs unwrapping on the line,
c_res[tChar][1] -= 1
Fortunately we just ensured that c_res[tChar] exists when we bound it to cResValue, and the only reason we need to index into again is because we need to update the dictionary value... this is a good use of a force-unwrap:
let tChar = t[i]
if let cResValue = c_res[tChar] {
if cResValue[1] > 0 {
c_res[tChar]![1] -= 1
summ -= 1
}
}
The last loop also seems to be the result of testing for existence in c_res and the loop variable isn't even used. Here's the original Python:
if i+len_s < len(t) and t[i+len_s] in c_res:
if c_res[ t[i+len_s] ][1] < c_res[ t[i+len_s] ][0]:
c_res[ t[i+len_s] ][1] += 1
summ += 1
We can use optional binding here combined with the comma-if syntax, and another force-unwrap.
tChar = t[i + len_s]
if i+len_s < t.count, let cResValue = c_res[tChar] {
if cResValue[1] < cResValue[0] {
c_res[tChar]![1] += 1
summ += 1
}
}
Of course, since we're re-using tChar with a new value, it has to be changed from let to var.
Now it all compiles. It definitely needs refactoring, but here it is altogether:
import Foundation
var t = [Character](readLine()!)
var s = readLine()!
var len_s = s.count
var t_lis = Set(t)
let character:[Character] = Array(s)
var c_s:[Character: Int] = Dictionary(uniqueKeysWithValues: zip(character, Array(repeating: 1, count: character.count)))
let character2:[Character] = Array(t_lis)
var c_t:[Character: Int] = Dictionary(uniqueKeysWithValues: zip(character2, Array(repeating: 1, count: character2.count)))
var c_res = [Character: [Int]]()
var summ = 0
for (e, csValue) in c_s {
let ctValue = c_t[e] ?? Int.max
let minC = min(csValue, ctValue)
c_res[e] = [csValue, minC]
summ += minC
}
for i in 0..<((t.count-s.count)+1) {
if summ == len_s-1 {
print(i)
break
}
var tChar = t[i]
if let cResValue = c_res[tChar] {
if cResValue[1] > 0 {
c_res[tChar]![1] -= 1
summ -= 1
}
}
tChar = t[i + len_s]
if i+len_s < t.count, let cResValue = c_res[tChar] {
if cResValue[1] < cResValue[0] {
c_res[tChar]![1] += 1
summ += 1
}
}
}
If all of this makes you wonder why anyone would use such a picky language, there are two things to consider. The first is that you don't get so many errors when writing code originally in Swift, or even when translating from another strongly typed language. Coverting from a typeless language, like Python, is a problem, because apart from subtle other differences, you also have to pin down it's overly flexible view of data to some concrete type - and that's not always obvious how to do it. The other thing is that strongly typed languages allow you to catch huge classes of bugs early... because the type system won't even let them compile.
Is there a way to make a variable immutable after initializing/assigning it, so that it can change at one point, but later become immutable? I know that I could create a new let variable, but is there a way to do so without creating a new variable?
If not, what is best practice to safely ensure a variable isn't changed after it needs to be?
Example of what I'm trying to accomplish:
var x = 0 //VARIABLE DECLARATION
while x < 100 { //VARIABLE IS CHANGED AT SOME POINT
x += 1
}
x = let x //MAKE VARIABLE IMMUTABLE AFTER SOME FUNCTION IS PERFORMED
x += 5 //what I'm going for: ERROR - CANNOT ASSIGN TO IMMUTABLE VARIABLE
You can initialize a variable with an inline closure:
let x: Int = {
var x = 0
while x < 100 {
x += 1
}
return x
}()
There's no way I know of that lets you change a var variable into a let constant later on. But you could declare your constant as let to begin with and not immediately give it a value.
let x: Int /// No initial value
x = 100 /// This works.
x += 5 /// Mutating operator '+=' may not be used on immutable value 'x'
As long as you assign a value to your constant sometime before you use it, you're fine, since the compiler can figure out that it will eventually be populated. For example if else works, since one of the conditional branches is guaranteed to get called.
let x: Int
if 5 < 10 {
x = 0 /// This also works.
} else {
x = 1 /// Either the first block or the `else` will be called.
}
x += 5 /// Mutating operator '+=' may not be used on immutable value 'x'
What is the fundamental difference between these 2 functions ?
func sqr(number: Int) {
print (number * number)
}
func sqr1(number: Int) -> Int {
return number * number
}
This is why I basically never teach print to new programmers. People conflate returning values with printing values, because ultimately they all get printed, so there's not much of an evident difference.
Suppose your goal was to evaluate a quadratic equation: a*x^2 + b*x + c.
How would you multiply the x^2 term by a if it doesn't return a value?
func sqr1(number: Int) -> Int {
return number * number
}
let a = 5
let b = 4
let c = 3
let x = 2
let y = 1
let result = a*sqr1(number: x) + b*x + c
print(result)
Trying doing this with sqr(number:), and you'll quickly see that it's impossible.
The first 1 is a void - return function that prints square of a number
The Second 1 is a Int - return function for a square number that returns it to caller
As an illustration sometimes in coding you need to print a value for e.x debugging purposes for beginners sometimes they think it's useless but when you be an experienced you'll know reason of it unlike the 1 that returns the value to callers which makes more sense for all levels
I was coding a calculator app on swift, and I am very new to swift. So I am lost with the syntax and everything. When I debug my code I get and error of on the code sayign division by 0. I have debugged and everything but I have no idea how to solve it any help would be greatly appreciated, I am just starting out swift and iOS. The application I am making right is for the mac terminal so my program takes the the users input from string and then converts it to an int.
This is the code I am working with
var average = 0;
let count = nums.count - 1
for index in 0...nums.count - 2 {
let nextNum = Int(nums[index])
average += nextNum!
}
return average / count
}
You are subtracting one from the array elements count, I assume due to the idea that zero based numbering affects it, but there is no need in this case.
You should check for an empty array since this will cause a division by zero. Also you can use reduce to simply sum up an array of numbers then divide by the count.
func average(of nums: [Float]) -> Float? {
let count = nums.count
if (count == 0) { return nil }
return nums.reduce(0, +) / Float(count)
}
There might be some reason for divisor be 0. As #MartinR said if there is only 1 object in nums then count = nums.count -1 would be zero and 1 / 0 is an undefined state.
One more issue I found that you are looping as 0...nums.count - 2 but it should be 0...nums.count - 1. You can also write it with less than condition as
0..<nums.count or 0..<count
Use,
var average = 0;
let count = nums.count
for index in 0..<count {
let nextNum = Int(nums[index])
average += nextNum!
}
return average / count
You can use the swift high-order functions for the optimised solution which will return 0 as average even if you do not have any number in your nums array. As:
let count = nums.count
let avg = nums.reduce(0, +) / count
Let try this:
var sum = 0;
let count = nums.count
for index in 0...nums.count - 1 {
let nextNum = Int(nums[index])
sum += nextNum!
}
return count != 0 ? sum/count : 0
I'm reading the iBook The Swift Programming Language and seeing a convention that I don't understand and hasn't been explained in the book: variable and functions followed by a single line with the variable or function name by itself.
For example:
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
do {
m = m * 2
} while m < 100
m
And:
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
What is the purpose of these lines where the variable or function name are on a line by themselves?
TIA
The purpose is for "Playground" Demonstrations. For example, if you put that code into playground. The window on the right will show result of the execution of the function.
If you were in a traditional project, you would likely do:
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
var someInt = returnFifteen()
println(someInt)
However, this is unnecessary in Playground:
Notice the right side.
When you are using Swift in the playground, the output display on the right hand side is not actually a console output more so just an output of whatever variable is on that line, or the number of times a loop runs.
So they are placing the variable/function on it's own line so that when you paste that into Playground you will see what the result is.