The capital word find answers

CodeWars Python Solutions


Find the capitals

Write a function that takes a single string (word) as argument. The function must return an ordered list containing the indexes of all capital letters in the string.

Example:

Test.assertSimilar( capitals('CodEWaRs'), [0,3,4,6] );

Given Code


Solution 1

def capitals(word):
    inds = []
    i = 0
    for l in word:
        if l.isupper():
            inds.append(i)
        i += 1
    return inds

Solution 2

def capitals(word):
    return [i for (i, c) in enumerate(word) if c.isupper()]

See on CodeWars.com

Capital
A Y G R E C A S K A B U L A P E F Y A C K E B
I P E C V R U A T I C T F A Y N F E L A M B A
E Y E J A K A R T A I W A N T E D J E C S O N
N A T H E N S P R C L R E I E C R Y M L K A L
P Y O R A C E I S V K Y E R E V A N I A K H A
P U V U A S S I B U G H A R E S F T O C F E D
O R I A C E D I H S T A R R U R E H C K A Y E
D A C R N E T D W O C S O M N D U O C A W F R
A C B R U S S E L S I L Z E B E A H T I W L R
L U G E H C V E S U K S N I M H C A I N R M A
J W E D S A C O B A P C Q U E K O K G N A B Q
E L T H E A R A K N A H S W A H S T O R E G Z
K U Z N R Q G U D A R N R N O S L O T H E C R
B I T U F A N U F O V X R O Y G I K O Y U W P
J Z K Y I V Z O O M D X E H T O T C H I F P J
Capital
V T Y P M C I R B E R N V O A U N U R W D Q E
S D K T I M E X N V E M S T A L L U O E S T K
M B A R G A Z C Y A L X F R E K I B O R I A N
T R V A D U Z Z N A O L C D Q U E Y V N Q F U
Q C O Q I G O G A I T N A S E U Q T K R O L A
Z P X L J O S K O P J E W W W D O T S P R C L
O B T U S E E L R E K C W A S R A W F D O D R
V L I N D A L I N A M A R T Y U J E W C I F N
Q U I O N A H N G U Z E V T E C H N Q L T A U
W Y A N T I O Z A P A L S G U T G I C H R Y G
D G B U B E N F U E E I H K I N G S T O N Z G
N I L V D R Y W O W U J D A D H G A B A T H P
K L O N D O N S Z I U G X I M I P O C I U T A
I O C T P E U I W F A V A L S I T A R B V X B
A B C D A C E L N U P M U J N I L B U D C B A

Recently Published

Quiz Scoreboard

More to Explore

Quiz From the Vault

Featured Blog Post

You Might Also Like…

Trending Topics

Showdown Scoreboard

More By:

enough

Quiz Plays Rating Category Featured Created

Country Word Search

173,590 4.29 Just For Fun Nov 26, 2009

Blitz: Name A…

456,608 4.61 Miscellaneous Sep 24, 2010

The Office: What Character?

391,673 4.27 Television Mar 1, 2010

Animated Movie by Characters

351,349 4.56 Movies Feb 11, 2010

Game System by Controller

349,910 4.34 Gaming Apr 8, 2010

Blitz: Name A… II

328,993 4.50 Miscellaneous Oct 12, 2010

Go to Creator’s Profile

I’m trying to learn how to use regular expressions but have a question. Let’s say I have the string

line = 'Cow Apple think Woof`

I want to see if line has at least two words that begin with capital letters (which, of course, it does). In Python, I tried to do the following

import re
test = re.search(r'(b[A-Z]([a-z])*b){2,}',line)
print(bool(test))

but that prints False. If I instead do

test = re.search(r'(b[A-Z]([a-z])*b)',line)

I find that print(test.group(1)) is Cow but print(test.group(2)) is w, the last letter of the first match (there are no other elements in test.group).

Any suggestions on pinpointing this issue and/or how to approach the problem better in general?

asked Apr 15, 2017 at 4:06

Argon's user avatar

0

The last letter of the match is in group because of inner parentheses. Just drop those and you’ll be fine.

>>> t = re.findall('([A-Z][a-z]+)', line)
>>> t
['Cow', 'Apple', 'Woof']
>>> t = re.findall('([A-Z]([a-z])+)', line)
>>> t
[('Cow', 'w'), ('Apple', 'e'), ('Woof', 'f')]

The count of capitalised words is, of course, len(t).

answered Apr 15, 2017 at 4:19

Synedraacus's user avatar

SynedraacusSynedraacus

9451 gold badge8 silver badges19 bronze badges

2

I use the findall function to find all instances that match the regex. The use len to see how many matches there are, in this case, it prints out 3. You can check if the length is greater than 2 and return a True or False.

import re

line = 'Cow Apple think Woof'

test = re.findall(r'(b[A-Z]([a-z])*b)',line)
print(len(test) >= 2)

If you want to use only regex, you can search for a capitalized word then some characters in between and another capitalized word.

test = re.search(r'(b[A-Z][a-z]*b)(.*)(b[A-Z][a-z]*b)',line)
print(bool(test))
  • (b[A-Z][a-z]*b) — finds a capitalized word
  • (.*) — matches 0 or more characters
  • (b[A-Z][a-z]*b) — finds the second capitalized word

This method isn’t as dynamical since it will not work for trying to match 3 capitalized word.

answered Apr 15, 2017 at 4:12

davidhu's user avatar

davidhudavidhu

9,2275 gold badges31 silver badges53 bronze badges

1

import re

sent = "His email is abc@some.com, however his wife uses xyz@gmail.com"

x = re.findall('[A-Za-z]+@[A-Za-z.]+', sent)

