blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1c99ed5b4de5c4625b7eaf80ebbbf6629ac8f63a | thaReal/MasterChef | /codeforces/round_619/three_strings.py | 263 | 3.515625 | 4 | #!/usr/bin/python3
# Codeforces Round 619
# Problem #1 - Three Strings
t = int(input())
for case in range(t):
a = input()
b = input()
c = input()
sol = "YES"
for i in range(len(a)):
if c[i] != a[i] and c[i] != b[i]:
sol = "NO"
break
print (sol)
|
38fb82fe432ccecf3b1d4da46657929cacfb5eae | manchenkoff/geekbrains-python-homework | /lesson06/task04.py | 2,577 | 3.5 | 4 | """
Реализуйте базовый класс Car.
У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).
Опишите несколько дочерних классов: TownCar, SportCar, W... |
2627b435fe6db21c23b5ba4e314b252836e29834 | santiagoPinzonD/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 952 | 3.90625 | 4 | #!/usr/bin/python3
"""create function"""
def matrix_divided(matrix, div):
"""create function that divide elements of a matrix"""
new_matrix = []
if matrix:
for x in range(0, len(matrix)):
new_matrix.append([])
for z in matrix[x]:
if type(z) != int and type(z... |
dffdcc0ea3ed718e78a03cc8682748fde493c921 | 16030IT028/Daily_coding_challenge | /Algoexpert-Solutions in Python/Group by Category/Dynamic Programming/01_Max_Subset_Sum_No_Adjacent.py | 1,781 | 3.703125 | 4 | # https://www.algoexpert.io/questions/Max%20Subset%20Sum%20No%20Adjacent
"""
Maximum Subset Sum With No Adjacent Elements
Write a function that takes in an array of positive integers and returns an integer representing the maximum sum of non-adjacent elements in the array. If a sum cannot be generated, the function ... |
8a732cef40644144b7ed2a400e0db8184aa338eb | jacskiier/VLFNavigation | /deeplearningfiles/logistic_sgd.py | 25,511 | 4 | 4 | """
This tutorial introduces logistic regression using Theano and stochastic
gradient descent.
Logistic regression is a probabilistic, linear classifier. It is parametrized
by a weight matrix :math:`W` and a bias vector :math:`b`. Classification is
done by projecting data points onto a set of hyperplanes, the di... |
5ce17f1bf2327adb05efafeeca7ef13b2cb6e24a | HardlyBriefDan/aquafina | /src/grouping.py | 3,267 | 3.65625 | 4 | # Grouping class has several methods that return index values of whatever led
# strand length is passed in
import math
import random
class Grouping():
def __init__(self,pixel_strand):
self.pixels = pixel_strand
self.pixel_count = len(self.pixels) # to eliminate the number of times we call fo... |
a6204c5065e326f60b3535b0fd3dcb646ecd27f2 | xxweell/exerciciosPython | /ex008.py | 301 | 4 | 4 | medida = float(input('Digite a medida em Mts: '))
km = medida/1000
hm = medida/100
dam = medida/10
dm = medida*10
cm = medida*100
mm = medida*1000
print('A medida de {}m corresponde a: '.format(medida))
print(km, 'km')
print(hm, 'hm')
print(dam, 'dam')
print(dm, 'dm')
print(cm, 'cm')
print(mm, 'mm')
|
826550ee62029fff7f61bf987598ee0125413a49 | tsamridh86/RSA | /decryptor.py | 1,387 | 4.375 | 4 | # this code converts cipher text into msg & displays it to the user
# this functions converts the cipherText into number format plainText
def decrypt( cipherText, publicKey, divisorKey , blockSize):
i = 0
lenCipherText = len(cipherText)
plainText = []
while i < lenCipherText:
copyBlockSize = blockSize
numArr =... |
8db7059e0bc10f334913e690dff0fedce2feaa41 | julie98/Python-Crash-Course | /chapter_5/age_test.py | 264 | 3.875 | 4 | age = 65
if age < 2:
print("He is an infant.")
elif age < 4:
print("He is learning to walk.")
elif age < 13:
print("He is a child.")
elif age < 20:
print("He is a teenager.")
elif age < 65:
print("He is a grown-up.")
elif age >= 65:
print("He is a senior.") |
7bd4a4b07d5acb0592c4ac6f2d1d1fd1124b8f06 | satrini/python-study | /exercises/exercise-18.py | 95 | 3.6875 | 4 | # Natal city
city = str(input("Your natal city:")).strip().lower()
print(city[:5] == 'santo') |
c040e588917bf312a543a317995621d1ceedfafa | lodi-jesse/aula_python | /desafio093.py | 675 | 3.59375 | 4 | lista_dec = {}
lista = []
soma = 0
lista_dec['nome']= str(input('Nome do jogador: '))
n = int(input('Quantas partidas ele jogou? '))
for i in range(0,n):
lista.append(int(input(f'Quantos gols na {i +1}º partida: ')))
lista_dec['gols']= lista[:]
for i in range(len(lista)):
soma += lista[i]
lista_de... |
2240f9ffb17f83dc9c3c0381b3d2aa987e0ea328 | justinliuyuwang/Bubble-Merge-Quick-Sort-Comparisons | /Bubble-merge-quick-sort-comparison.py | 12,355 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 9 23:22:53 2017
@author: justin
This program compares the average amount of time it takes bubbleSort, recursive mergeSort, and recursive quickSort to sort through the same sequences of various sizes.
WARNING - in order to run, this program raises the recursion limit set ... |
0dc7ff5842aa6a40390ee4287fe2de72e09acf0f | andeemarks/exercism | /python/rotational-cipher/rotational_cipher.py | 558 | 3.609375 | 4 | """docstring"""
import string
LOWER_PLAINTEXT = string.ascii_lowercase
UPPER_PLAINTEXT = string.ascii_uppercase
def rotate(text, key):
"""docstring"""
key = key % 26
transposed_lower_letters = "".join(
(2 * list(LOWER_PLAINTEXT))[key:(key+26)])
transposed_upper_letters = "".join(
(... |
d2ac5ed2563606919d4911c365e0b9f9ce4ab1ef | Breccia/s-py | /sp/nug.py | 1,122 | 4.5 | 4 | #!/usr/local/anaconda3/bin/python
# program to plot Gravitational Force vs Distance graph
# Newton's Universal Gravitational Law
import matplotlib.pyplot as plt
# F = Gm1m2/r^2
# Gravitational constant
G = 6.674 * (10**-11) #m^3/kg.s^2
def plot_graph(m1, m2, d_min, d_max):
print("User input mass 1 = {0} kg, ma... |
cd2d080d09b52823ea0b7e3255cc2dd3875e14bb | Lzffancy/Aid_study | /fancy_month01/day14_fancy/day14_teacher/demo05.py | 971 | 3.96875 | 4 | """
yield
"""
class StudentController:
def __init__(self):
self.__list_students = []
def add(self, stu):
self.__list_students.append(stu)
# def __iter__(self):
# 生成迭代器代码的大致规则:
# 1. 将yield关键字以前的代码存入__next__函数体
# 2. 将yield关键字以后的数据作为__next__函数返回值
# index = 0
# yield ... |
312c7acadf2e08cf16cfa91defb2ff49c34e5e2b | PawarKishori/HDTB_Query_engine | /Treebank.py | 3,459 | 3.796875 | 4 | # author:- Bhavana Saraswat M.Tech Banasthali University 2016-2017
import Modules
i=1
print("\t Select option by number given below:\n\t1:- To obtain vibhakti and it corresponding karak-lists.\n\t2:- To obtain sentences corresponding to vibhakti and karak.\n\t3:- To extract words of given POS or category and karak havi... |
94c816c523e8119a30800db5909fece521d3b249 | SaiSujithReddy/CodePython | /PalindromicSubstrings_v1.py | 1,242 | 4.09375 | 4 | '''
647. Palindromic Substrings
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic ... |
e2bfb653e9428a0cfa423935b36524c9b54a0528 | yuzumei/leetcode | /面试题(17.13).py | 967 | 3.6875 | 4 | dictionary = ["looked","just","like","her","brother"]
sentence = "jesslookedjustliketimherbrother"
class Trie:
def __init__(self,words):
self.root={}
self.length=0
for word in words:
self.length=max(self.length,len(word))
node=self.root
for c in word:
... |
6d27120808f56a7ccf75e3057b790f8236d5624e | schef/pp_curses | /getkey.py | 327 | 3.59375 | 4 | #!/usr/bin/python3
import curses
def main(stdscr):
y = 0
x = 0
while True:
c = stdscr.getch()
if c == ord('q'):
break # Exit the while loop
else:
stdscr.clear()
stdscr.addstr(y, x, curses.keyname(c))
stdscr.refresh()
curses.wrapper... |
099916ea34321fb85813f92187d2c24180956b74 | tanmaymohite/my-python-practice | /primeNumber.py | 196 | 4.125 | 4 |
n = input("\nEnter a number: ")
n = int(n)
d = 2
while d < n:
if n % d == 0:
break
d = d + 1
if d == n:
print("\nNumber is prime")
else:
print("\nNumber is not prime")
|
76dbe1d351997eb319b32755a686737fe1c0cda5 | LowerDeez/grasp-gof-patterns | /interpreter/main.py | 3,636 | 3.765625 | 4 | from abc import ABC, abstractmethod
from typing import List
class Pizza:
properties: dict
def __init__(self):
self.properties = dict()
def __repr__(self):
parts = ', '.join([key for key in self.properties.keys()]).upper()
return f"Pizza \"{parts}\" properties: {self.properties}"
... |
6b5ee4d917bc21c584b0301af6eef35062f3ae1b | Mugala/Project-Euler | /Prob_6/solution.py | 283 | 3.8125 | 4 | def square_root():
list_b = []
y = int(input())
list_a = range(1,y+1)
for i in list_a:
x = i**2
list_b.append(x)
total = sum(list_b)
print(total)
square_root()
def sum_square();
list_c = []
print(list_a)
sum_aquare() |
251a109e8e9a941373abe292b14f1847f690ff17 | rennergade/project-euler | /euler1.py | 124 | 3.9375 | 4 | #!/usr/bin/python
total = 0
for x in range(0, 1000):
if (x % 3) == 0 or (x % 5) == 0:
total = total + x
print(total)
|
ac6f4a4aa431f517afbc6e9db9c792489cb8964e | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/rddkum001/question2.py | 747 | 3.90625 | 4 | """Calculating change from a vending machine
Kumaran Reddy
16 April 2014"""
#Stipulate the amounts that can be used
denominations = [[100, '$1'], [25, '25c'], [10, '10c'], [5, '5c'], [1, '1c']]
cost=eval(input("Enter the cost (in cents):\n"))
paid=0
#To ensure user deposits more moeny than actual cost
while p... |
cfa407011010aef35888744f742138b1e5497c2a | kyosukekita/ROSALIND | /Algorithmic Heights/median.py | 379 | 3.625 | 4 | file = open('Desktop/Downloads/rosalind_med.txt').read()
n=int(file.split()[0])
A=[int(i) for i in file.split()[1:n+1]]
k=int(file.split()[-1])
def qSort(a):#クイックソート
if len(a) in (0,1):
return a
p=a[-1]
l=[x for x in a[:-1] if x<=p]
r=[x for x in a[:-1] if x>p ]
return qSort(l)+[... |
39aacd4ffe74860fdc031030344feb65e713486c | muzavan/py-interviewbit | /dynamic_programming/max_sum_path_in_binary_tree.py | 794 | 3.78125 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def maxPathSum(self, A):
dp = {"max": -99999}
self.ma... |
9a09f0452a83dc3dfbb5df6a49f4015571dd7a2d | famaxth/Way-to-Coding | /MCA Exam Preparations/Python/4. Write a python program to read a text file and print each word.py | 265 | 3.75 | 4 | def main():
file = open("sample.txt","r")
file_list = file.readline().split()
file_min_list = list(set(file_list))
file_min_list.sort()
for each in file_min_list:
print(each," : ",file_list.count(each))
file.close()
main()
|
4420cf7f2b3f2d6eeeaf025719837fb61e47b242 | pattman96/Tonnage-Limitation | /Tonnage_Limitation.py | 1,729 | 4.03125 | 4 | # Import the functions that calculate the separate brackets
from TL_Functions import *
############################################################
# Get user to set vessel name
vessel_name = input('Enter vessel name:')
# Get user to set vessel weight
weight = int(input('Enter vessel weight in tons:'))
# Print expla... |
826d7c4601d57b96cd35fd54f71b24e45e3e75e1 | freebz/Introducing-Python | /ch07/ex7-1.py | 8,117 | 3.703125 | 4 | # 7.1 텍스트 문자열
# 7.1.1 유니코드
# 파이썬 3 유니코드 문자열
def unicode_test(value):
import unicodedata
name = unicodedata.name(value)
value2 = unicodedata.lookup(name)
print('value="%s", name="%s", value2="%s"' % (value, name, value2))
unicode_test('A')
# value="A", name="LATIN CAPITAL LETTER A", value2="A"
uni... |
415e75705bfd3ec95b0455f0b5e27e9a7ae11bcd | iri02000/rau-webappprogramming1 | /seminar7/nested_lists_g611.py | 842 | 4.125 | 4 | def sorting_function(x):
return x[1]
# get number of students
n = int(input("Number of students: "))
# get grades
grades = []
for i in range(n):
student_name = input()
student_grade = float(input())
grades.append([student_name, student_grade])
# sort [student, grade] by grade
# sorted_grades = sorte... |
dc7f933f86fd19da26b035f41a46231cbe1c5861 | laion-j/exercicios-PCLC | /python-section/ex4.py | 336 | 3.828125 | 4 | def alfabeto(frase):
arr_palavras = frase.upper().split(' ')
arr_alfabeto = []
for palavra in arr_palavras:
cont = 0
while cont < len(palavra):
letra = palavra[cont]
if letra not in arr_alfabeto:
arr_alfabeto.append(letra)
cont += 1
pri... |
c9d8491a92eafd816ed8c5a41fdf6f29f94367fc | danielphilipjohnson/Computer-Science | /intro-cs/Introduction-to-Programming/fundamentals-of-computing/Principles-of-computing/Part-1/2.week/col.py | 3,150 | 3.609375 | 4 | import math
row = 2
col = 3
nested_list = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]
# print(nested_list[row][col])
# die_ev = (1+2+3+4) / float(4) #2.5
# print(die_ev * die_ev)
# one_pos = 0.1 ** 5 # 0.00001
# print(one_pos * 12)
# def q4():
# '''
# Permutations
# Consider a trial in w... |
ed02096484a4d136bce47e975e03be5a7b4701b5 | orangewangjie/Algorithm-Dryad | /05.LinkedList/25.逆向k个一组翻转链表.py | 1,521 | 3.734375 | 4 | """
*
* 给定一个链表,将链表从尾部开始,k个一组进行反转。 如果最左边的那个片段不足k个,那么不去翻转。
*
* A = [1, 2, 3, 4, 5], k = 3
*
* 输出:[1, 2, 5, 4, 3]
*
"""
class Solution(object):
def reverse(self, head):
dummy = ListNode()
p = head
while p:
back = p.next
p.next = dummy.next
... |
6063c6c63af49e685e3034143198e8812af9c956 | brony28/My-HaRa-Solutions | /PYTHON/Itertools/itertools_permutations.py | 1,171 | 3.84375 | 4 | from itertools import permutations
word,n = input().split()
# print(*list(sorted(permutations(word,int(n)))))
for i in list(sorted(permutations(word,int(n)))):
print("".join(i))
#itertools.permutations(iterable[, r])
# This tool returns successive length permutations of elements in an iterable.
# If is ... |
8f848b8c7c6148d31a0abc5e774d01aaaf3d46af | diego-go/taller_python_PROTECO | /1er semana/switchDiccionario.py | 447 | 3.859375 | 4 | diccionario={1:"Opcion 1", 2:"Opcion 2", 3:"Opcion 3"}
lista=list(diccionario.keys())
lista.sort()
print(lista)
while True:
for llave in lista:
#print("\t%s. %s"%(llave,diccionario[llave]))
print("\t%s. %s"%(llave,diccionario[llave]))
seleccion=int(input("Selecciona una opcion: "))
if seleccion in lista:
pri... |
7747ce33bb523c74cafbdf9e26e1e3c374f4dd96 | tennyson-mccalla/PPaItCS | /7.17.1.py | 836 | 3.640625 | 4 | from graphics import *
def createWindow():
win = GraphWin("Moving", 900, 300)
win.setCoords(-15,-5,15,5)
return win
def drawCircle(win):
p = win.getMouse()
r = 1
#p = Point(0, 0)
c = Circle(p,r)
c.setOutline("red")
c.setFill("red")
c.draw(win)
return c
def moveRightLeft(x,... |
1333deacbe18d8d5e1f66fdf1617d76bf2e8b8e7 | hongpan0507/Programming | /Python/pycharm/tutorial/tutorial.py | 506 | 3.625 | 4 | #Notes:
#
#
import time;
num1 = 0.1
num2 = 100
str1 = "hello"
list = [785, 'name', 70.2]
print (list)
print(list[0])
print(list[0:]*2)
if num2 == 100:
if num1==1:
print (num2)
else:
print(str1)
else:
print("Num2 is one hundred")
for num2 in range (100, 105):
print(num2)
++num2
w... |
ca3bcedaa7d10d1a3ecbe0c2ce54d6283eebf73e | Erica1217/algorithm | /11653 소인수분해/main.py | 105 | 3.546875 | 4 | n = int(input())
i=2
while(n>1):
if n%i==0:
n = n//i
print(i)
else:
i+=1 |
75b69b115367a83eb3d09dd1fed544d6296df9e1 | globocom/dojo | /2022_06_22/dojo.py | 1,952 | 3.890625 | 4 | def calculate_steps(array):
steps = 0
index = 0
while index < len(array) and index >= 0:
value = array[index]
array[index] += 1
index += value
steps += 1
return steps
def calculate_steps_part2(array):
steps = 0
index = 0
while in... |
d881f9b2580a0cae8babfb234a641fe4a9b17c77 | puziop93/Python-programming-exercises | /ListEnds.py | 522 | 4.1875 | 4 | """
12)List Ends
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
Solution
"""
def num():
return input("Enter numbers: ")
lista=[]
numbers = num().split()
f... |
cb2bdef8c4ecc6f776df763bfb5b327a43425095 | Ruchika1706/PythonCode | /AreaCalculation.py | 638 | 4.28125 | 4 | import math
#Area of Rectangle
length = 3
breadth = 4
area_rectangle = length*breadth
print("Area of Rectangle is ",area_rectangle)
side = 5
area_square = side *side
print("Area of Square is ",area_square)
radius = 5
area_circle = math.pi*math.pow(radius,2)
perimeter = 2 * math.pi *radius
print("Area of Circle", area_c... |
c12c9ff5f40f69cf7ee43637d53c253c12de3a6e | dishant888/PythonGUI | /BookingApp/booking.py | 1,363 | 3.546875 | 4 | from tkinter import *
def submit():
Label(col,text=name.get(),bg='white').grid(columnspan=2)
Label(col,text=age.get(),bg='white').grid(columnspan=2)
Label(col,text=gender.get(),bg='white').grid(columnspan=2)
Label(col,text=payment.get(),bg='white').grid(columnspan=2)
root = Tk()
root.geometry('250x30... |
a8d6d84c76711a258c81896b027ce4d9a5ff7e06 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/66c14e3264ac40d1bc37702e25c169c8.py | 680 | 3.953125 | 4 | def detect_anagrams(s, words):
s_letters = string_to_charcounts(s)
matches = []
for word in words:
if word.lower() == s.lower():
continue
w_letters = string_to_charcounts(word)
if (len(s_letters) == len(w_letters) and
all(w_letters.setdefault(c, 0) == count
... |
5d1517a6a92f7985eb64e2b8832af81f549154af | farzel/PythonDersleri | /Lesson4/Lists.py | 562 | 3.75 | 4 | # Tanimlama Sekli
# Bir dizinin maximum index degeri eleman sayisinin bir eksigi degerindedir.
sehirler= ['ankara','edirne','istanbul','kars','kayseri','istanbul','adana']
# eleman sira no: 1,2,3
# eleman index no: 0,1,2
print(sehirler[0])
index = len(sehirler)-1 #0'dan basladigi icin
prin... |
ca850ccb5e6d1e0be31ae963ab67fb1079ec3dea | EDalSanto/MIT-6.00.2x | /FinalExam/SimFoxRabbitPop.py | 3,606 | 4.21875 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
# Global Variables
MAXRABBITPOP = 1000
CURRENTRABBITPOP = 500
CURRENTFOXPOP = 30
def rabbitGrowth():
"""
rabbitGrowth is called once at the beginning of each time step.
It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP... |
46a3ceba5d69d9c3a7883eac04b69456b8bbe19a | BenMarriott/1404 | /prac_01/shop_calculator.py | 512 | 4.15625 | 4 |
number_of_items = int(input("Please enter number of items: "))
if number_of_items < 0:
input("Invalid number of items: ", )
list_of_item_costs = []
print(number_of_items)
for i in range(number_of_items):
int(number_of_items)-1
cost_of_each_item = int(input("Please enter cost of item: "))
list_of_item_c... |
d27a3236f94c7b0cc5d7d3cde3aa8c71868d7517 | Daniiarz/neobis-1-file-projects | /python/Functions/super_prime.py | 340 | 3.75 | 4 | aa = input()
def is_prime(num):
if num <= 1:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def is_super_prime(a):
for k in a:
if is_prime(int(k)):
pass
else:
return "NO"
return "YES"
print(i... |
6c44363313cc6b08317bdf71c2dcfb7a07731378 | Khristofor11/algorithms | /task3.2.py | 172 | 3.609375 | 4 | a = [8, 3, 15, 6, 4, 2]
b = []
for i, item in enumerate(a):
if a[i] % 2 == 0:
b.append(i)
print(a)
print('Индексы четных элементов: ', b)
|
c39171c375a566eff512cb9722adc01a813a397e | buxizhizhoum/tool_scripts | /app/bin/traceback.py | 815 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
method used to trace exception, it is useful when there is an Exception, but
the detail information such as line number is not available.
"""
import traceback
try:
1/0
except ZeroDivisionError as e:
print e
# print "traceback", traceback.print_exc()
tmp = t... |
bf1650c51b8e7a26cf039970ebc2cef71fb4a093 | Serggi0/python-project-lvl1 | /brain_games/games/progression.py | 819 | 3.515625 | 4 | from random import randint, choice
DESCRIPTION = 'What number is missing in the progression?'
lenght_of_progression = 10
def create_progression(start, step, lenght):
finish = start + lenght * step
progressions = [i for i in range(start, finish, step)]
return progressions
def give_data_for_round():
... |
98ca86146b793f92a02b69aed6420b19c15edbb6 | JKGilchrist/4107-VSE | /models/wildcard_handler.py | 514 | 3.96875 | 4 |
def get_bigrams(string):
'''
Returns a list of bigrams from the given string
'''
lst = []
if len(string) == 1:
return lst
i = 0
while i < len(string) - 1:
if i == 0 and string[i] != "*":
lst.append("$" + string[0])
if string[i] != "*" and string[i+1] !... |
4d1f006ac5c107ca9397fbf3c656ea1fd2437074 | DCWhiteSnake/Data-Structures-and-Algo-Practice | /Chapter 1/Reinforcement/R-1.11.py | 847 | 4.28125 | 4 | # Imagine this :
# x = []
# for k in range(1,n+1):
# x.append(k)
# Being shortened to this;
# List comprehension syntax typically go like this
# x = [ k for k in range(1, n+1) ]
# which assigns to x the list 1,2,3,..., n
# a more complex version of the list comprehension syntax is shown below
# x = [k for k in ran... |
f47aa0329c0552cb498f387509b18e4ae8ba3ac9 | KarKLi/PythonLearning | /source/切片/切片/切片.py | 677 | 4.03125 | 4 | # 演示切片的威力
# 切片可用于list和tuple
L=['Michael','Sarah','Tracy','Bob','Jack']
# 取前三个元素
# 原始方法
L1=[L[0],L[1],L[2]]
print(L1)
# 切片方法(薯片超棒的QWQ)
print(L[0:3])
print(L[:3])
# 语法:x1:x2,从索引为x1,切到索引为x2(如果x1=0还可以省略x1)
# 还支持倒数切片
print(L[-2:])
print(L[-2:-1])
#还可以有这种语法:L[x1:x2:x3],意为从x1切到x2,每x3个切一个
print(L[:10:2])
print(L[::5]) #0到0切片意为... |
1a3c80e67290584419b26bd4f6cf3c42624b6127 | wzz2019/mystudynote | /pythoncode/task_class/person.py | 492 | 3.734375 | 4 | class Person:
name:str = "default"
gender:str = "default"
age:int=20
money:float=1000
def __init__(self,name,gender,age,money):
self.name = name
self.name = gender
self.name = age
self.name = money
def set_name(self,name):
self.name=name
def eat(self... |
1aa63691074255e3000926850eafb12953e97065 | Raghav-Bajaj/HacktoberFest-2 | /Largest_Palindrome_Substring.py | 461 | 4.1875 | 4 | # PYTHON PROGRAM TO PRINT LARGEST PALINDROMIC SUBSTRING
def palinString(ex):
string_size = len(ex)
for str_length in range(string_size, 0, -1):
i = 0
for get_str_size in range(str_length, string_size + 1):
made_str = ex[i:str_length + i:1]
rev_str = made_str[::-1... |
61bb888d24058a1079f2898c2cb5e02a136195d3 | jorgeOmurillo/Python | /recursion/fractal_tree.py | 918 | 3.9375 | 4 | from random import randint
import turtle
def tree(branchLen, t, width):
if branchLen > 5:
t.forward(branchLen)
t.right(randint(15, 45))
#t.color(randint(0,255), randint(0,255), randint(0,255))
t.width(width-3)
if branchLen > 25:
t.color("brown")
if bra... |
8e266c96ec9b8e5b721b81068e2f4b79778d46e0 | GuiRodriguero/pythonFIAP | /1 Semestre/Aula10/Desafio2.py | 660 | 4.09375 | 4 | horaExtra = float(input("Digite o número de horas extras do funcionário: "))
horaFalta = float(input("Digite o número de horas que o funcionário faltou: "))
h = horaExtra - ((2/3)*(horaExtra - horaFalta))
if horaExtra >= 0 and horaFalta >= 0:
if h >= 2400:
print("O funcioário receberá R$1500,00 de bonific... |
c34f2c133023f28897df65bfbf2e5b5b5db92ac1 | jackrobson/kaggle | /001-titanic-passenger-surival-prediction/old-versions/8.py | 837 | 3.671875 | 4 | # Version 8
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
train_data = pd.read_csv('../input/titanic/train.csv')
test_data = pd.read_csv('../input/titanic/test.csv')
def predict(row):
# males perish
if row["Sex"] == "male":
return 0
# f... |
ebfa457b36a0f5dee875bd41701fa0ca967d3e83 | BlackHat-Ashura/Data-Structures-And-Algorithms | /Linked List/Linked_Lists_Interview.py | 5,046 | 3.5 | 4 | from Singly_Linked_List import SinglyLL, Node
def remDup1(LL):
"""
T - O(N)
S - O(N)
"""
if LL.head is None:
print("[!] LL doesnt exist")
else:
tempNode = LL.head
visited = [tempNode.value]
while tempNode.next:
if tempNode.next.value in... |
c020a704f4c243a42d2e2a16c3b79a951ca63d1e | RachelEW/module2 | /ch12_for_loop/ch12_for_loops_rachel.py | 6,940 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 09:31:07 2018
@author: winkl
"""
#######################
"""For Loops"""
#######################
#---------------------------------#
"""Task One: writing a for loop"""
#---------------------------------#
my_shopping_cart = ["cake", "plates", "plastic forks", "juice"... |
47061ca5b3bc2cb2537a0076f78b81c87d68748d | fenglihanxiao/Python | /Module01/DataStructure/List.py | 247 | 3.828125 | 4 | list1 = [1, 2, 3, "itcast", "test", True, False, None, "test"]
# print(list1)
# print(list1[4])
# list1[4] = "Black horse"
list1.append("xyz")
list2 = list1.copy()
idx = list1.index("test")
idx = list1.pop(3)
for data in list1:
print(data)
|
6167e0632b3137fd4c747035256172e1bc7003e4 | DhruvMakwana/Matplotlib | /Matplotlib.py | 6,535 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#importing matplolib.pyplot
import matplotlib.pyplot as plt
# In[2]:
plt.plot([1,2,3,4])
plt.xlabel("some values")
plt.ylabel("some numbers")
plt.title("MyPlot")
plt.show()
# *You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you prov... |
89cc66faf484fa59e4c168675736716e513179f4 | Sandy4321/cli_stats | /scripts/min | 459 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Compute the minimum of a number stream piped from stdin
Author: Gertjan van den Burg
License: See LICENSE file
Copyright (c) 2020, G.J.J. van den Burg
"""
import sys
def main():
minimum = None
for line in sys.stdin:
if not line.strip():
... |
be45a14fc0707045266b7702dbf1853bddb7f114 | orlando2019/curso-python-udemy | /Introducion Programacion/agenda/agenda.py | 6,115 | 3.578125 | 4 | import os
import sys
CARPETA = "mis_contactos/" # Carpeta de contactos
EXTENSION = ".txt" # Extension de contactos
# Clase Contacto
class Contacto:
def __init__(self, nombre, apellido, telefono, categoria):
self.nombre = nombre
self.apellido = apellido
self.telefono = telefono
s... |
cc372c57217d9b8e79ea2b83504fd950ea387059 | YufeiZhang/Some-Important-Notes | /OpenCVSample/lab-1/python_practies.py | 294 | 3.59375 | 4 | import random
list = []
while len(list)<50:
x = random.randrange(0,100)
list.append(x)
list2 = []
list3 = []
list4 = []
for i in list:
if i<50:
list2.append(i)
elif (i>50 and i<75):
list3.append(i)
else:
list4.append(i)
print list2
print list3
print list4 |
d7cf1ad30a115e10fb32ae122e3f8e4f89828e5d | joaopdalbino/predicting_sao_paulo_state_gdp | /Python/1_colector.py | 2,878 | 3.59375 | 4 | import urllib
import os
import time
# it defines coordinates latitudes and longitudes from state of sao paulo
MinLong = -52.611579
MinLat = -24.9982777
MaxLong = -44.3304263
MaxLat = -20.0371434
path = "../data/satellites/TIF"
os.chdir(path)
# Creates a path to sabe images
def path_creator(name_path):
path = os.get... |
34b2a41cef0618a80f2f08d32e656ca751a8ddb0 | shifteight/python | /fop2/account.py | 331 | 3.90625 | 4 | class SavingsAccount(object):
"""This class represents a savings account
with the owner's name, PIN, and balance."""
def __init__(self, name, pin, balance=0.0):
self._name = name
self._pin = pin
self._balance = balance
def __lt__(self, other):
return self._name < other.... |
d6475eefa022b2ada8373fa5e1f46eda1e59d2ce | kujin521/pythonObject | /第五章/列表/元素列表提取.py | 556 | 4.0625 | 4 | #########请按照注释要求完成相应的功能############
tempStr = "80,30,50,60,70,80,90,95,100,85"
lista = list(eval(tempStr)) #将输入的多个数据转换为列表 lista
#####完成以下功能#####
#用一个语句输出列表的第一个元素和最后一个元素,元素之间用默认的空格分隔
print(lista[0],lista[-1])
#用一个语句输出第3~6个元素(4个)组成的子列表,默认最最左边的为第一个元素
print(lista[2:6])
#用一个语句输出列表中索引号为奇数的元素列表
print(lista[1::2])
|
1df3f271bfd99afa100187d3b0342a6255fa6868 | CmKVbzN9/tbb | /module_9.py | 428 | 3.984375 | 4 | """This is the ninth exercise"""
#!/usr/bin/env python3
def main():
"""This module calculates how much paint you need fo the ceiling of a room"""
length = int(input("Length? "))
width = int(input("Width? "))
area = length * width
paint = area / 350
print("You will need to purchase {} gallons o... |
8f0004c1b8771575e6b38201073d72507f8e7e4d | dhanabal-s/Leet-Code-30-Days-Challenge | /May2020/Week1/Day4/Solution.py | 589 | 3.796875 | 4 | # convert the number into binary
# val = 0
# if binary[i] == 0
# add 2 pow i to val
# return val
class Solution:
def findComplement(self, num: int) -> int:
binary = []
if(num == 0):
return 1
# also use bin() build in function for find binary value
while(num... |
753096b6512a18c5926fdb52b2d65a619abd9cfb | DinithaSanthupa/Tic-Tac-Toe-Game---Python | /main.py | 3,894 | 3.859375 | 4 | # --------Global Varibles -----------#
#Game Board
board = ["-","-","-",
"-","-","-",
"-","-","-"]
#If game still running
game_still_running=True
#Who won or tie?
winner=None
#varible for check the user input valid or not valid
valid_input=True
#count the number of rounds
turn =1
#Who's turn is it... |
d7ad9c2229336bad231ce2e50e6b212215b7be31 | Web-penguin/Snake_q_learning | /snake_logic/snake_game.py | 1,919 | 3.546875 | 4 | import pygame
import player
import food
import random
width = 400
height = 400
white_color = (255, 255, 255)
black_color = (0, 0, 0)
class Game_Window(object):
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
food_x, food_y = random.randint(1,18), random.randint(1,18)
self.screen = pygame... |
fb6c83ac81150851653e9d7ef5859e4cf8eaf6dd | SoniaB78/supportSG | /class/heritage.py | 2,418 | 3.59375 | 4 | #-------------------------------------------------------------------------------
# Name: CHeritages
# Purpose:
#
# Author: Sonia
#
# Created: 17/01/2020
# Copyright: (c) Administrateur 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
i... |
6ca2297fac258bcb00129dbcc69583952c24ce01 | calebpeffer/AutomatedStudyGuide | /docreader.py | 452 | 3.640625 | 4 | import docx2txt
import re
#Find a way to convert docx and pdf into txt files
#Easier for reading and parsing.
import string
#open File
with open("french.txt") as fh:
count = 0
for line in fh:
if line != '':
print(str(count)+ " " + line)
count += 1
#Split Paragraph on bas... |
1f3369f05150d10e23b58eee8b9b21562cf56d9f | Tiuku/olio-ohjelmointi | /maxvalue.py | 748 | 4.375 | 4 | # File name: maxvalue.py
# Author: Tiia Iire
# Description: Asks for user to set max value, counts the number of terms and sum of terms
maxvalue = int(input("Set your maximum value: "))
x1 = 2
x2 = 4
def formula(x, y, max):
numterms = 2
sumterms = 0
while True:
z = x + y
if z > max:
... |
2ff894c921025bd762716096fc1b278ec3bdfba6 | meshall2019/Python | /CalculaterTikinter.py | 1,587 | 3.75 | 4 | from tkinter import *
meshal=Tk()
meshal.geometry("200x200")
meshal.title('nothing')
def sum():
num=int(input('Enter first number: '))
num2=int(input('Enter second number: '))
print('The sum is :',num2+num)
def sub():
num = float(input('Enter first number: '))
num2 = float(input('Enter second... |
48c94949251a63137d53807fcf9e05d40c9aa0b9 | gabrieleliasdev/python-cev | /ex079.py | 983 | 4.15625 | 4 | """ 079
Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista.
Caso o número já exista lá dentro, ele não será adicionado.
No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
"""
lst = []
print("Cadastro de valores númericos")
while Tru... |
2c0e70f7906144c4609967b3aaa59f62011927c2 | Margarita-Sergienko/codewars-python | /7 kyu/Bug Squish.py | 551 | 3.765625 | 4 | # 7 kyu
# Bug Squish!
# https://www.codewars.com/kata/5a21f943c5e284d4340000cb
# Take debugging to a whole new level:
# Given a string, remove every single bug.
# This means you must remove all instances of the word 'bug' from within a given string, unless the word is plural ('bugs').
# For example, given 'obugobugobuo... |
812198bdc5e9bdb1f745f2a0196ee9b8d4f7029d | rlaqhdwns/django1 | /django1/src/files/files/2019/02/09/a1.py | 1,442 | 3.5 | 4 | '''
def defaultfun(a,b,c,d,e,f=20,g=10):
pass
def func(a=5,b=10,*args, **kwarges):
pass
def print_info(**kwarges):#딕셔너리 타입
print(kwarges)
def sum(*args):#튜플 타입
print (args)
isum = 0
for i in args:
isum += i
return isum
print(sum())
print(sum(10,20,30,40,55... |
d6bd849346a21b6cb22c035dd7171e14c8a41a0e | MrWJB/rtxs | /rtxs/day/day_04.py | 239 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from io import StringIO
f = StringIO()
f.write('hello world!')
print(f.getvalue())
import json
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
jsr = json.loads(json_str)
print(jsr)
|
7ee1ec9bb651c95eeba2dcc61b0278fe1ff4c2dd | albertoiur/Algoritmos | /max_pairwise_mult.py | 354 | 3.890625 | 4 | #Uses python3
'''
Slow algorithm.
MaximumPairwiseProductProblem: Find the maximum product of two distinct
numbers in a sequence of non-negative integers.
O(n^2)
'''
n = int(input())
a = [int(x) for x in input().split()]
product=0
for i in range(n):
for j in range(i+1 ,n):
product = max(pro... |
6cd13d5db32a0c9f764c58ede9e0dc1c486dc6c0 | poifra/adventOfCode | /2017/day1.py | 819 | 3.65625 | 4 |
def revertCaptcha(text, mode = 1):
#mode is for part 1 or 2
size = len(text)
s = 0
for i,n in enumerate(text):
if mode == 1 and text[i] == text[(i+1)%size]:
s += int(n)
if mode == 2 and text[i] == text[(int(i+size/2)) % size]:
s += int(n)
return s
def problem():
# problem description : http://advento... |
925cf368550810cae9f977d517a78839c460b837 | harverywxu/algorithm_python | /01_string/04单调栈-邻近小值/556. NextGreaterElementIII.py | 2,140 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer
which has exactly the same digits existing in the integer n and is greater in value than n.
If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12
Output... |
0018e7fff973284cfa5552eda6babce327b5c676 | harshadsbs/SWHLab | /scripts/update_version.py | 1,081 | 3.671875 | 4 | import os
import sys
def updateVersion(fname):
"""
given a filename to a file containing a __counter__ variable,
open it, read the count, add one, rewrite the file.
This:
__counter__=123
Becomes:
__counter__=124
"""
fname=os.path.abspath(fname)
if not os.path.exists(fn... |
cdd627641997bd7c8983be064b2be84d27f52a4e | league-python-student/level0-module0-codybsauer | /_01_drawing/_a_shapes_and_colors.py | 2,186 | 4.4375 | 4 | import turtle
if __name__ == '__main__':
window = turtle.Screen()
window.bgcolor('white')
# This code makes a new Turtle. Pick a new name for the turtle
cool_turtle = turtle.Turtle()
# Make your turtle's shape 'turtle', .shape('turtle')
cool_turtle.shape('turtle')
# Set your turt... |
58350ca6bb676b4aad71c8ad3c9941c890f6eaf4 | stasvorosh/pythonintask | /INBa/2015/Serdechnaya_A_M/task_2_25.py | 548 | 3.625 | 4 | #Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Гиппократ.
#Не забудьте о том, что автор должен быть упомянут на отдельной строке.
print("Душа человека развивается до самой смерти.\n\t\t\t\tГиппократ")
input("Нажмите ENTER для продолжения") |
816b05ab4b76a897302138d61de048c86f560f2b | UniBreakfast/ConceptualPacerSkeleton | /ConceptualPacerSkeleton/SANDBOX.py | 1,795 | 3.5625 | 4 | #myVariable = 5
from consoleui import *
#from keychoice import *
def printhere(*args):
print(*args, end='')
main_menu = Board(height=12)
item1 = MenuItem('Go to screen 1', print, (), 1)
item2 = MenuItem('Go to screen 2', print, (), 2)
item3 = MenuItem('Go to screen 3', print, (), 3)
item4 = MenuItem('Show somet... |
67f0259c7d0190920996bdb8eafba0b22ab400db | abdullatheef/Python-exercises | /chapter5/peep.py | 282 | 3.875 | 4 | # Program to implement a function peep, that takes an iterator as argument and returns the first element and an equivalant iterator.
def peep(it):
p=it.next()
l=[]
l.append(p)
l.extend(list(it))
it1=iter(l)
return p,it1
it = iter(range(5))
x,it1=peep(it)
print x,list(it1)
|
6a386228722551da3d14d998a033bbbd46bc5209 | analyzehim/poker | /cards.py | 2,870 | 3.5625 | 4 | import random
card_values=['2', #0
'3', #1
'4', #2
'5', #3
'6', #4
'7', #5
'8', #6
'9', #7
'10',#8
'J', #9
'Q', #10
'K', #11
'A', #12
... |
1b08a9d4d16b3939119436020a0c653441326ea1 | hakimguenther/snake_ai | /environment.py | 10,068 | 3.625 | 4 | from typing import List
from snake import Snake
from food import Food
class Environment:
def __init__(self,snake, food):
self.snake = snake
self.food = food
self.walls = []
self.getStartState()
def getCurrentState(self):
field = self.getEmptyField()
... |
1e9c8942eaadcf755d6179f3faa28ec1698c8cd9 | seungk-new/jumptopython | /JumpToPython/list comprehension(리스트 내포)문제.py | 267 | 3.984375 | 4 | # numbers = [1, 2, 3, 4, 5]
# result = []
# for n in numbers:
# if n % 2 == 1:
# result.append(n*2)
#위 코드를 리스트 내포를 사용하여 표현해 보자.
numbers = [1, 2, 3, 4, 5]
result = [num for num in numbers if num % 2 == 1]
print(result) |
2649620075eec6299c12b937db00510acc684b4d | ravichalla/wallbreaker | /week4/permutations.py | 712 | 3.953125 | 4 | def permute( nums):
def backtrack(start, end):
if start == end:
#print("start end equal",nums)
ans.append(nums[:])
for i in range(start, end):
nums[start], nums[i] = nums[i], nums[start]
#print("before backtrack",nums)
backtrack(start + 1, ... |
492bd33c84d352430b5ff3fc679d0bf0206b3f23 | bajram-a/Basic-Programing-Examples | /For-While Loops/Exercise3.2.py | 423 | 4.03125 | 4 | """Write a program that takes DNA sequences and interprets them as RNA
sequences
*DNA sequence is made up of A, C, G, T
*RNA sequence is made up of A, C, G , U
G -> C
C -> g
T -> A
A -> U"""
a = input()
output = ''
for i in range(0, len(a)):
nuk = a[i]
if nuk == 'A':
b += 'U'
elif nuk == 'T':
... |
fec104c44266fe37e869648896571708234973e3 | notesonartificialintelligence/07-01-20 | /chapter_10/1011_seperate_file.py | 242 | 3.515625 | 4 | #Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 10
import json
filename = 'favorite_number.txt'
with open(filename) as f:
favorite_number = json.load(f)
print(f"I know your favorite number, it's: {favorite_number}") |
376453fd18ea493724a4e92c8a41afb6e558d865 | thomzi12/helper_functions | /regression_helper.py | 2,762 | 3.640625 | 4 | import pandas as pd
import seaborn as sns
import statsmodels.api as sm
import numpy as np
'''
regression_helper.py
A file with regression functions I often use for linear/logistic regression
'''
def logistic_regression(df, y_col, x_col, dummy_cols = None):
'''
INPUT: Dataframe, string of column of response v... |
be35c159fc1fcad80fcf63b8611c3344d5ed64a9 | funny1dog/CTCI_python | /chapter_10/p10_4.py | 1,121 | 3.765625 | 4 | class Listy:
def __init__(self, arr):
self.arr = arr
def elemAt(self, index: int):
return self.arr[index] if index < len(self.arr) else -1
def search_unsized_list(arr: Listy, target: int) -> int:
# Lenght is not known
ind = 0
low = 0
while arr.elemAt(ind) != -1 and arr.elemAt(i... |
4cc5042d0bf272c9b1ae145bb94fa9682860a19b | gabriellaec/desoft-analise-exercicios | /backup/user_217/ch74_2019_06_06_22_59_01_763507.py | 240 | 3.546875 | 4 | def conta_bigramas(palavra):
i=0
dic={}
while i < len(palavra):
bigrama = palavra[i] + palavra[i+1]
if bigrama in dic:
dic[bigrama] +=1
else:
dic[bigrama] = 1
i+=1
return dic |
0a03a146cdb0959afa45e8854e4115acb38b8490 | aa-fahim/practice-python | /Ex35.BirthdayMonths.py | 1,046 | 3.65625 | 4 | ## Birthday Months
# Reads how many birthdays are in each month
import json
from collections import Counter
def read_from_file():
with open('birthdays.json', 'r') as f:
info = json.load(f)
return info
if __name__ == '__main__':
months = []
num_of_months = {}
bi... |
f2ca93aa2d28b2ec0900156fa8fd61b6c88b0dc4 | thehanemperor/LeetCode | /LeetCode/TwoPointer/532. K-diff Pairs in an Array.py | 744 | 3.5 | 4 | # EASY
# 1. store the count of each digit into dict as {3:1,,,,}
# 2. loop the input and check if nums[i] -k in dict ?
# if yes, we found one pair
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
if k < 0:
return 0
check = {}
for i in range(len(nums))... |
310c0e1ad29936eea54a3fa545b566851eb5164f | SanskarZulu/Semaphores-python | /PS_RW_using_Semaphores.py | 8,406 | 3.890625 | 4 | #OS Lab Assignment on Semaphores
#Submitted by: Sanskar Sharma
#PRN: 0120180381
#Roll number: 090
#Date: 15/10/2020
#OS Lab Assignment:
#Part1: Process Synronization Using Semaphores
# Python program to illustrate
# the concept of locks
# in multiprocessing
import multiprocessing
# function to withdraw from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.