blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d7252629d420dca47b5fc4910ebc93578f60bf44 | veritakim/study_python | /study_python/day9/loop_star.py | 902 | 4.15625 | 4 | '''
계단식으로 별 출력하기
증첩 루프
for i in range(횟수) # 바깥쪽 루프
for j in range(횟수) # 안쪽 루프
가로 처리 코드
세로 처리 코드
'''
for i in range(5):
for j in range(5):
print("*", end="")
print()
for i in range(5):
for j in range(5):
print(f"j:{j}", end=" ")
print(f"i:{i}\\n")
# 별 출력하기~
... | false |
67faf3c41b90be73374613ffe610e522d67117f8 | firewb/calculator | /calculator.py | 2,091 | 4.25 | 4 | #!/usr/bin/env python3
title = "This is a scientfic calculator created by firew shafi"
titlelen = len(title)
def intro():
'''Displays intro '''
title = "This is a scientfic calculator created by firew shafi"
titlelen = len(title)
print ('*'* titlelen)
print (title)
print ('*'* titlelen)
prin... | true |
283580e4683c241cb7f1d22d6302dbafda804736 | luisvmpcl/PYTHON3 | /diccionario1.py | 1,162 | 4.40625 | 4 | #22
#diccionario = {1: "Hola", 2: "Como estas", 3: "Bien"}
#print(diccionario)
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
print(diccionario)
"""
"""
diccionario = {
1:"Hola",
2:"Como estas",
3:"Bien"
}
diccionario = {} # aqui estoy redefiniendo el diccionario es decir va imprim... | false |
b5b93fef86f3d5a370da9057021a9f49e5a46cd3 | nair97/https-github.com-ABE65100-AUG-2020-assignment-1-python-learning-the-basics-nair97 | /Exercise_4.2_flower.py | 2,254 | 4.59375 | 5 | # -*- coding: utf-8 -*-
"""
Spyder Editor
To draw 3 set of flowers using turtle module
by Meera - 09-01-2020
"""
import math
import turtle
#math function provides all mathematical functions
#turtle module creates images
# import the tkinter graphics library tools. Note that is was called Tkinter for
# Python 2
from ... | true |
d6ffd6a761096bfe324a36cb0fca5ada4ecd9025 | ksjksjwin/practice-coding-problem | /CodeSignal/sortByHeight.py | 1,001 | 4.21875 | 4 | '''
Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!
Example
For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
sortByHeig... | true |
978d5951c4eda9a8af8b08a3fdd99c64586211c3 | ksjksjwin/practice-coding-problem | /LeetCode/isPalindrome.py | 919 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Copyright... | true |
ab5255c66430947348c194e9278a7e7056b41861 | benblaut/cse491-numberz | /fib_iter/example.py | 286 | 4.46875 | 4 | import fib
for n, i in zip(range(3), fib.fib()):
print i
# additional questions to address:
# - what the heck do 'zip' and 'range' do, and why are they there?
# "zip" iterates over two ranges, and "range" denotes a range from 0 to the number in parentheses (0-3, so a range of 4)
| true |
b7f5322889f87f3496af7cefced9db2bad56e168 | veena863/python-practice-01 | /practice02.py | 772 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[10]:
#Numbers
#1 Integers: Any plane digit is a integer
x=2;y=3;z=4
print(x,y,z)
#Advanced approach of assignment operator is
x,y,z=2,3,4
print(x,y,z)
# In[12]:
#2 Float:a number with a decimal number
x=1.2
y=2.2
print(x+y)
# In[15]:
#3 Constant:variable whose i... | true |
4cb827b971c2e9324355e96b1a3e838d349e57bb | ronl27/Python | /scores.py | 819 | 4.28125 | 4 | # Scores and Grades
# Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table:
#
# Score: 60 - 69; Grade - D
# Score: 70 - 79; Grade - C
# Score: 80 - 89; Grade - B
# Score: 90 - 100; G... | true |
1f33bddde1ca44bda6c8e9643f836cf3fbc130d4 | voidbert/PyTacToe | /CommentRemover.py | 2,016 | 4.59375 | 5 | #A file that removes comments in Python scripts. This is useful to reduce the
#size of the game file to save space on the calculator. Empty lines are also
#removed but comments after code aren't. Example:
#print("Hello, world") #This comment isn't removed
#Imported the needed sys module
import sys
#The function that ... | true |
2ab7dcde7fbf76a679aabb0876d9407a42ad53af | jalaldotmy/TTTK2053-Module5 | /Fundamentals/Input and Output.py | 2,254 | 4.1875 | 4 | #Task 1: Run the script and explain the implementation
## Break a name into two parts -- the last name and the first names.
fullName = input("Enter a full name: ")
n = fullName.rfind(" ") # index of the space preceding the last name
# Display the desired information.
print("Last name:", fullName[n+1:]) #n+1 will f... | true |
5bbbc0834d562b02263187aef04468dfff4bfe44 | AnaMaghear/Python-Beginner | /For.py | 670 | 4.125 | 4 | for letter in "casa": # ia fiecare element de dupa in
print(letter)
friends =["Maris","Ioana","Carla"]
for friend in friends:
print(friend)
print("\n")
for i in range(2, 7): # range i>=2 i<3
print(i)
print("\n")
for i in range(len(friends)): # lungime lista
print(friends[i])
print("... | false |
a91f4bfd2f64fb7edd7402f530750c361f12ccad | lmhbali16/algorithms | /ds_class/reverse_linkedlist.py | 871 | 4.1875 | 4 | '''
Given a singly linked list, we would like to traverse the
elements of the list in reverse order.
You are only allowed to use O(1) extra space,
but this time you are allowed to modify the list you are traversing.
Give an O(n) time algorithm.
'''
class Node:
value = None
next = None
def reverse_linkedlist(... | true |
5f906c021b941343d19836b6febbf4bf7d43a353 | dawidsielski/Python-learning | /sites with exercises/w3resource.com/Dictionatry/ex39.py | 201 | 4.15625 | 4 | d1 = {'key1': 1, 'key2': 3, 'key3': 2}
d2 = {'key1': 1, 'key2': 2}
d1_keys = d1.keys()
d2_keys = d2.keys()
for key in d1_keys:
if key in d2_keys:
print("key " + key + " is in d1 and d2")
| false |
bc2c386c4d4ebb8faa08d36db2224fe035338871 | brettjbush/adventofcode | /2016/day02/day02_2.py | 2,952 | 4.125 | 4 | #!/usr/bin/python
"""
--- Part Two ---
You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead... | true |
3f61528984edd34b56089cb42baf1672b63b61bc | jw56578/learn-python | /lesson3_functions.py | 893 | 4.4375 | 4 | import datetime
# copy and paste the below code 3 more times and print a different name
# a function is a group of code that needs to be called multipl times
# put the code in a function called printName so you don't have to keep typing the same code over and over
# call the function in place of where the duplicate co... | true |
2cd6234b044d42ef4cb0b418d4918a113aa35150 | polancof1182/CTI110 | /P3LAB_PolancoDelaRosa.py | 913 | 4.15625 | 4 | # CTI-110
# P3TLAB-Debugging
# Francicso PolancoDelaRosa
# 6/21/2018
def main():
# This program takes a number grade and outputs a letter grade.
# system uses 10-point grading scale
A_score = 90
B_score = 80
C_score = 70
D_score = 60
F_score = 50
score = int(input('Enter a nu... | true |
b3ceaba60dfe9edc7e2880f496b4af40d4de006b | luizffdemoraes/Python_1Semestre | /Exercicios/Média simples.py | 727 | 4.15625 | 4 | """
Descrição
Escreva um programa em Python3 que receba a altura de 4 pessoas, calcule e imprima a média final.
Formato de entrada
As entradas serão números reais positivos não nulos. Não deve ser impresso nenhum texto para pedir os dados de entrada.
Formato de saída
A saída devera ser formatada conforme ... | false |
d8210899c0be06b357438307e475b9ceaf5ffcaf | luizffdemoraes/Python_1Semestre | /AC/Contando múltiplos I.py | 1,343 | 4.15625 | 4 | """
Faça um programa que receba dois inteiros x e n, com x, n > 0 e x < n, e conte o número de múltplos de x menores do que n.
DICA 1: Os múltiplos de um número são obtidos multiplicando-se esse número pelos números naturais (1, 2, 3, 4, 5, ...)
DICA 2: No primeiro exemplo, os múltiplos de são: 7*1, 7*2, 7*3... | false |
642b969ea1602a3ec8ce277dc9c70e4ecadaf817 | TiredOfThisAll/Epam-hometsks | /task_5/task_5_ex_3.py | 978 | 4.25 | 4 | """
Create function sum_geometric_elements, determining the sum of the first elements of a decreasing geometric
progression of real numbers with a given initial element of a progression `a` and a given progression step `t`,
while the last element must be greater than a given `lim`. `an` is calculated by the formula (an... | true |
c1270a670156d7e931e9abd5b5b83c07d7d0cf45 | TiredOfThisAll/Epam-hometsks | /task_9/task_9_ex_2.py | 852 | 4.4375 | 4 | """
Write a function that checks whether a string is a palindrome or not.
Return 'True' if it is a palindrome, else 'False'.
Note:
Usage of reversing functions is required.
Raise ValueError in case of wrong data type
To check your implementation you can use strings from here
(https://en.wikipedia.org/wiki/Palindrome#... | true |
e436a7e9095e79717698bed17619ca6c4fa45d49 | yaremych/si206-ds4 | /code.py | 1,739 | 4.3125 | 4 | # function to return the factorial of a number
import unittest
# Add comments
def factorial(num):
ans = 1
if num < 0:
return None
elif num < 2:
return ans
else:
for i in range(1, num + 1):
ans = ans * i
return ans
# function to check if the input year is a l... | false |
398087d022d701825aa8022fa074294e0b222244 | ingadis/max_int.py | /max_int.py | 1,408 | 4.375 | 4 | north_int = int(input("Number of cars travelling north: "))
south_int = int(input("Number of cars travelling south: "))
east_int = int(input("Number of cars travelling east: "))
west_int = int(input("Number of cars travelling west: "))
north_south = north_int + south_int #the sum of north and south traffic
east_w... | false |
d40009682eb23ccbed804a8781cf7190d2582d46 | pruppet/Portfolio | /years.py | 486 | 4.34375 | 4 | #Author: Maggie Laidlaw
#Python program to find all Sundays that are the first
#of the month between 1901 and 2000.
def loopYears():
notLeap = [3,0,3,2,3,2,3,3,2,3,2,3]
leap = [3,1,3,2,3,2,3,3,2,3,2,3]
day = 2 #Su-0,M-1,...,S-6
year = 1901
count = 0
for x in range (1901,2000):
if x%100 != 0 && x%4 == 0:
fo... | false |
5c375468236c672ff6aeb1782282206600108197 | dooran/Aaron-s-Rep | /main2.19.py | 2,091 | 4.34375 | 4 | #Manuel Duran 1584885
#input the number so cups of lemon juice, water and agave nectar
cups_lemon_juice = float(input('Enter amount of lemon juice (in cups):\n'))
cups_water = float(input('Enter amount of water (in cups):\n'))
cups_agave_nectar = float(input('Enter amount of agave nectar (in cups):\n'))
# input th... | true |
614c4157f947e294c7b1fd451b11517866aff7e8 | CosmoSt4r/exercism-python | /easy/prime-factors/prime_factors.py | 809 | 4.15625 | 4 | """
Solution to Prime Factors task on Exercism
https://exercism.org/tracks/python/exercises/prime-factors
"""
def is_prime(value: int) -> bool:
"""Check if value is prime"""
if value == 1:
return False
if value <= 0:
raise ValueError("Value must be greater than zero")
for i in range(... | true |
1ff5af9c8380f4126ea35a8944e916b060a1a915 | CosmoSt4r/exercism-python | /easy/pythagorean-triplet/pythagorean_triplet.py | 499 | 4.1875 | 4 | """
Solution to Pythagorean Triplet task on Exercism
https://exercism.org/tracks/python/exercises/pythagorean-triplet
"""
def triplets_with_sum(number: int) -> list:
"""Get all pythagorean triplets which in sum give number"""
result = []
for a in range(1, number // 3):
for b in range(a + 1, (num... | false |
82f7fdb214f3dfea2dc1741721c84ead57626c08 | fehringj/Python-Coding-Exercises | /MyQueue.py | 1,591 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 10:13:17 2019
@author: Jenny
"""
# Requires Stack.py
from Stack import *
new_stack = Stack()
old_stack = Stack()
class MyQueue:
"""Implementation of a queue that is comprised of two stacks"""
def size(self):
r... | true |
0d9a6f03bf18ad832dab8db1e8994226127167d0 | zmengle/python_learn | /day/05.py | 406 | 4.125 | 4 | # 使用dict
dict1 = {'a': 100, 'b': 10}
dict1['c'] = 1000
dict1['c'] = 10000
print(dict1)
print('f' in dict1, 'a' in dict1)
print(dict1.get('c', 0), dict1.get('g', 0))
dict1.pop('c')
print(dict1)
# dict查询快 但是耗内存
# list查询慢 不耗内存
# 使用set(list) key唯一,set和dict的唯一区别仅在于没有存储对应的value
set1 = ([1, 2, 4])
print(set1)
set1.__... | false |
7a1a837e9ecd484294d547d4aff4676242d04c2a | AprajitaChhawi/365DaysOfCode.JANUARY | /Day 14 merge two sorted list.py | 2,187 | 4.125 | 4 | #User function Template for python3
'''
Function to merge two sorted lists in one
using constant space.
Function Arguments: head_a and head_b (head reference of both the sorted lists)
Return Type: head of the obtained list after merger.
{
# Node Class
class Node:
def __init__(self, data): # data -> ... | true |
9464a8f9fdeb1836c92d2e2d3d55bb2e55b669da | AprajitaChhawi/365DaysOfCode.JANUARY | /Day 21 reverse a string.py | 370 | 4.15625 | 4 | #User function Template for python3
def reverseWord(s):
s1=""
for i in range(0,len(s)):
s1+=s[len(s)-i-1]
return s1
#your code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == "__main__":
t = int(input())
while(t>0):
s = input()
print(reve... | false |
6dc622886e68061531b5f8a2fbd6a9367a1af767 | Saurabh9520/python-programs | /largest palindr.py | 1,282 | 4.25 | 4 | def isPalindrome(n):
# Find the appropriate divisor
# to extract the leading digit
divisor = 1
while (int(n / divisor) >= 10):
divisor *= 10
while (n != 0):
leading = int(n / divisor)
trailing = n % 10
# If first and last digits are
... | true |
4cd4d0c0e2af76e507dbf7ea9c9a967ea9122a18 | isaacMullen/Class-Projects | /my first game..py | 562 | 4.21875 | 4 | x = 67
print ('''Welcome to my game... You will be asked to choose a number between
1 and 100, The computer has also chosen a number between 1 and 100. The object
of this game is to eventually reach the same number as the computer. using
simple information you will be provided with in the form of <,>,=.''')
num1 =... | true |
dc625928f7ee963d49758b929564870304259e1c | AshwinShanbhag/Coursera_PythonCode | /Coursera Assignment 8.4_new.py | 692 | 4.46875 | 4 | """8.4) Open the file 'romeo.txt' and read it line by line. For each line, split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append
it to the list. When the program completes, ... | true |
16cb42d79ada5f327ca8ff3bb0e840028dc4d699 | DishenMakwana/Python-DS | /Python Data structures/stack2.py | 1,003 | 4.1875 | 4 | from collections import deque
class Stack():
def __init__(self):
self.stack = deque()
def push(self, value):
self.stack.append(value)
def pop(self):
if self.empty():
return 'Stack is empty'
return self.stack.pop()
def top(self):
if self.empty():
... | true |
1e0e064580cae963a11da5e4ab8c147cba83e53e | JaiJun/Codewar | /8 kyu/Is n divisible by x and y.py | 551 | 4.25 | 4 | """
Create a function that checks if a number n is divisible by two numbers x AND y.
All inputs are positive, non-zero digits.
I think best solution:
def is_divisible(n,x,y):
return n % x == 0 and n % y == 0
https://www.codewars.com/kata/5545f109004975ea66000086
"""
def is_divis... | true |
095443c6aa00d7a1cf26144fef51e0e6b3d368da | JaiJun/Codewar | /7 kyu/Unlucky Days.py | 1,008 | 4.21875 | 4 | """
Friday 13th or Black Friday is considered as unlucky day.
Calculate how many unlucky days are in the given year.
Find the number of Friday 13th in the given year.
Input: Year as an integer.
Output: Number of Black Fridays in the year as an integer.
Examples:
unluckyDays(2015) == 3
... | true |
5d5030661faa2593eae476df9f7cbb4d1991ccd5 | JaiJun/Codewar | /7 kyu/Mr Martingale.py | 2,349 | 4.28125 | 4 | """
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the Martingale strategy is.
You will be given a starting cash balance and an array of binary digits to represent a win or a loss as you play: 0 for loss and 1 for win.
You s... | true |
bb16544fcbd25a20e61072b7faffd6ac0f6ac114 | JaiJun/Codewar | /8 kyu/Is he gonna survive.py | 1,260 | 4.15625 | 4 | """
A hero is on his way to the castle to complete his mission.
However, he's been told that the castle is surrounded with a couple of powerful dragons!
each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.
Assuming he's gonna grab a specific given number ... | true |
1fa3180c91f2cd3b0d8114ff03bab5b75b71358b | JaiJun/Codewar | /7 kyu/Reverse a Number.py | 1,002 | 4.375 | 4 | """
Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321)
Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.
Examples
123 -> 321
-456 -> -654
1000 -> 1
I think best solution:
def reve... | true |
a96a4a83a1cf28935c8bff11bbe2e4b3899687fc | JaiJun/Codewar | /7 kyu/Disemvowel Trolls.py | 1,149 | 4.375 | 4 | """
Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example:
the string... | true |
776ef7eb8dcecc8c86da50a56cc5d218e6140d9d | JaiJun/Codewar | /7 kyu/Simple string matching.py | 2,128 | 4.3125 | 4 | """
You will be given two strings a and b consisting of lower case letters,
but a will have at most one asterix character.
The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters.
No other character of string a can be replaced.
If it is possible to re... | true |
741f0a0e4797077a17a64418ce9175a9ba85ddac | varunpandey0502/skyfi_labs_ml_workshop | /hands-on_introduction/2 - build_your_first_machine_learning_model - exercise.py | 1,853 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
#Import the train.csv file
sydney_file_path =
home_data =
#Step 1 - Specify the prediction target
#Select the target variable, which corresponds to the sales price. Save this to a new variable called `y`. You'll need to print a list of the columns to find the name of the... | true |
29d82ea0cd907107818cbf803a13fc185e16d50d | ishitadate/nsfPython | /Week 9/w9_homework.py | 498 | 4.125 | 4 | print("problem 1")
# write a simple example to show how 3 functions of your choice from the math and random libraries work.
print("problem 2")
# create something that takes command-line imput, does some mathematical calculations with the
# number inputted and some other random numbers, and returns something back
pri... | true |
dffccbd116d9b81b2bd5aa3de049ec7ebef46c56 | kavyareddi/level1_python | /program_4_class_inheritance.py | 1,015 | 4.125 | 4 | #program on class inheritance
#input : defining classe subclass and thier attributes
class Person:
# initializing the variables
# defining constructor
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
# defining class methods
... | true |
f8e16231cedbdf1526e2fa2c5ab4aa60f760821c | Nihaoaung/git-test | /for-loop.py | 291 | 4.125 | 4 | names=['aung aung','mg mg','su su','aye aye']
for name in names:
if name=='mg mg':
print(f'{name} is a tour guide')
break
else :
print(f'{name} is a forgein')
fruits=['apple','mango','orange','pineapple']
for fruit in fruits :
print(f'{fruit} is a fruit')
| false |
e3bb9036ba091d5a066d664368e51b13f0ab7252 | KenNyakundi01/Password-Locker | /user.py | 1,313 | 4.3125 | 4 | class User:
'''
This is the user class where the user is persisted to disk in a plain file
'''
user_list = [] # empty user list
def __init__(self, username, password):
'''
__init__ method that helps us define properties for our objects
Args:
username: New us... | true |
56bea18d5d3dfe7a2bc3e339cf5bad8577daa060 | agatanyc/section_normalization | /mysolution/matching.py | 2,971 | 4.25 | 4 | #!/usr/bin/env python
from string import ascii_uppercase
# some sections may have numerical ROW names (1-10) and some may have alphanumeric row names (A-Z, AA-DD). Your code should support both
def extract_integer(text):
"""Filters non-digits from text, and parses the result as an integer."""
try:
digit... | true |
168dc53740de4847cd82a81c34317b4373639a49 | cuauhtemocmartinez/python_projects | /Lab 1/CMartinezLab1.py | 1,528 | 4.3125 | 4 | #################################################################
# Program Header
# Course: CIS 117 Python Programming
# Name: Cuauhtemoc Alex Martinez
# Description: Lab 1
# Application: Hello World and infomation
# Topics: Using Python3 Interpreter and capturing program output
# Development Environment: Windo... | true |
5a6b854e94c511821e21f7e04e39c28a112f1d96 | plushies/py | /rps.py | 1,477 | 4.125 | 4 | from random import randint
cont = 'memes'
pscore = 0
cscore = 0
print('ROCK PAPER SCISSORS')
print('enter \'stop\' to end the game')
while cont == 'memes':
player = input('rock, paper, or scissors? ')
while player != 'rock' and player != 'paper' and player != 'scissors' and player != 'stop':
... | true |
59593f705c26af60ea691ed9de128691f39ac493 | bmandiya308/python_trunk | /pallendron.py | 226 | 4.28125 | 4 | def reversed(s):
rev = s[::-1]
return rev
input_str = str(input("Please enter string to check pallendrom"))
rev = reversed(input_str)
if(rev == input_str):
print("pallendrom")
else:
print("Not a pallendromj")
| true |
0c4c890525138446edcd5578cd431c6d289d92b4 | bmandiya308/python_trunk | /dict_order_dic.py | 419 | 4.375 | 4 | # A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
import string
print("This is a Dict:\n")
dict_1 =list(range(26))
dict_2 = list(string.ascii_lowercase)
d = {dict_1[i]:dict_2[i] for i in range(len(dict_1))}
for key, value in d.items():
print(key,value)
print("\nThis... | true |
3647001cacf70f7b0d550fb80e75ee2d5f114910 | RohanDeySarkar/DSA | /sorting_algo/2_insertion_sort/insertionSort.py | 370 | 4.15625 | 4 | def insertionSort(arr):
for i in range(1, len(arr)):
currentIdx = i
while currentIdx > 0 and arr[currentIdx] < arr[currentIdx - 1]:
swap(arr, currentIdx, currentIdx - 1)
currentIdx -= 1
return arr
def swap(arr, idx1, idx2):
arr[idx1], arr[idx2] = arr[idx2], arr[idx1]... | true |
6151b44413b5c121ae437edcae4132ad7cf10424 | requestriya/Python_Basics | /basic27.py | 277 | 4.15625 | 4 | # wap to sum of three numbers given integers. however, if two values are equal sum will be zero
def sum_nums(n1, n2, n3):
if (n1 == n2 or n1 == n3 or n2 == n3):
sum = 0
else:
sum = n1+n2+n3
return sum
print(sum_nums(2,4,5))
print(sum_nums(2,2,2)) | false |
c9549a896f442252f998a5a784da381dccdee559 | requestriya/Python_Basics | /basic60.py | 357 | 4.59375 | 5 | # Write a Python program to check whether a string is numeric.
# 1.
val = '12345'
count = 0
for i in val:
if (ord(i)>=48 and ord(i)<=57):
count+=1
else:
print('has alpha values')
break
if count == len(val):
print('val has only numeric value')
# 2.
if val.isdigit():
print('its n... | true |
373acac5374b31482cb2f0121d48e0ca79edeafc | requestriya/Python_Basics | /basic54.py | 229 | 4.125 | 4 | # define a string that has alphanumeric letters and print only alphabet from that string
dec = 'ABc5d90uibdy56h38$!a'
for i in dec:
if (ord(i)>=65 and ord(i)<=90) or (ord(i)>=97 and ord(i)<=122):
print(i, end=' ')
| false |
c6608f837bf7d38af00ad6af3af1ceba22f0a28f | j3py/cracking_codes | /caesar_cipher.py | 2,382 | 4.15625 | 4 | # Caesar Cipher
import pyperclip
import cipherrandom
def main():
# the string to be encrypted/decrypted
message = input('Enter message: ')
# whether the program enc or dec
mode = input('Type e for encrypt or d for decrypt: ')
# every possible symbol that can be enc:
SYMBOLS = 'ABCDEFGHIJKLM... | true |
44459258bdde077daa7e3ed2775c2f79e19b7d3b | eaglerock1337/realpython | /part1/1.1-1.9/find.py | 273 | 4.125 | 4 | print("AAA".find("a"))
name = "Version 2.0"
ver = 2.0
print(name.find(str(ver)))
string = input("Please enter a string: ")
search = input("Please enter a search character: ")
print("The result of searching '{}' for '{}' is {}.".format(string, search, string.find(search)))
| true |
3a13c13c28e5b18fd24578568b3c50e6eb053ca2 | rituteval/collatz | /collatz.py | 494 | 4.40625 | 4 | # The number we will perform the collatz operation on.
n = int(input("Enter a positive integer:"))
# Keep looping until we reach number 1.
# Note: This is assumes the collatz conjecture is true.
while n != 1:
# Print the current value of n.
print (n)
#Check is n is even.
if n % 2 == 0:
# If n is e... | true |
3099d9b4450c63646d2a63658edb9b11a4d40613 | Sergei729/Python_begin | /Task_4.py | 718 | 4.15625 | 4 | # Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
def my_func(x, y):
... | false |
7ca49776529709e5f0892f41e0c229e1a4548822 | tayyabmalik4/pandas_in_python | /14_interpolate_#2_pandas_practical.py | 1,737 | 4.5625 | 5 | # *****************Interpolate function using pandas linbray in python******************
# discuss about-----parameters of interpolate-----------method,axis,limit,inplace,limit_direction,limit_area
import pandas as pd
inter1=pd.read_csv('F:\\tayyab programming\\machine learning\\pandaswithtayyab\\05_using_write_the... | true |
a121eb4f526d1c1d0eddd7c6c40674582afcc825 | tayyabmalik4/pandas_in_python | /10_Handling_missing_values_#03_pandas_practical_09.py | 2,807 | 4.59375 | 5 | # ******************************Handling Missing values part 3 using pandas in python*****************************
# /////discuss about (dropna(values,method,axis,how,subset,thresh,inplace))
# /////dropna() function basically which colums or rows are exists the empty values and we want to drop this colums or rows tha... | true |
344701e7c5b2f5410f4155127c1777969dc50f2a | tayyabmalik4/pandas_in_python | /02_Series_pandas_practical_01.py | 2,658 | 4.15625 | 4 | # ////////series in pandas/////////////////
# //////Series is a one dimentional array in pandas
# //////
# ****************import the pandas library
import pandas as pd
# //////checking the version of pandas
# /////the verion is 1.3.0
# print(pd.__version__)
lst=[1,2,-3,6.2,'data values']
# print(lst)
# ********... | true |
972166aa22c08efe01fceb483298ecb61c803f2b | ocslegna/hackerrank | /hackerrank/Python/Collections/namedtuple.py | 772 | 4.34375 | 4 | #!/usr/bin/python3
"""
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Named tuples are especially useful for assigning field
names to result tu... | true |
d807e356e346c5348197311aa88aac7ab543af5a | minasel/GEOS636_PAG | /listings/io_wite.py | 712 | 4.125 | 4 | fname = "io_print.txt"
#1) open this file in read mode
print("Example 1")
print("--------------------Start")
my_file = open(fname, "r")
#print the entire thing
print(my_file.read())
#close the file
my_file.close()
print("--------------------End")
#2) print a two lines of the file
print("Example 2")
print("----------... | true |
30d006b121bda4a42bb623f0eab1c9baf3c42dbd | Chaitanya-Raj/PyLearn | /SimpleCalculator.py | 650 | 4.125 | 4 | import os
print("Welcome to Simple Calculator")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
print("5.Modulus")
print("6.Exponentiation")
choice = int(input("Choose an option : "))
print()
x = float(input("Enter the first number : "))
y = float(input("Enter the s... | true |
4df2681be502fd1dd5d1efff5022b24e5699dca3 | DouglasBavoso/ExerciciosPraticaPython | /ex065MaiorMenorValores.py | 840 | 4.15625 | 4 | # =================== MAIOR E MENOR VALORES ================================
# Crie um programa que leia varios numeros inteiros pelo teclado
# No final da execucao, mostre a media entre todos os valores e qual foi a mair e menor valores lidos
# O programa deve perguntar ao usuario se ele quer ou nao continuar a digita... | false |
53a8765a33abbc2f03cd581ae1df8936542d96a2 | DouglasBavoso/ExerciciosPraticaPython | /ex024VereficandoAsPrimeirasLetrasDeUmTexto.py | 309 | 4.1875 | 4 | # ============================ VERIFICANDO AS PRIMEIRAS LETRAS DE UM TEXTO =============================================
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou nao com o nome "SANTO"
cid = str(input('Em que cidade você nasceu? ')).strip()
print(cid[:5].upper() == 'SANTO') | false |
c0000e107d0c36eb4f5b5f00fba30a80c3213ba2 | samyak1903/Decision_Making | /A4.py | 1,021 | 4.28125 | 4 | '''Q.4- Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service.
1. if employee is female, then she will work only in urban areas.
2. if employee is a male and age is in between 20 to 40 then he may work in anywhere
3. if employee is male and age is... | true |
e1b7def14c817489a104e200dc255bb376324bcd | zayarmyothwin/programming-basic-python | /code/math.py | 501 | 4.25 | 4 | x=input("Enter first value : ")
y=input("Enter second value : ")
op=input("Operator + - * / : ")
try:
x=int(x)
y=int(y)
output=True
if op=="+":
result=x+y
elif op=="-":
result=x-y
elif op=="*":
result=x*y;/
elif op=="/":
result=x/y
else :
output = ... | false |
beae28fba50dbfa69d98aa8ab5201c0a25ac4645 | aleksiheikkila/AdventOfCode2019 | /day01/The_Tyranny_of_the_Rocket_Equation.py | 1,584 | 4.15625 | 4 |
# to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
def calc_fuel_req(mass: int) -> int:
return (mass // 3) - 2
# Unit tests
#For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
#For a mass of 14, dividing by 3 and rounding down still ... | true |
f5675d3dfe845e6522c1e418eb3e846720ad250b | ArnabBasak/PythonRepository | /progrms nltk/stop words.py | 657 | 4.1875 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentence = "this is a first sentence written by me in the nltk python."
stop_words = set(stopwords.words("english"))
print('original sentence is',example_sentence)
#print(stop_words)
words = word_tokenize(example_sentence)
filtered_sente... | true |
bdd31b8913b5e2480dada2e1f4092aa4cd251b59 | ArnabBasak/PythonRepository | /Python_Programs/PythonCode/Dice_Rolling_Simulator.py | 1,969 | 4.5625 | 5 | """
1. Dice Rolling Simulator
The Goal: Like the title suggests, this project involves writing a program that simulates rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print ... | true |
299a505a01a4b9180c53a461882f5ee26b4b4107 | ArnabBasak/PythonRepository | /python programs/posnegnumber.py | 282 | 4.34375 | 4 | number = int(input("enter any number it can be postive negative or 0"))
if number == 0:
print("the number is nither negative nor postive its 0")
elif number>0:
print("the numer is postive")
elif number<0:
print("the number is negative")
else:
print("invalid input")
| true |
71bc39777c133295ca95cf2c16b33feae0186086 | MxValix/corso_data_science_python | /5nov.py | 999 | 4.375 | 4 | # Test Case 1
# Enter your annual salary: 120000
# Enter the percent of your salary to save, as a decimal: .10
# Enter the cost of your dream home: 1000000
# Number of months: 183
#
# Test Case 2
# Enter your annual salary: 80000
# Enter the percent of your salary to save, as a decimal: .15
# Enter the cost of your dre... | true |
b1a2365c9c26db6bc0702c5ecf7537c5fc9dfeae | ashleyabrooks/code-challenges | /polish_calculator.py | 1,144 | 4.25 | 4 | """Calculator
>>> calc("+ 1 2") # 1 + 2
3
>>> calc("* 2 + 1 2") # 2 * (1 + 2)
6
>>> calc("+ 9 * 2 3") # 9 + (2 * 3)
15
Let's make sure we have non-commutative operators working:
>>> calc("- 1 2") # 1 - 2
-1
>>> calc("- 9 * 2 3") # 9 - (2 * 3)
3
>>> calc("/ 6 - 4 ... | false |
3e0e0258c387fdcd702a446e0d8f8265ac72ad23 | avyuktitech/DXCRepo | /Python_Calculator.py | 975 | 4.3125 | 4 | # This was Sample Python script
# Basic Calculator:
# This function performs additiion
def add(a, b):
return a + b
# This function performs subtraction
def subtract(a, b):
return a - b
# This function performs multiplication
def multiply(a, b):
return a * b
#This function performs divisi... | true |
db14964251ed0383169d71315f0208de6cfe7509 | TechbirdsYogendra/DataStructureExercisePython | /recursion.py | 525 | 4.125 | 4 | # This funcion returns factoril of a number.
def factorial(n):
if n == 0 or n == 1:
return 1
elif n < 0:
return 0
else:
return n * factorial(n-1)
n = 5
fact = factorial(n)
print(f"Factorial of {n} is {fact}.")
# It returns nth numner in Fibonacci series.
def fibonacci(n):
if ... | true |
44d926fffff7a4f11a052faadc042496ffebeb49 | jPUENTE23/ESTRUCTURA-DE-BASES-DE-DATOS-Y-SU-PROCESAMIENTO-3ER-SEMESTRE | /Ejemplos/04_importacion_datetime.py | 1,480 | 4.25 | 4 | '''
Ejemplo para ilustrar la importación de la librería datetime en Python 3
Demuestra el uso de: hora, fecha y aritmética de fechas
'''
import datetime
import time
SEPARADOR = ("*" * 20) + "\n"
#Creación de una hora específica
hora = datetime.time(10, 20, 30)
print(f"El tipo de objeto de la hora es {type(hora)}")
pri... | false |
f475c34f064940629f995f092b5cbd5d3a1bd569 | sohye-lee/algorithm_study | /9498.py | 359 | 4.125 | 4 | score = int(input(""))
def grade(score):
if score > 100 or score < 0:
return
if score >= 90 and score <= 100:
print("A")
elif score < 90 and score >= 80:
print("B")
elif score < 80 and score >= 70:
print("C")
elif score < 70 and score >= 60:
print("D")
e... | false |
2c3d384f7671d2db709bb0381168eca461595e2d | runningshuai/jz_offer | /48.不用加减乘除做加法.py | 690 | 4.125 | 4 | """
题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
思路:
①不考虑进位:两个数之和是异或
②计算进位:求与,左移一位
若②不为0,就继续①②步
"""
class Solution:
def Add(self, num1, num2):
# write code here
if not num1:
return num2
elif not num2:
return num1
while num2:
num1, num2 = (num1 ^ nu... | false |
b5999e8997bb3450f85dc92493c2cab17639a1f6 | mmeysenburg/ccla-hpc-workshop | /src/optimizing-python/function-alias/exercise02.py | 403 | 4.15625 | 4 | '''
Function alias exercise 2
Convert cartesian coordinates to polar.
'''
import math
import random
# create n cartesian coordinates in the unit square
n = 1_000_000
uni = random.uniform
cartesians = [(uni(-1, 1), uni(-1, 1)) for i in range(n)]
# write code here to create a new list called polars.
# the new list sh... | true |
f275b55d7ee2ce5aa69e40898b8a846a7033d386 | Ahsank01/FullStack-Cyber_Bootcamp | /WEEK_1/Day_1/7_Forwards_Is_Backwards.py | 928 | 4.625 | 5 | #!/usr/bin/env python3
"""
The path to the input file will be passed into your program as a command line argument when your program is called.
Write a program that receives a single word as input and checks to see if the word is a palindrome
(i.e. words that look the same written backwards).
"""
import sys
... | true |
7a00269839623ccf7c805152f61711d543f4a721 | Ahsank01/FullStack-Cyber_Bootcamp | /WEEK_1/Day_1/8_Lines.py | 829 | 4.125 | 4 | #!/usr/bin/env python3
"""
Your boss handed you a simple task, just replace the "newlines" from the provided file with spaces...
(hint - it's not just that simple)
"""
# Import the 'sys' module
import sys
def lines():
# Get the name of the file from the command line arguments
file_name = sys.arg... | true |
8ca87f709db67790f37e7e77d762eb00261d0e0a | PashaKim/Python-Function-for-basic-math-operation | /Basic-Math-Operations.py | 653 | 4.6875 | 5 | #Write the function "arnntetik", taking 3 arguments:
#the first 2 - the number, the third - the operation that should be performed on them.
#If the third argument is +, add them; If -, then subtract; Multiply; / - divide (the first into the second). In other cases, return the string "Unknown operation" ..
print ("Hi. ... | true |
6ea19b0d8bdb75aa46b59db78ba90f608ec65047 | bosskeangkai/Python-Math-Solving | /max_min.py | 1,025 | 4.15625 | 4 | # input three number and then check what is the max or min number and then finally show on your screen
# while loop 5 time
# คำสั่ง if เเบบ 1 ทางเลือก
# do only if for check
# initail
max = 0
min = 0
n = 1
# process
# while loop check if n <= 5 loop
while n <= 5:
x = int(input("Enter your X numbe... | true |
6f036986207dfaf22e0a7e8af4e71edf12ed478c | MatthewTurk247/Programming-II | /Recursion.py | 764 | 4.375 | 4 | # Recursion: functions calling themselves
# Functions calling functions
def f():
g()
print("f")
def g():
print("g")
f()
# Functions calling themselves
def hello():
print("hello")
hello()
# hello()
# helpful uses: searching files
# We can control the recursion depth
def controlled(level, end_le... | true |
e18137c5524499290af0cdbdfdbf4e8a0a0563da | ValentynaGorbachenko/cd2 | /ltcd/matrixReshape.py | 2,259 | 4.34375 | 4 | '''
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped... | true |
7e4b0c59f46428157c01a81fbbcfcbc1d42a9e08 | jheyer23/python_gdal | /Functions.py | 524 | 4.21875 | 4 | # Writing functions in Python
#Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
# Functions in python are defined using the block keyword "def", ... | true |
bfe48ca69a214ffd51785329ca332be465a99bd1 | jheyer23/python_gdal | /Dictionaries.py | 984 | 4.59375 | 5 | # Storing items in dictionary
# Different attributes - name, email, phone, etc.
# Key value pairs (Key: name, email, phone). Each key has value
# Keys need to be unique in a dictionary - cannot duplicate
# Values of keys can be any data type
customer = {
"name": "John",
"age": 30,
"is_verified": Tru... | true |
d71a573e079571fb6033bc22c03438b4c0a9b7c3 | dressaco/Python-FiapOn | /Cap02Pt02_Decisoes/Ex02_DecisaoComposta.py | 774 | 4.15625 | 4 | name = input('Digite o nome: ')
age = int(input('Digite a idade: '))
contagious_susp = input('Suspeita de doença infecto-contagiosa (S/N)?').upper()
if age >= 65 and contagious_susp == 'S':
print('O paciente ' + name + ' será direcionado para a sala AMARELA - COM prioridade')
elif age < 65 and contagious_susp == 'S'... | false |
b28ca5390ed22e9860761f7dcfccf1ff9ca868ac | Neeraj-Palliyali/chegg_python | /test.py | 410 | 4.3125 | 4 |
# getting account number
accountNo=input("Enter the 8 digit account number:")
# try catch for if the input cannot be converted to integer
try:
account=int(accountNo)
# if the length is not equal to 8
if(len(str(account))==8):
print("The account number is valid")
else:
print("Invalid ... | true |
c9ab498ac08db9fe6d289bc7ebc2fa4b3a173738 | Freire71/treinamento-python | /exercicios/modulo-4/exercicio-3.py | 512 | 4.15625 | 4 | # Dada uma lista com os nomes = ["Tony Stark", "Peter Parker", "Thor"]
# Crie uma nova lista contendo a primeira letra de cada nome na lista, converta essa caractere para minusculo
# Faça essa operação utilizando compreensão de listas e um loop tradicional
# Compare os 2 métodos
nomes = ["Tony Stark", "Peter Parker", ... | false |
e944d86b29c424384cf1e35c2593220107a8d9d1 | reggiemccoy/python_code | /tempature/converter.py | 305 | 4.25 | 4 |
print("Welcome to my conversion project for measurements")
cm = int(input(" please enter in cm: \n")) # making sure the data entered is integer
# and then make the text appear on a new line
conVertthis =(.39*cm)
print(conVertthis)
print("inches")
foot = (conVertthis/12)
print(foot)
print("feet")
| true |
23578f985e19392effd465752c3fe289c0431fe5 | reggiemccoy/python_code | /compare/compare_sting_input.py | 271 | 4.25 | 4 | # String compare in Python with input
str_input1 = input("Enter First String? ")
str_input2 = input("Enter Second String? ")
# comparing by ==
if str_input1 == str_input2:
print("First and second strings are same!")
else:
print("You entered different strings!") | true |
a6d5b82a61dda2ff6693d5fac779d175690fc451 | duncandill/Age | /age.py | 1,306 | 4.15625 | 4 | def question():
answer = None
while answer is None:
print ("Welcome to AGE\n please enter your age.")
answer = input("How old are you?\nEnter a number from 0 to 99 ")
try:
answer = int(answer)
if answer >99 or answer < 0:
answer = None
... | true |
39f208f932dfb344b589ee8c69e12432bcde3e8d | arcadecoder/Rosalind-algorithms | /RabbitsandRecurrence.py | 838 | 4.46875 | 4 |
def Fibonacci_loop_rabbits(months, offsprings):
"""
1. Initially assign 1 parent and one child. This is the first set of offspring.
2. Loop over the number of months (minus 1 - we already had the first month)
3. The child becomes a parent, so given a new value (still 1)
4. The child value is now th... | true |
7273758e0cced965db85a7dbc850da8439b45588 | varnitmittal/quarantine-coding-revision | /DS/Queue/deque_incomplete.py | 1,360 | 4.15625 | 4 | #Deque implementation
class Deque:
def __init__(self, *args):
self.max = 5
self.deque = []
self.front = -1
self. rear = -1
self.display()
def isFull(self):
return False
def insertFront(self, x):
if self.isFull():
print("Can't insert,... | true |
f78cc4d4d4456a10f09d870bfd0385f2bc588431 | baleshwar-mahto/cse-using-python | /sqplot.py | 537 | 4.34375 | 4 | #python 3 program to plot x^2 and x^3 function on same graph
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize']=5,3
#figure of the size 5in x 3in
x=np.linspace(-1,1,10)
y=x**2
y1=x**3
plt.plot(x,y,'r.',label=r'$y=x^2$')
plt.plot(x,y1,lw=3,color ='g',label =r'$y=x^... | true |
130a86a145641063007d47126c2aab88150a3c76 | SHJoon/Algorithms | /arrays/5_reverse.py | 496 | 4.40625 | 4 | # Reverse Array
# Given a numerical array, reverse the order of the
# values. The reversed array should have the same
# length, with existing elements moved to other
# indices so that the order of elements is reversed.
def reverse_array(lst):
for i in range(len(lst) // 2):
temp = lst[i]
lst[i] = ls... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.