print(x)

If there is a period at the end of an email ID (abc@some,com.), it will be returned at the end of the email address. However, this can be dealt separately.

answered Jun 10, 2020 at 23:27

Saurabh Vaichal's user avatar

Complete the sentences with the correst word

• Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle

e. g Bob has got two credit cards.

1 Has Bill got a … licene

2 My grandparents are in their … fifties

3Magrid is the … city of Spain

4Paul has got two brothers. They are …

5Her father is a … aged man

6Milan is in the … of italy

7 Lisa is tall and … with long, dark hair

8What … is she? She’s French

9In Africa there are a lot of …

10Sally’s hair is short and …

Найдите правильный ответ на вопрос ✅ «Complete the sentences with the correst word • Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle e. g …» по предмету 📘 Английский язык, а если вы сомневаетесь в правильности ответов или ответ отсутствует, то попробуйте воспользоваться умным поиском на сайте и найти ответы на похожие вопросы.

Смотреть другие ответы

Главная » Английский язык » Complete the sentences with the correst word • Capital •twins •late •north •desert •slim •credit •nationality •wavy •driving •middle e. g Bob has got two credit cards. 1 Has Bill got a … licene 2 My grandparents are in their …

UroborusUrius

Task 4 Complete the sentences with a word
formed from the word in capitals
1. When we raise the temperature, the rate of ___________ increases. (EVAPORATE)
2. I’m interested in doing a _______ on my car to make it more environmentally friendly. (CONVERT)
3. Using a plastic bag once and throwing it away is very _______ (WASTE)
4. Don’t give up – you can achieve anything with ______ and hard work. (PERSEVERE)

Progress
Check – 3

V – 1

I.
Find the word with the same or similar meaning.

Example: dull – c)

a) original b) fascinating c) boring

1. to report

a) to borrow b) to inform c) to explain

2. advertisement

a) commercial b) review c) quiz

3. headline

a) article
b)
title c) conclusion

4. quality

a) popular b) original c) serious

5. handbook

a) manual b) guidebook c) encyclopedia

6. fascinating

a) gripping b) brilliant c) amusing

II.
Complete each sentence with one of the words or phrases below.

whenever wisdom tabloids events celebrate prove

book broadcast issue suggested

1. … contain a lot of photographs
and have a more sensational reporting style.

2. Smoking is bad. Can you … it?

3. Local newspapers give information on different … happening in the
local area.

4. I’d like to … tickets for a group of students to London.

5. Series is a long drama or comedy or documentary that is … in parts,
usually at a certain time of day.

6. The first … of the newspaper “The Daily Courant” was published in London in 1702.

7. … you ask for help, I’ll help you.

8. My uncle … making green tea as it is very good for the health.

9. Mikhail Lomonosov was known as a man of great … .

10. How did you … the turn of the century?

III. The word in capitals above each of the
following sentences can be used to form a word that fits suitably in the blank
space. Fill each blank in this way.

Example: MANAGE

He is the manager of a popular singer.

1. DAY

… newspapers are published on
every day of the week except Sunday.

2. COMMENT

Who is your favourite TV … ?

3. COMMUNCATE

Pamela thinks that the Internet
is the most useful means of … .

4. CULTURE

I prefer to read articles about
… affairs in our town.

5. PRINT

I think CD books will be much
more popular with teenagers of my generation than … books.

IV.
Complete the sentences. Choose the correct variant.

Example: I’ve got a lot of …
(work/ works) to do for the weekend. –

I’ve got a lot
of work
to do for the weekend.

1. What (is/ are) her progress in
English?

2. (Is/ Are) there any news from Andy?

3. Where (is/ are) Granny’s glasses?

4. (Is/ Are) these goods from America?

5. I got a lot of useful (information/ informations).

6. Do you eat much (fruit/ fruits)?

7. I like any kind of (weather/ weathers).

V.
Complete the sentences. Choose the correct variant.

Example: My mother disapproved of … (to read/ reading)
thrillers. —

My mother
disapproved of reading thrillers.

1. I have never dreamed of (to win/ winning) a competition.

2. My sister always enjoys (to go/ going) for a walk.

3. The angry neighbour told the teenagers to stop (to speak/ speaking)
too loud.

4. Do you think she’ll manage (to pass/ passing) her Maths exam?

5. My mum is always at home. She quitted (to work/ working) last year.

6. The teacher reminded us (to bring/ bringing) some flowers to decorate
the classroom.

7. Linda suggested me (to drink/ drinking) a cup of tea now.

Обучайтесь и развивайтесь всесторонне вместе с нами, делитесь знаниями и накопленным опытом, расширяйте границы знаний и ваших умений.

поделиться знаниями или
запомнить страничку

  • Все категории
  • экономические
    43,633
  • гуманитарные
    33,652
  • юридические
    17,917
  • школьный раздел
    611,709
  • разное
    16,898

Популярное на сайте:

Как быстро выучить стихотворение наизусть? Запоминание стихов является стандартным заданием во многих школах. 

Как научится читать по диагонали? Скорость чтения зависит от скорости восприятия каждого отдельного слова в тексте. 

Как быстро и эффективно исправить почерк?  Люди часто предполагают, что каллиграфия и почерк являются синонимами, но это не так.

Как научится говорить грамотно и правильно? Общение на хорошем, уверенном и естественном русском языке является достижимой целью. 

Понравилась статья? Поделить с друзьями:
  • The cuss word song rusty cage на русском
  • The capabilities of excel
  • The curse word song
  • The c word game music
  • The current russian word for customs tamozhnya in the times of the mongol tatar yoke