문제
여러 개의 소금물을 섞었을 때, 혼합된 소금물의 퍼센트 농도와 양을 계산하는 프로그램을 만드시오.
입출력 방식
소금물의 퍼센트 농도와 소금물의 양을 입력하고, end를 입력하면 혼합물의 퍼센트 농도와 양이 출력되도록 하시오.
입력에는 소수점 자리수의 제한이 없지만, 출력된 혼합물의 퍼센트 농도와 양이 소수점 2자리를 넘어갈 경우, 반올림하여 2번째 자리까지만 나타내시오.
입력 횟수는 최대 10회이다.
입력 예1
1% 400g
8% 300g
end
입력 예2
12.245% 21.258g
42.18% 6.826g
0.169% 32.33g
end
출력 예1
4.0% 700.0g
출력 예2
9.16% 60.41g
38개의 풀이가 있습니다.
n=1
slst,swlst=[],[] #소금의 양과 소금물의 양을 받기 위한 리스트
while n<=10:
inp=input("소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: ")
if inp=='end':
break
else:
s,sw=inp[:inp.find("%")],inp[inp.find(" ")+1:inp.find("g")] #s=%앞의 숫자(소금의 농도), sw=g앞의 숫자(소금물의 양)
slst.append(float(s)/100*float(sw)) #소금의 양(s/100에 sw를 곱한 것)을 slst에 추가.
swlst.append(float(sw))
n+=1
print(str(round(sum(slst)*100/sum(swlst),2))+"%",str(round(sum(swlst),2))+"g")
결과
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: 1% 400g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: 8% 300g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: end
4.0% 700.0g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: 12.245% 21.258g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: 42.18% 6.826g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: 0.169% 32.33g
소금물의 농도(%)와 소금물의 양(g)을 입력하십시오: end
9.16% 60.41g
import re
#(소금물의 농도) = (소금의 양) / (소금물의 양) * 100
#(소금의 양) = (소금물의 농도) / 100 * (소금물의 양)
def salt(salt_rate, salt_water):
if salt_rate <0 or salt_water <0:
return 0
return (salt_rate / 100) * salt_water
def format1(fvalue, f):
return format(fvalue, f)
def input_fn(lines):
#공백|\n + 소수점 숫자 + % +공백 + 소수점 숫자+g+공백|\n 의 조합일 때만 유효
p = re.compile("\b*\s*(\d+\.*\d*[%])\s+(\d+\.*\d*[g])\b*\s*")
match = p.findall(lines)
total_salt = 0.0
total_salt_water =0.0
for m in match:
x = str(m[0])
x = x[:-1] # %제거
y = str(m[1])
y = y[:-1] # g제거
# print(x, y)
total_salt += salt(float(x),float(y)) # 총 소금양
total_salt_water +=float(y) #총 소금물 양
print('',total_salt, total_salt_water)
total_salt_rate= float(total_salt/total_salt_water *100) #총 소금물 농도
astr = str(total_salt_rate)
if astr[-2]== '.' and astr[-1] =='0': # 소숫점 한자리인지 검사
srate = format1(total_salt_rate, '.1f')
swater= format1(total_salt_water, '.1f')
return (srate+"%"+" "+swater+"g") #총 소금물 농도, 총 소금물 양
srate = format1(total_salt_rate, '.2f')
swater= format1(total_salt_water, '.2f')
return (srate+"%"+" "+swater+"g")
uinput = """
12.245% 21.258g
42.18% 6.826g
0.169% 32.33g
20% 10kg
end
"""
#uinput = input('input: ')
print('sum:',input_fn(uinput))
결과:
5.5368866 60.414
sum: 9.16% 60.41g
Python 3.7 알고리즘과 상관없이 정규표현으로 구현해 봤어요.. input 함수로도 입력 받아할 수 있어요..
이제 Python 개발 1주일차입니다.
enter, sa = None, []
while 1:
enter = input()
if enter == 'end':
break
temp = []
for x in enter.split():
temp.append(float(x))
sa.append(temp)
def salt_mix(brine):
salt = 0
vol = 0
for a in range(len(brine)):
salt += brine[a][0] * brine[a][1] / 100
vol += brine[a][1]
res = []
res.append(salt * 100 / vol)
res.append(vol)
return res
result = salt_mix(sa)
print("%.2f%% %.2fg" % (result[0], result[1]))
import re # 정규 표현식을 사용하기 위해 import
list_ = []
for i in range(10) : # 입력횟수는 최대 10
a = input() # 퍼센트와 혼합물의 양을 받음
if a == 'end' : # end 가 나올때까지만 받는다
break
list_.append(a) # 퍼센트와 혼합물의 양 리스트로 저장
sum_salt = 0
sum_saltwater = 0
for i in range(len(list_)) : # 최종 혼합물의 양과 소금양을 계산하는 for문
pat = re.compile(r"""
(\w*[.]?\w*) # percent 받기
[%] # %
\s # 한 칸 띄우기
(\w*[.]?\w*) # 혼합물 양 받기
[g] # gram
""", re.VERBOSE)
m = pat.search(list_[i])
percent = float(m.group(1))
saltwater = float(m.group(2))
sum_salt += saltwater*percent/100
sum_saltwater += saltwater
result_percent = sum_salt*100/sum_saltwater
result_percent = str(round(result_percent, 2)) # 소수점 2째자리에서 반올림
sum_saltwater = str(round(sum_saltwater, 2))
print("%s%% %sg" % (result_percent, sum_saltwater))
package study;
import java.util.HashMap;
import java.util.Scanner;
public class salt {
public static void main(String[] args) {
double totalWater = 0;
double totalSalt = 0;
double salt = 0;
double water = 0;
double totalPercent = 0;
Scanner sc = new Scanner(System.in);
System.out.println("소금물의 농도(%)와 물의 양(g)을 입력하시오.");
for(int i = 0 ; i < 11 ; i++) {
System.out.println("%입력");
String percent = sc.nextLine();
if(percent.equals("end")) {
break;
}
System.out.println("g입력");
String amount = sc.nextLine();
if(amount.equals("end")) {
break;
}
if(percent.contains("%") && amount.contains("g")) {
int percentInt = Integer.parseInt(percent.substring(0, percent.length()-1));
int amountInt = Integer.parseInt(amount.substring(0, amount.length()-1));
salt = percentInt * amountInt / 100;
water = amountInt - salt;
totalSalt += salt;
totalWater += water;
}else {
System.out.println("입력 오류");
}
}
totalPercent = totalSalt / (totalWater+totalSalt) * 100 ;
System.out.println("농도는"+ String.format("%.2f", totalPercent) + "%");
}
}
import re
i = ""
numbers = []
for i in range(10):
data = input("")
if data == 'end' :
break
numbers.append(data)
print(numbers)
amount_of_salt = 0
whole_water = 0
for i in numbers :
percent, gram = i.split(" ")
p = re.compile(r"\d*.?\d*(?=%|g)")
m1 = p.search(percent).group()
m2 = p.search(gram).group()
amount_of_salt += float(m1)*float(m2)*0.01
whole_water += float(m2)
a = round((amount_of_salt / whole_water)*100, 2)
b = round(whole_water, 2)
print(str(a)+"%"+" "+str(b)+"g")
def calc_salt_gram(pcnt, gram):
pcnt = pcnt.split('%')[0]
water_gram = gram.split('g')[0]
return float(water_gram) * float(pcnt) / 100, float(water_gram)
if __name__ == "__main__":
text = ''
placeholder = []
for i in range(10):
one_line = input()
text = one_line
if text != 'end':
pcnt, gram = one_line.split(' ')
salt_gram, water_gram = calc_salt_gram(pcnt, gram)
placeholder.append((salt_gram, water_gram))
else:
break
salt = 0
water = 0
for row in placeholder:
salt += row[0]
water += row[1]
res_pcnt = salt/water * 100
total_water = water
print("{:.2f}% {:.2f}g".format(res_pcnt, total_water))
python 3.8
import re
i=0
j=input()
a=[]
while i< 10 or j != 'end': # 10회 이내 또는 end시 계산
a.append(j)
j=input()
i+=1
a=' '.join(a)
sal=wat=0.0
b=re.findall(r'\d+.?\d+',a)
for i in range(0,len(b),2):
sal+= float(b[i])*0.01*float(b[i+1])
wat+=float(b[i+1])
print("%.2f%c %.2f%c" % (sal/wat*100,'%',wat,'g'))
-----------
import re
a="""
12.245% 21.258g
42.18% 6.826g
0.169% 32.33g
end
""".split() # range() 0 미삽입시 zero division err
sal=wat=0.0
b=re.findall(r'\d+.?\d+',str(a))
for i in range(0,len(b),2):
sal+=float(b[i])*0.01*float(b[i+1])
wat+=float(b[i+1])
print("%.2f%c %.2f%c" % (sal/wat*100,'%',wat,'g'))
grams, salts = 0, 0; count = 0
while 1:
count += 1
if count > 10: break
Input = input().split()
if Input == ['end']: break # 'end' 입력 시 종료
persent = Input[0]; gram = Input[1]
persent = float(persent[:-1]); gram = float(gram[:-1]) # remove %, 'g' and floating
salt = gram * (persent / 100)
grams += gram; salts += salt
result_persent = str(round((salts / (grams)) * 100, 2)) + '%'
result_gram = str(round(grams, 2)) + 'g'
print(result_persent, result_gram)
flo4 = 0.0
flo5 = 0.0
lst1 = [] #소금양
lst2 = [] #물양
for i in range(10) :
s = input("농도랑 양 : ")
if s == "end" :
break
flo1 = float(s.split(" ")[0].replace("%", "")) / 100 # 농도
flo2 = float(s.split(" ")[1].replace("g", "")) # water gram
flo3 = flo1*flo2 / (1-flo1) # 소금
lst1.append(str(flo3))
lst2.append(str(flo2))
for j in lst1 :
flo4 += float(j)
for k in lst2 :
flo5 += float(k)
print("{0}% {1}g".format(round(flo4/(flo4+flo5)*100,2), flo5))
파이썬 공부중인 파린이 입니다
근데 제 공식에 문제가 있는지 값이 틀리게 나오네요..
어디에 오류가 있을까요?
파이썬 입니다. 초보라서 좀 기네요
while True:
i = int(input('몇개의 소금물을 사용할지 입력하세요 (단 10개를 초과할 수 없습니다.) : '))
j = []
if i >10:
print('10개의 소금물을 초과할 수 없습니다. ')
continue
else:
for I in range(i):
k = input('%s번째 소금물의 퍼센트 농도와 소금물의 양을 입력하세요 : ' % (I + 1)).split()
l = [float(x) for x in k]
l = [round(l[0],2), round(l[1],2)]
j.append(l)
m = []
n = []
for J in range(len(j)):
m.append(j[J][1])
n.append(j[J][0]/100*j[J][1])
o = sum(m) - sum(n)
print("")
print("-----------------------------------------------------------------")
print('혼합물의 퍼센트 농도는 %s' %(round((sum(n)/o*100),2)), '% 이며')
print('혼합물의 양은 %s g 입니다.' %(sum(m)))
print("-----------------------------------------------------------------")
print("")
print("")
print("")
print("============================================================")
iii = input('다시 실행하시겠습니까? \n'
'(다시 실행하려면 "y"나 "Y"를 입력하고 끝내시면 이외의 아무키나 입력하세요 ) :')
if iii == 'y' or iii == 'Y':
print("============================================================")
print("")
print("")
continue
else:
print("")
print("수고하셨습니다. ")
break
sumOfSalt=0
sumOfSaltWater=0
for i in range(10):
a=input('소금물의 농도와 양을 입력하세요 ')
if a=='end':
break
b=a.split()
x=float(b[0].strip('%'))
y=float(b[1].strip('g'))
c= (x*y)/100
sumOfSalt += c; sumOfSaltWater += y
print('%.2f%% %.2fg' % (sumOfSalt/sumOfSaltWater*100, sumOfSaltWater))
import math
nong=[]
gram=[]
nong1=[]
gram1=[]
for i in range(10):
inp=input()
if inp=='end':
break
else:
a, b=map(str, inp.split(' '))
nong.append(a)
gram.append(b)
for i in range(len(nong)):
nong1.append(float(nong[i].rstrip('%')))
gram1.append(float(gram[i].rstrip('g')))
total=0
water=0
for i in range(len(nong)):
total+=(nong1[i]*gram1[i])/100
water+=gram1[i]
new=(total/water)*100
print('{0}% {1}g'.format(round(new,2),round(water,2)))
파이썬 3.8.1로 작성했습니다.
import re #정규 표현식 사용
m=re.compile("(\w*[.]?\w*)[%]\s(\w*[.]?\w*)[g]") #groupping하여 %와 g 분리해냄
list_rows=[]
i=0
j=0
mass_water=0
mass_salt=0
# list_rows에 입력 추가하기
while i<10:
input_data=input()
if input_data=='end':
break
elif input_data=='':
break
else:
list_rows.append(input_data)
i+=1
for j in range(len(list_rows)): #list_row의 성분에 대해서 percent, mass 소수값으로 얻어냄
p=m.match(list_rows[j])
percent=float(p.group(1))/100
mass=float(p.group(2))
mass_water=mass_water+mass
mass_salt=percent*mass+mass_salt
print("%s%% %sg" % (round(mass_salt*100/mass_water,2),mass_water))
i = 1
new = []
while i <= 10:
question = input("농도(%), 소금물(g)의 양을 입력하시오: ")
if question == 'end':
break
new.append(question.split())
i += 1
sault_sum = 0
gram_sum = 0
for j in new:
first = j[0]
second = j[1]
first_num = first[:first.find('%')]
second_num = second[:second.find('g')]
sault_sum += float(first_num) * (float(second_num)/100)
gram_sum += float(second_num)
result_percent = round((sault_sum * 100) / gram_sum, 2)
result_gram = round(gram_sum, 2)
print("{}% {}g".format(result_percent, result_gram))
for i in range(1,11):
a=input("농도1:")
x=input("소금물1:")
b=input("농도2:")
y=input("소금물2:")
c=input()
if c=="end":
print("%.2f"%float((float(a)*float(x)/100+float(b)*float(y)/100)/(float(x)+float(y))*100), "%", end=" ")
print("%.2f"%float(float(x)+float(y)), "g")
i+=1
def ext(x): #농도 및 소금물양에서 %와 g을 제외한 앞의 숫자만 추출
if 'g' in x:
p=x.index('g')
elif '%' in x:
p=x.index('%')
x=float(x[:p])
return (x)
i,water_sum,salt_sum=0,0,0
while (i<10):
temp=str(input('소금물농도(%) 소금물양(g)...')).split(' ')
if 'end' in temp:
break
nongdo,water=ext(temp[0]),ext(temp[1])
salt=nongdo*water
water_sum+=water
salt_sum+=salt
i+=1
print (str(round(salt_sum/water_sum,2))+'% '+str(round(water_sum,2))+'g')
x=[float(input("농도")),float(input("농도"))]
y=[float(input("소금물")),float(input("소금물"))]
b=input()
salt_=[]
for n in range(2):
salt_.append(y[n]/100*x[n])
if b=="end":
salt=sum(salt_)
salt_water=sum(y)
density=salt/salt_water*100
print("{}%,{}g".format(density,salt_water))
import re
def s_concentration(inp):
salt = 0
salt_water = 0
for i in inp:
m = re.match('(\d+\.?\d*)[%] (\d+\.?\d*)[g]', i)
salt += float(m.group(2)) * (float(m.group(1))/100)
salt_water += float(m.group(2))
mixed = (salt/salt_water)*100
print('{}% {}g'.format(round(mixed, 2), round(salt_water, 2)))
if __name__ == '__main__':
cnt = 0
inp = []
while cnt < 10:
in1 = input('소금물의 %농도, 소금물의 양 입력: ')
if in1 == 'end':
break
inp.append(in1)
cnt += 1
s_concentration(inp)
C#
using System;
namespace CD245
{
class Program
{
static void Main()
{
SaltWater sw = GetInputFromConsole();
Console.WriteLine(sw);
}
static SaltWater GetInputFromConsole()
{
// 키보드 입력은 항상 유효한 상태로 주어진다고 가정
SaltWater sw = new SaltWater(0, 0);
while (true)
{
string foo = Console.ReadLine().Trim();
if (foo == "end") { break; }
string[] bar = foo.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
double concentration = double.Parse(bar[0].Substring(0, bar[0].Length - 1));
double totalWeigt = double.Parse(bar[1].Substring(0, bar[1].Length - 1));
sw += new SaltWater(concentration, totalWeigt);
}
return sw;
}
}
class SaltWater
{
/// <summary>
/// 소금의 무게(g)
/// </summary>
public double SaltWeight { get; }
/// <summary>
/// 소금물의 농도(%)
/// </summary>
public double Concentration { get; }
/// <summary>
/// 소금물의 무게(g)
/// </summary>
public double TotalWeight { get; }
/// <summary>
/// 소금물의 인스턴스를 생성합니다.
/// </summary>
/// <param name="concentration">소금물의 농도(%)</param>
/// <param name="totalWeight">소금물의 무게(g)</param>
public SaltWater(double concentration, double totalWeight)
{
Concentration = concentration;
TotalWeight = totalWeight;
SaltWeight = Concentration * TotalWeight / 100.0;
}
public static SaltWater operator +(SaltWater sw1, SaltWater sw2)
{
double newTotalWeight = sw1.TotalWeight + sw2.TotalWeight;
double newConcentration = (sw1.SaltWeight + sw2.SaltWeight) / newTotalWeight * 100.0;
return new SaltWater(newConcentration, newTotalWeight);
}
public override string ToString()
{
return $"{Concentration:#.0#}% {TotalWeight:#.0#}g";
}
}
}
Go
package main
import "fmt"
func main() {
// 퍼센트 농도, 소금물 양, 순수 물의 양, 소금의 양, 각 소금물의 소금 양
var per, weight, water, salt, s float64
var err error
water = 0
salt = 0
for i := 0; i < 10; i++ {
_, err = fmt.Scanf("%f%% %fg\n", &per, &weight)
if err == nil {
// 정상 입력됨
s = per * weight
water += weight - s
salt += s
} else {
break
}
}
// 입력 완료
// 소금물 계산해서 출력
fmt.Printf("%.2f%% %.2fg", salt/(salt+water), salt+water)
}
salt, w_tot = 0, 0
while True:
inp = input()
if inp == "end":
break
d, w = map(lambda x: float(x[:-1]), inp.split(' '))
salt += w * (d / 100)
w_tot += w
w_tot = round(w_tot, 2)
dense = round(salt / w_tot * 100, 2)
print("{:.2f}% {:.2f}g".format(dense, w_tot))
입력 받기
inputs = []
for i in range(10):
s = input('>')
if s == 'end':
break
inputs.append(s)
계산
total_sault = 0
total_water = 0
for i in inputs:
s = i.split(' ')
water = float(s[1][:-1])
sault = water * float(s[0][:-1])/100
total_sault += sault
total_water += water
sault_ratio = round(total_sault / total_water * 100, 2)
total_water = round(total_water, 2)
print('{}% {}g'.format(sault_ratio, total_water))
lst = list()
n = 1
while n <= 10:
temp = input()
if temp =='end':
break
else:
t = temp.split(' ')
lst.append(t)
n += 1
salt = 0
water = 0
for l in lst:
water += float(l[1][:-1])
salt += float(l[1][:-1]) * float(l[0][:-1]) / 100
concentration = round(salt / water * 100, 2)
water = round(water, 2)
print(f'{concentration}%, {water}g')
def salt_water():
count = 0
tot_water = 0
tot_salt = 0
while True:
count += 1
inputval = input("input salt per water and water : ")
if inputval == "end":
break
inputval = inputval.replace("%", "")
inputval = inputval.replace("g", "")
inputval = inputval.replace(",", "")
inputval = inputval.split(" ")
salt_per = int(inputval[0])
water = int(inputval[1])
salt = salt_per * water / 100
tot_water += water
tot_salt += salt
if count == 10:
break
return f"{round(tot_salt / tot_water * 100, 3)}% {tot_water}g"
import java.util.Scanner;
public class Water {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
double []aPer=new double[10];// 농도
double []aWater=new double[10];// 물의양
double []aSalt=new double[10];//소금의 양
double bPer=0;//두번째 농도
double bWater=0;//두번재 소금물
double bSalt=0; //두번째 소금
double []sPer= new double[10];// 혼합된 농도
double []sWater=new double[10];//혼합된 소금물
double []sSalt= new double[10];//혼합된 소금
String d=null;// end or go
int j=2;// 농도구하기 횟수
int e=0;
System.out.println("1번째 소금물의 농도와 소금물을 입력하세요");
System.out.print(" 소금물의 농도 : ");
aPer[1]=scan.nextDouble();
System.out.print(" 소금물 : ");
aWater[1]=scan.nextDouble();
aSalt[1]=aPer[1]*aWater[1]/100;// 소금의 양 구하기
sSalt[0]=aSalt[1]+sSalt[0];// 소금의 합
sWater[0] =aWater[1]+sWater[0];//소금물의 합
sPer[0]= sWater[0]/sSalt[0]*100;//소금물 합의 농도
while(j<11 && e !=1) {
System.out.println(j+"번째 소금물의 농도와 소금물을 입력하세요");
System.out.print(" 소금물의 농도 : ");
aPer[2]=scan.nextDouble();
System.out.print(" 소금물 : ");
aWater[2]=scan.nextDouble();
aSalt[j]=aPer[j]*aWater[j]/100;// 소금의 양 구하기
sSalt[j-1]=aSalt[j]+sSalt[j-2];// 소금의 합
sWater[j-1] =aWater[j]+sWater[j-2];//소금물의 합
sPer[j-1]= sSalt[j-1]/sWater[j-1]*100;//소금물 합의 농도%
System.out.print(" 계산을 끝마치려면 end 다음을 입력하려면 go를 누르세요 :");
d=scan.next();
if(d.equals("end")) { //end를 적게되면 while문을 빠져나옴
e=1;
System.out.println(d );
System.out.print("소금의 농도"+sPer[j-1]+"%"+ " "+"소금물의 양"+sWater[j-1]+"g");
}//if
}//while
j++;
}//main
}//class
import re
density = 0
volume = 0
count = 0
while True:
a = input('농도(%) 용량(g) :')
if count>10 or a=='end':break
a = list(map(int,re.findall('\d+',a)))
print(a)
d = a[1]*a[0]/100
v = a[1]
density += d
volume +=v
count+=1
print(f'{round((density/volume)*100,2)}% {volume}g')
Ss = [] # 소금
Ls = [] # 소금물
while True:
X = input("입력 : ")
if X == "end":
break
S, L = int(X[:X.find("%")]), int(X[X.find(" ")+1:X.find("g")])
Ss.append(S*L/100) # 농도 * 물 / 100 = 소금
Ls.append(L)
print("농도 : {:.2f}%\n용량 : {}g".format(sum(Ss)/sum(Ls)*100, sum(Ls)))
# 소금 / 물 * 100 = 농도
whole,salt=0,0
for i in range(10):
inp=input("").split('%')
if inp==['end']: break
salt+=float(inp[1][:-1].strip())*float(inp[0])/100
whole+=float(inp[1][:-1].strip())
print(f'{round(salt/whole*100,2)}% {round(whole,2)}g')
#codingdojing_salt_water
s = input('ex) 1% 400g: ')
salt = 0
salt_water = 0
while s != 'end':
try:
salt += eval(s.split()[1][:-1]) * eval(s.split()[0][:-1])/100
salt_water += eval(s.split()[1][:-1])
s = input('ex) 1% 400g: ')
except:
pass
print(f'{salt/salt_water*100:0.2f}% {salt_water:0.2f}g')
p_arr=[]
m_arr=[]
n=0
while True:
n+=1
a = input("첫번째 소금물의 농도와 양을 입력하시오")
try :
p = float(a.split(" ")[0].strip('%'))
m = float(a.split(" ")[1].strip('g'))
p_arr.append(p)
m_arr.append(m)
except ValueError:
break
if n==10 :
break
def mix (arr1,arr2):
salt=0
sum =0
for k in range(len(arr1)):
salt += arr1[k]/100*arr2[k]
sum +=arr2[k]
print(round(salt/sum*100,2),"% ",round(sum,2),'g')
mix(p_arr,m_arr)
inp = '''12.245% 21.258g
42.18% 6.826g
0.169% 32.33g
end'''
*d,e = inp.splitlines()
salt, water = 0,0
for index, data in enumerate(d):
c, w = data.split(' ')
conc = float(c[:-1])
weight = float(w[:-1])
salt += conc/100*weight
water += weight
print(f'{round(salt/water*100,2)}%, {round(water,2)}g')
ml = []; sl = []
for i in range(10):
iinn = input('소금물의 농도와 양을 입력하세요 : ')
if iinn == 'end':
break
per, mass = iinn.split()
per = float(per.rstrip('%'))
mass = float(mass.rstrip('g'))
salt = per * mass/100
ml.append(mass)
sl.append(salt)
all_mass = sum(ml)
all_salt = sum(sl)
print('{0:.2f}%% {1:.2f}g' .format(all_salt/all_mass, all_mass))
raw_data = []
salt_data = [];salt=[]
water_data = [];water = []
while True:
user = input()
if user == 'end':break
else:
raw_data.append(user.split())
for i in range(len(raw_data)):
salt_num = raw_data[i][0]
water_num = raw_data[i][1]
salt.append((float(salt_num.strip("%")))/100 * (float(water_num.strip("g"))))
water.append((float(water_num.strip("g")))-salt[i])
print("===============")
print(round((sum(salt)/((sum(water)+(sum(salt))))*100),2),"%",end=" ")
print(round((sum(water))+(sum(salt)),2),"g",end="\n")
saltWater = 0
salt = 0
while True:
inInp = input('소금물의 퍼센트 농도와 소금물의 양을 입력하세요;\n')
if inInp == 'end':
break
c = ''
for n in inInp:
if n == ' ':
continue
elif n == '%':
s = float(c)
c = ''
elif n == 'g':
w = float(c)
c = ''
else:
c += n
salt += s * w
saltWater += w
print('{0}% {1}g'.format(round(salt/saltWater, 2), round(saltWater, 2)))
saline = []
flag = 0
vol_w, vol_s = 0, 0
while flag < 10:
inpt = input().split()
if 'end' in inpt:
flag = 10
else:
s = [float(x) for x in inpt]
saline.append(s)
flag += 1
for i in saline:
p, v = i
salt = (p * v) / 100
vol_s += salt
vol_w += v
per = (vol_s / (vol_w))*100
print(f'{round(per, 2)}% {round(vol_w, 2)}g')
def saltConvert(a):
c = float(a[0:a.index("%")])
d = float(a[a.index(" ")+1:a.index("g")])
e =[c,d]
return e
def saltAmt(a):
b = []
for i in a:
b.append(float((i[0]/100) * i[1]))
return float(sum(b))
def waterAmt(a):
b =[]
for i in a:
b.append(i[1])
return float(sum(b))
def saltPctg(a,b):
c = float((a/b) * 100)
return c
salt = []
a = input ("% 그리고 g 입력하시오: ")
while a.lower() != "end":
salt.append(saltConvert(a))
a = input ("% 그리고 g 입력하시오: ")
sAmt = saltAmt(salt)
wAmt = waterAmt(salt)
sPct = saltPctg(sAmt, wAmt)
print(f"{sPct:.2f}% {wAmt:.2f}g")