blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
59e950ee6a31216fd2a7f84b73f043e659909652 | menard-noe/LeetCode | /Repeated Substring Pattern.py | 419 | 3.671875 | 4 | import math
class Solution:
def repeatedSubstringPattern(self, str):
"""
:type str: str
:rtype: bool
"""
if not str:
return False
ss = (str + str)[1:-1]
return ss.find(str) != -1
if __name__ == "__main__":
# execute only if run as a script... |
cf8a9997126ab7b838ed83fcc708bb9c209b8fc7 | JackSSS/sea-c34-python | /students/JonathanStallings/session02/string.py | 957 | 4.09375 | 4 | from __future__ import print_function
import sys
import traceback
def highest_ordinal():
"""Which letter has the highest ordinal value?"""
string = u"The quick brown fox leaped!"
msg = u"The max was {maxOrd} and its value was {maxValue}." \
.format(maxOrd=max(string), maxValue=ord(max(string)))
... |
ad28c59f909a70f93635a73db6fade1677b6b89b | cenkayberkin/interviewBits4 | /mergeKSorted.py | 1,473 | 3.625 | 4 | import heapq
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
heads = []
resultHead = None
resultTail = None
def __init__(self):
self.heads = []
def mergeKLists(self, lists):
"""
:type lists: List[List... |
8c871a1239df1f714cdd5bfeb5b203b012b376d5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_116/1827.py | 1,507 | 3.546875 | 4 | def isWinner(board, p):
for x in range(4):
matchCount = 0
for y in range(4):
if board[x][y] == p or board[x][y] == 'T':
matchCount += 1
if matchCount == 4:
return True
matchCount = 0
for y in range(4):
if board[y][x] ... |
63bb27e053e3e7f53edc9ccb5c1c738aac28b6ba | nitrozyna/revword.py | /revword.py | 125 | 4 | 4 | print "What is your word?"
word = raw_input()
reversed_word = word[::-1]
print "Your reversed word is %r." % (reversed_word)
|
6ad93f59273246edc2bacc6ed92735738bd1e6b6 | vuhi/python_final_project | /hand.py | 3,735 | 3.515625 | 4 | from card import Face
import matplotlib.pyplot as plt
from matplotlib.image import imread
class Hand:
def __init__(self):
print('Init hand ...')
self.hand_size = 5
self.cards_in_hand = [None] * self.hand_size
self.rank = None
self.score = 0
def get_score(self):
... |
934a1fd6b0e2ff24594e90572196996dc97a8899 | Muthulekshmi-99/guvi | /code/sort no_new constrain.py | 110 | 3.53125 | 4 | a=int(input())
x=list(map(int,input().split()))
if (a==len(x)):
x.sort()
for i in x:
print(i,end=' ')
|
d2d7c82a9e0adb6cefd0751e61fb8f352b6cfb7d | Saurav9jal/Code | /identicalTree.py | 694 | 3.9375 | 4 | ###Write Code to Determine if Two Trees are Identical
class Node(object):
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def checkIdentical(root,root1):
if(root == None and root1 == None):
return True
if((root == None and root1 != None ) or (roo... |
b282e82fc0578d9f3ed98d2ce0cefd0e9721a86b | alqu7095/DS-Unit-3-Sprint-2-SQL-and-Databases | /SC/Northwind.py | 1,418 | 3.5 | 4 | import sqlite3
conn = sqlite3.connect('northwind_small.sqlite3')
curs = conn.cursor()
query = '''SELECT * FROM Product
ORDER BY UnitPrice;'''
query
curs = conn.cursor()
curs.execute(query)
curs.fetchall()
#Top 10 most expensive products:
#Cote de Blaye
#Thüringer Rostbratwurst
# Mishi Kobe Niku
# Sir Rodney's Marm... |
1ff17a44fc699045470757dc91592d52882d9ced | ViataF/Python_mysql_project | /main_menu.py | 1,820 | 3.984375 | 4 | import admin
'''
1. Register user details.
2. Ability to sign-in and sign-out.
3. Upgrade/downgrade user privileges.
4. Show people who have signed-in for the day.
5. Show people who have signed-out for the day.
6. Admin add and remove users in the system.
if true or if false
save to github
'''
# display... |
a5856a42e25e0569d611ff2acfca7de24171917c | Saujas/LearnPy | /prim.py | 307 | 3.953125 | 4 | def prime(n):
c = 0
for i in range(1,n+1):
if(n%i==0):
c+=1
if(c==2):
return 1
else:
return 0
var = int(input("Enter end point of range: "))
for j in range(1,var+1):
if(prime(j)):
print(j,"is prime")
else:
print(j, "is not prime")
|
49789f83f1481ecb7cf89858b6317d39e9e5b9bb | selfcompiler/c---files | /spoj/geoprob.py | 165 | 3.5625 | 4 | t = int(raw_input(""))
while t>0:
string = raw_input("")
b,c,d = string.split(" ")
b = int(b)
c = int(c)
d = int(d)
print 2*c-b-d
t -= 1
|
2a18bcd7a7f46f6080dabff3238aed181f34ae19 | Indian-boult/algoexpert-2 | /Anshul/Binary Search Trees/BST Construction.py | 3,229 | 3.703125 | 4 | # BST Construction
# Not Complete
class BinaryTree:
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def insert(self, value):
currentNode = self
while True: # Neither low nor high ?
if value < currentNode.value:
... |
abd665e47b0c4a7c2f128b8ff21e288576c38b23 | swetakum/Algorithms | /CTCI/Chapter02LinkedLists/ReturnKthToLast.py | 386 | 3.625 | 4 | class node:
def __init__(self, val, next=None):
self.val = val
self.next = None
def printList(head):
while head != None:
print(head.val, " ")
head = head.next
def returnkthtolast(head,k):
slow = fast = head
for i in range(k+1):
fast = fast.next
while fast:... |
06468a48fb1d4bf5df09fe80179dffd3438692a2 | IvanVK/fmi-python | /Game-Project/adventure.py | 3,319 | 3.5625 | 4 | from hero import Hero
from villains import Villains
from fight import Fight
class Adventure():
def __init__(self, map_path):
map_file = open(map_path, 'r')
self.map = map_file.read().splitlines()
map_file.close()
self.map = [list(x) for x in self.map]
self.players = {}
... |
32077e33cd3a3fec3a690c997331b826ee694b78 | vaidehinaik/PracticeSession | /GroupAnagrams.py | 351 | 3.96875 | 4 | def groupAnagrams(arr):
str_dict = dict()
for word in arr:
sorted_str = "".join(sorted(word))
if sorted_str in str_dict:
str_dict[sorted_str].append(word)
else:
str_dict[sorted_str] = [word]
return list(str_dict.values())
print(groupAnagrams(["eat", "tea", "ta... |
efa0f2f1f9b563bd72ed2f55ef5321ea72a1fffc | ashutosh-narkar/LeetCode | /three_sum_smaller.py | 1,125 | 4.09375 | 4 | #!/usr/bin/env python
"""
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n
that satisfy the condition nums[i] + nums[j] + nums[k] < target.
For example, given nums = [-2, 0, 1, 3], and target = 2.
Return 2. Because there are two triplets which sums are l... |
09a05ea80469164a3087aab07de9d649222cdec8 | Skywal/PerceptMulClass | /graph.py | 3,352 | 3.5625 | 4 | # Widget class that displays graph.
from PyQt5 import Qt
import numpy as np
import pyqtgraph as pg
import pyqtgraph.examples
class Graph(Qt.QWidget):
def __init__(self, data_classes=1):
super().__init__()
layout = Qt.QVBoxLayout(self) # create layout
self.view = self.init_plot()
... |
34504ea6b4e4daa4d7e11bf5399afa308e44660d | ashu123git/Guess-the-number | /exercise.py | 648 | 3.9375 | 4 | #it's Ashutosh Choubey
print("\t\t\t\t\t\t\t\tCOME LET'S PLAY A GAME")
print("-->Guess the number taken by me\n-->You have only 10 guesses")
a=53
c=10
while(c>0):
b=int(input("Enter any number = "))
if(b<a):
print("Your number is less than my number")
c=c-1
print("Number of guesses left ... |
d0d7d3642c3619258b06549768755521d29cd4aa | p4arth/GrPa-Solutions | /Week7GrpA3.py | 201 | 3.75 | 4 | def minor_matrix(M, i, j):
m = M
m.remove(m[i])
print(m)
for k in range(len(m)):
for h in range(len(m)):
if h == j:
print(m[k][h])
m[k].remove(m[k][h])
return m
|
5e2210b2e584792bb44335791b76a837e442332e | s2arora/Bio | /Bioinfo_Problem/bioinformatics_1_3.py | 101 | 4.03125 | 4 | num1 = int(input("Enter a integer: "))
num2 = int(input("Enter another: "))
print("sum:",num1+num2)
|
08e0bd31247cff43c7759580e33f2f8634aba78e | StephanieLoomans/learning_python | /favorite_numbers.py | 303 | 3.71875 | 4 | favorite_numbers = {
'dan':['9', '44', '55'],
'ahmed':['6', '12', '55'],
'anna':['15', '4', '8'],
'rik':['18', '77', '11'],
'irina':['21','24', '88'],
}
for name, numbers in favorite_numbers.items():
print(f"\n{name.title()}'s favorite numbers are:")
for number in numbers:
print(f"\t{number}") |
4484109487bd1ea511373d75e09a3f513ce1ac96 | dhsim86/hello_py | /lambda/map.py | 184 | 4.03125 | 4 | #!/usr/bin/env python
# Basic
print('--------------------')
print('Basic\n')
f = lambda x: x > 0
g = lambda x: x ** 2
print(list(map(f, range(-5, 5))))
print(list(map(g, range(5)))) |
654ade1bb8b39a2130d17dec5551aedeb4e8ad37 | aguilmes/Portfolio | /SopaDeLetras.py | 12,272 | 3.765625 | 4 | import random
# DEFINICION FUNCIONES
# ********************
def elegirCategoria():
"""Selector de categoria. Podes generar tu categoría siguiendo <Categoria>:<Palabra>,<Palabra>"""
try:
categorias = open("categorias.txt","rt")
categoriaLista = []
for linea in categorias:
ca... |
d83617ff45e5daeb5c3c78331f425369a8efd757 | WanderersTeam/The-adventures-of-a-lone-wanderer | /main_menu.py | 2,106 | 3.796875 | 4 | import functions
global main_menu
main_menu = 1
def mainMenuText():
"""Prints options for start of the game"""
print(""" 1. New Game
2. Load Game
3. Authors
4. Exit""")
global choice
choice = input("What to do? [Choose the number]:")
return(choice)
def newGameLoad():
"""Import ... |
322a3a2581340b0f3e95390333288d3cc9c54d58 | chaun01/python_ML | /data_cleaning/data_cleaning.py | 1,637 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
Type
Null Data
Missing Data
Duplicate
Outliers
# In[19]:
get_ipython().system(' pip install pandas')
# In[2]:
import numpy as np
import pandas as pd
# ### Problem 1
# In[39]:
df = pd.read_csv('property.csv')
df.info() #Check the type of data and whether any data is null
... |
6e49e9253088b8d0c0e649626fd9f71ff101f128 | wushengwei2000/Wu | /python/bst/linkedlist.py | 1,151 | 3.90625 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MergeList:
def merge(self, p1, p2):
root = ListNode(None)
p = root
while p1 or p2:
if not p1:
p.next = p2
break
if not p2:
p.next = p1
break
if p1.val <= p2.val:
p.next = p1
p1 = p1.next
else:... |
a58b82474a3d5085e56f05201b69acca048bb11b | dayanandtekale/Python_Basic_Programs | /if_statements.py | 302 | 4.1875 | 4 | #if str_input%2==0:
# print("number is in multiple of 2")
#elif str_input%7==0:
# print("number is in multiple of 7")
num1 = 5
num2 = 10
#if num1>num2:
# print("num1 is grater")
#else:
# print("num2 is grater")
print("num1 is grater")if num1>num2 else print("num2 is grater")
|
6756dec201998d01a43d3876c619659c1571b496 | wentsun12/AlgorithmCHUNZHAO | /Week_02/Tree.py | 3,078 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
#94: 二叉树,中序,递归
class Solution:
def inorderTraversal(self, root):
res = []
self.helper(root, res)
return res
... |
706e85da67e8565964be796b0768be94d77a38f2 | gup-abhi/rand_dice_num | /Simpledicegame.py | 831 | 4.0625 | 4 | # importing tkinter
import tkinter as tk
from tkinter import ttk
# importing showinfo from tkinter messagebox
from tkinter.messagebox import showinfo
# importing random module
import random
# creating a window
win = tk.Tk()
# giving a title to our window
win.title("Random Number Generator")
# creating a function ran... |
e22e9b650b621bd6e782f72f8e131c961e4abaa6 | dogancanulgu/arin-python-tutorial | /lists2.py | 708 | 3.9375 | 4 | # cities = ['tokyo', 'madrid', 'londra', 'kiev']
# # print(cities.index('madrid'))
# # print('ankara' in cities)
# for city in cities:
# print(f'Gezilen şehir: {city}')
# print('Gezilecek şehir kalmadı')
# str_cities = 'tokyo, madrid, kiev'
# my_list = str_cities.split(', ')
# print(my_list)
# str_email = 'arin... |
b81cf676ab443950bec25538ff0d628014d3e88b | IL23/Python_exercises | /Part2/1.py | 196 | 3.765625 | 4 | # 1. Apgriezt pozitīva skaitļa ciparu secību.
num = input("Enter number: ")
numLength = len(num)
revers = ""
for i in range(1, numLength+1):
revers += num[numLength-i]
print(revers)
|
0e8f2ebc33f6442c152b29e86996fc265d0facab | edu-athensoft/stem1401python_student | /py200622_python2/day01_py200622/ex/function_kevin.py | 929 | 4.28125 | 4 | """
create 2 functions
1. y = 2x
2. y = 2x + 1
(whereas 2x mean 2 * x)
call each function for 3 time with different input x of x (value of x)
then print out the returned value of y
"""
# define function with the keyword 'def'
# define a function
def myfuc1(x):
return x
# 1. y = 2x
# call a function
result = myfuc... |
ee6e33573521232df1e9322bf3e16d3332e15c56 | mistrydarshan99/Leetcode-3 | /trie/211_add_and_search_word_data_structure_design.py | 2,670 | 4.0625 | 4 | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search(... |
f8d19053cc611e0dfdcbdcf1751ceb9f70a25416 | ONOentrepreneur/python-code | /kisuu.py | 109 | 3.578125 | 4 | def gen():
i=1
while i<=30:
yield i
i+=2
it= gen()
for v in it:
print(v,end=",")
|
697d3c6985d24f985669e1fb437afe9d0079c4b4 | hdannyyi/my-first-python | /firstProject.py | 330 | 4.03125 | 4 | FirstName = input('What is your first name?')
LastName = input('What is your last name?')
FavMovie = input('What is your favorite movie?')
#print ("First Name: %s" % FirstName)
#print ("Last Name: %s" % LastName)
#print ("Favorite Movie: %s" % FavMovie)
print ("Hello %s %s. I like %s, too" % (FirstName, LastName, F... |
b38ae79f9684a745a9c6ca2a8ec68432d8f2a823 | hyang012/leetcode-algorithms-questions | /238. Product of Array Except Self/Product_of_Array_Except_Self.py | 843 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Leetcode 238. Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such
that output[i] is equal to the product of all the elements of nums except
nums[i].
Note: Please solve it without division and in O(n).
Follow up:
C... |
e565cf4871a4802b0c2ddc7e60731adb55b23295 | tsmith328/AoC2015 | /Day24/day24.py | 734 | 3.515625 | 4 | import itertools, operator
from functools import reduce
items = []
num_groups = 3
with open("input24.txt") as f:
for line in f:
items.append(int(line.strip()))
def find_qe(things, parts):
for i in range(1, len(items)):
for x in (c for c in itertools.combinations(items, i) if sum(c) == sum(ite... |
0163e281e5d4d2f67c6c81453b5ec7e298174e3d | jichilen/python | /problem/_34_tree_sum.py | 790 | 3.65625 | 4 | from tree_node import MyTree
def tree_sum(root,target):
def search(node,target,re):
if node is None:
return None
val = re[0]+node.val
if val>target:
return None
past = re[1].copy()
past.append(node.val)
if val==target:
return [past... |
ee69cf33525a2fb7633cb1249282821b6187d1df | gongjianc/Learn | /python/quadratic.py | 264 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
#Ҫжb*b - 4ac Ƿ0
def quadratic(a,b,c):
x1 = float((-b + math.sqrt(b * b - 4 * a * c)) / (2 * a))
x2 = float((-b - math.sqrt(b * b - 4 * a * c)) / (2 * a))
return x1,x2
|
73d4b4e4e9b59c36775af69bc0882b260df064ad | lilsweetcaligula/sandbox-codewars | /solutions/python/7.py | 309 | 4.09375 | 4 | def string_parse(s):
if type(s) != str:
return 'Please enter a valid string'
import itertools
result = ''
for char, chars in itertools.groupby(s):
group = ''.join(chars)
result += '{}{}'.format(
group[:2],
'[' + group[2:] + ']' if len(group) > 2 else '')
return result |
8469b36f6a34ae13ead0752fd3c506525f6cb77b | Carl-Chinatomby/Algorithms-and-Data-Structures | /programing_problems/order_agnostic_binary_search.py | 1,519 | 4.125 | 4 | #!/usr/bin/env python3
"""
Given a sorted array of numbers, find out if a given number key is present in the array.
Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order.
You should assume that the array can have duplicates.
Write a function to return the index of the ke... |
4c171d4824b894644e0bf73c27b8f8c998821d7d | Darkspectra/CSE-111-Assignment-1 | /Medium03.py | 191 | 3.71875 | 4 | #Medium_03
num=int(input("Enter number:"))
sum=0
for i in range(1,num):
if(num%i==0):
sum=sum+i
if(sum==num):
print("Perfect Number")
else:
print("Not Perfect") |
0916fe4c35446106bf90cccb6d1ae0bde0009476 | Atylonisus/AutomateHello | /hello.py | 1,175 | 4.25 | 4 | #This Program says hello, and asks for my name.
print('Hello world!')
print('What is your name?') #asks for their name
myName = input() #a new variable, which will store whatever the user types here
print('It is good to meet you, ' + myName) #concatenates a string, with your myName variable, to produce a sing... |
1d2ea1012518151e6549e8b681270fda57f14804 | 1205-Sebas/TALLERCV-GOMEZ-DIAZ | /Ejercicio6.py | 926 | 4.15625 | 4 | """
6. Elaborar un algoritmo que permita realizar el inventario de una tienda, es decir cuántas unidades de
cada tipo de producto existen actualmente en la tienda. Se debe imprimir una lista ordenada de
productos de menor a mayor cantidad.
"""
import operator
a=int(input("Cantidad Aceite:"))
b=int(input("Cantida... |
0e8bd4c5a652a29dc70031c6f0e897f97bb6c8d8 | giuseppeSilvestro/ScientifiComputingWithPython | /RaiseExceptions.py | 1,092 | 4.21875 | 4 | # import math module to use in split_check function
import math
# this function will take the bill and split it between the number of people
def split_check(total, number_of_people):
# check the number of people input by the user. if it is less or equal to 1
# raise a ValueError exception
if number_of_people <= 1:... |
238e2d87773713788d967de748683b48ce0db390 | AnaBiaCosta/curso-python | /exercicios-python/34.py | 283 | 3.75 | 4 | salario = int(input('Seu salário:'))
if salario > 1250:
aumento = (salario * 110)/100
print('Com aumento de 10% seu salário será de R${}'.format(aumento))
else:
aumento = (salario * 115)/100
print('Com aumento de 15% seu salário será de R${}'.format(aumento)) |
e393052b15dfc2cbabee148aa6121350ac5e1496 | ArhiTegio/GB-Python-Basic_2 | /Lesson_6/04.Car.py | 1,933 | 3.859375 | 4 | from enum import Enum
class Color(Enum):
Red = 1
Yellow = 2
Green = 3
class Car:
speed = 0
color = Color.Red
name = ""
is_police = False
def __init__(self, speed, color, name, is_police):
self.speed = speed
self.color = color
self.name = name
self.is_... |
ad516745bf2c0a26c24e5dae3ff3483bc8bbd089 | James-Oswald/IEEE-Professional-Development-Night | /7-5-21/rev.py | 354 | 3.75 | 4 | #https://leetcode.com/problems/reverse-integer
def reverse(x: int) -> int:
fullArr=list(str(x))
digiArr=fullArr[1:]if fullArr[0]=="-"else fullArr
digiArr.reverse()
revVal = int("".join((["-"] + digiArr) if fullArr[0]=="-" else digiArr))
if revVal < -2**31-1 or revVal > 2**31:
return 0
r... |
d3d4d3e539e2f2d73643280624dad3fe2061f4c6 | VirajShah21/euler | /py/9.py | 285 | 3.578125 | 4 | import math
breakout = False
for a in range(1, 1000):
for b in range(1, 1000):
c_2 = ((a)**2) + ((b)**2)
c = math.sqrt(c_2)
if a + b + c == 1000:
print("a = %d\nb = %d\nc = %d" % (a, b, c))
breakout = True
if breakout:
break
if breakout:
break
print(a*b*c)
|
fc41c93123c02481c72861309b47e98df1cab29b | loopfree/Praktikum-Daspro | /Prak 4/segitiga.py | 1,565 | 3.65625 | 4 | # Steven
# 16520203
# 26 Maret 2021
# Program GambarSegitiga
# Input: N : integer
# Output: Jika N > 0 dan ganjil, gambar segitiga sesuai dengan N
# Jika tidak, tampilkan pesan kesalahan:
# KAMUS
# Variabel
# N : int
def GambarSegitiga(N):
# I.S. N > 0 dan N ganjil
# F.S. Gambar segitiga... |
af97d2adfeb27d9a5aa7216eb9bb3784138c67cd | firstlord15/Python | /Уроки/Дашина работа.py | 368 | 3.875 | 4 | # Линейный поиск
names = ["Володя", "Валера", "Вася", "Саша", "Антон", "Яков"]
search_for = "Антон" # что ищем
def liner_search():
for v in enumerate(where):
if v[1] == what
return v[0] # возвращаем индекс
return None # или None если не найдено
print( liner_search() ) |
cff6625e2b6f932e325b7411a4c71127eecc7ea6 | aye-am-rt/python-practice | /Strings/KUniquesIntSubs/GenerateStringKDistinct.py | 1,715 | 3.984375 | 4 | # Generate a string of size N whose each substring of size M has exactly K distinct characters
# Given 3 positive integers N, M and K. the task is to construct a string of length N
# consisting of lowercase letters such that each substring of length M having exactly K
# distinct letters.
# Examples:
# Input: N = 5, M =... |
fef491c7eb090ab6f04b415d9708e7db7294155d | notini/python_recursive_binary_tree | /binaryTree.py | 2,425 | 4.03125 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
#Inserts value to tree.
def insert(self, currNode, value):
#no root yet
if self.root == None:
self.root = Node(value)
else:
if value < curr... |
4501f44dd2423fc9ca0d98bc79988215756fd641 | milica325/unibl_radionica | /sveske/sources/08_OOPI/OOP_I.py | 3,796 | 4.65625 | 5 | # Code for Object-Oriented Programming with Python - Lesson 1
# SBC - 01/12/12
###
# Slide 9 - Bear: Our first Python class
class Bear:
print "The bear class is now defined"
a = Bear
a
# Equates a to the class Bear. Not very useful
a = Bear()
# Creates a new *instance* of the class Bear
###
# Slide 10 - Attribu... |
bb596882dd9fdf844b7996063ba7c672eb7f908a | ipsorus/lesson_2 | /string_challenges.py | 2,148 | 4.125 | 4 | # Вывести последнюю букву в слове
word = 'Архангельск'
def last_letter(word):
print(f'Последнняя буква в слове {word}: {word[-1]}')
#last_letter(word)
# Вывести количество букв "а" в слове
word = 'Архангельск'
def count_letters(word):
letters = []
res = 0
letters = list(word)
for letter in lette... |
1dff787a8cdf5bd4e80df675841a32cc1c8e1908 | timisaurus/workspace-python-Hello_world | /book/is_triangle.py | 636 | 4.34375 | 4 | # This program calculates if a triangle with 3 different lenght would be possible.
x = int(input('Lenght a:'))
y = int(input('Lenght b:'))
z = int(input('Lenght c:'))
def is_triangle(a, b, c):
ab = a + b
ac = a + c
bc = b + c
result = True
if bc < a:
result = False
if ac < b:
... |
10faff94628776074504921d378550b0e089ba2b | zsmountain/lintcode | /python/stack_queue_hash_heap/551_nested_list_weight_sum.py | 1,869 | 4.09375 | 4 | '''
Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Have you met this question in a real interview?
Example
Example 1:
Input: the list [[1,1],2,[1,1]],
Output: 10... |
ce105e7a1ef22746b05019c4b9d610072cd6b384 | hxxtsxxh/codewithmosh-tutorials | /DisplayingCurrentTIme.py | 352 | 3.5 | 4 | # import time module
import time
import datetime
# 24-hour format below
print(time.strftime("%H:%M:%S"))
# 12-hour format below
print(time.strftime("%I:%M:%S"))
# datetime module
e = datetime.datetime.now()
print(e.strftime("%Y-%m-%d %H:%M:%S"))
print(e.strftime("%d/%m/%Y"))
print(e.strftime("%I:%M:%S %p"))
pri... |
8d76e00de54a7d6c997ef7fe88ab0e6f86877957 | stepc0re/TestRepo | /test.py | 1,886 | 3.84375 | 4 | import sys
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
# instead of Name ein __str__ , i say print x nicht x. Name, str wird automatisch benutzt
def __str__(self):
... |
c73533c1987d9eaa6af0f200fb2ddb1651057c5c | kannyg87/python- | /Howmanycoins.py | 279 | 3.953125 | 4 |
print('you have 0 coins')
answer = input('Do you want another coins? ')
answer = answer.lower()
count = 0
while answer == 'yes':
count +=1
print('you have %d coin' % count)
answer = input('Do you want another coins? ')
if answer == 'no':
print ("Bye")
|
88cee63d41f55f998e096642a02abe8da7431db6 | zhenyong97/leecode_learning | /question26删除排序数组的重复项/farmer_solution.py | 426 | 3.609375 | 4 | class Solution:
def removeDuplicates(self, nums):
for index, item in enumerate(nums):
mark = nums.count(item)
if mark == 1:
pass
else:
for i in range(mark-1):
nums.pop(index)
return len(nums)
if __name__ == '... |
ee7fd8d1977b5c972c165c2474bce283a7cb4749 | Darya1501/Python-course | /lesson-8/task-5.py | 344 | 3.796875 | 4 | # Произведение количества положительных и отрицательных чисел
a = int(input())
count_positive = 0
count_negative = 0
while a != 0:
if a < 0:
count_negative += 1
if a > 0:
count_positive += 1
a = int(input())
print(count_negative * count_positive) |
66af88db005b6d4a24cf4595b897ba0edba2a111 | Yuliya-Karuk/get-repo | /lesson04/easy_homework.py | 1,900 | 3.890625 | 4 | # Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
import random
lst_beg = [random.randint(-10, 10) for i in ra... |
8fb17a5d1238afd46a7d87179467415ba82aaebc | brenj/solutions | /hacker-rank/python/data-types/sets.py | 590 | 4.34375 | 4 | # Sets Challenge
"""
You are given two set of integers M and N and you have to print their
symmetric difference in ascending order. The first line of input contains
value of M followed by M integers, then value of N followed by N integers.
Symmetric difference between M and N mean those values which either exist
in M o... |
6cabf25b8c8c2de53e5254d2bfb758d26c3711fb | dogedogethedoge/NIM | /NIM/server.py | 1,599 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""This file contains the socket server used for the Expanding Nim game.
It is a very simple implementation that has methods to wait for a player to
move, update all players after each move, and establish connections.
@author: Munir Contractor <mmc691@nyu.edu>
"""
import socket
cl... |
eabbb9ac482cce3474f42d1997105f80af389e96 | cifpfbmoll/practica-6-python-fperi90 | /P6ej10.py | 1,454 | 4.3125 | 4 | # Escribe un programa que te pida los nombres y notas de alumnos. Si escribes una nota fuera del intervalo de 0 a 10,
# el programa entenderá que no quieres introducir más notas de este alumno. Si no escribes el nombre, el programa
# entenderá que no quieres introducir más alumnos. Nota: La lista en la que se guard... |
5499fa55e3d9c618fb3af71bf07fbf766a44a76a | leinian85/year2019 | /month01/code/day08/exercise07.py | 746 | 3.84375 | 4 | # 4. (扩展)方阵转置.(不用做成函数)
# 提示:详见图片.
list02 = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
list03 = [
[1, 2, 3, 4],
[6, 7, 8, 9],
[11, 12, 13, 14],
[16, 17, 18, 19]
]
def phalanx_permute(list_phalanx):
"""
方阵转置函数
... |
a3c179aec737de30cf872a8adc665d2f0e28a943 | HeywoodKing/mytest | /MyPractice/tryexception.py | 871 | 3.765625 | 4 | # Filname:tryexception.py
re = iter(range(5))
try:
for i in range(100):
print re.next()
except StopIteration:
print 'here is end ', i
print 'hahahaha'
#Ľṹ
try:
print "try"
except exception1:
print 'except exception1'
except exception2:
print 'except exception2'
excep... |
08d9cd21e4446e72ef308ce8890605f7d5aa6482 | hajelav/programs | /affirm_coding_challenge/facilities/facility.py | 1,907 | 3.703125 | 4 | #! /bin/python
import sys
import csv
import json
from pprint import pprint
import traceback
'''
This function compares two dictionaries,
returns True/False
'''
def compareDict(dictOne,dictTwo):
if((not dictOne) or (not dictTwo)):
return False
if(len(dictOne) != len(dictTwo)):
return Fals... |
7be20a8cf40acaee1cc86f66bf27a5cb52acd52e | HalfMoonFatty/Interview-Questions | /019. Remove Nth Node From End of List.py | 863 | 3.84375 | 4 | '''
Problem:
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one ... |
a689400c3523e0a5e4556203dee0273cb858b7bc | Aziz1Diallo/python | /factorial.py | 809 | 3.625 | 4 | '''agsag
agsfga
agfag
'''
def facto(n):
if n==0:
return 1
else: return n * facto(n-1)
def main0():
''' gsousgj
skj dsogsd
adfkja;
'''
print("0! = ",facto(0))
print("4! = ",facto(4))
def sum1(n):
s=0
while n > 0:
s += 1
n -= 1
return s
val =... |
d705e943ee04147d7617ce491d814fb95f21d3d3 | porregu/unit2 | /yearsoftheuser.py | 178 | 3.953125 | 4 | name=input("what's your name ?")
print(" that's a cool name")
years=float(input("how old are you?"))
old=(75-years)
print(old)
later=input("you will turn 75 in this many years ") |
128ab9982f5a29fad4af13a9d6620b7e11b8ae03 | gagankandel0/Insight_projects | /Python Assignment/Ques5.py | 249 | 3.765625 | 4 | def sample(str1):
a='ing'
b='ly'
if len(str1)>=3:
if str1[-3:]!='ing':
result=str1+a
else:
result=str1+b
else:
return str1
return result
print(sample('sw'))
|
7f633113313b2ab2ff55e199bab6b7eee786a7e7 | daniel-reich/ubiquitous-fiesta | /GP8Tywnn2gucEfSMf_6.py | 248 | 3.53125 | 4 |
def error(n):
dict = {1 : "Check the fan",
2 : "Emergency stop",
3 : "Pump Error",
4 : "c",
5 : "Temperature Sensor Error"}
if n >5 or n<1:
return 101
else:
return "{}: e{}".format(dict[n],n)
|
1f0a3d23fbbe700da1ef3e2c8c9f57845c1e5118 | pavanmutyala3448/Bank_Managment_System_Python | /bms.py | 3,597 | 3.828125 | 4 | from random import *
class User:
def __init__(self,name,age,gender,address):
self.name=name
self.age=age
self.gender=gender
self.address=address
def show_User_Details(self):
print('\n')
print('*** Personal Details ***')
print('Name : ',self.name)
p... |
148a60fa3e06a3ece884814b23d5024a3e652cd7 | Shauryayamdagni/IITM_python | /test2.py | 124 | 3.8125 | 4 | arr=[]
brr=[1,2,3]
arr.append(brr)
arr.append(brr)
arr.append(brr)
print(arr)
arr[2][0]=0
arr[2][1]=0
arr[2][2]=0
print(arr) |
18d0042786d0f560deacfee70730d21e863a973f | luodiweiyu/GlyphClientPython | /pointwise/glyphapi/utilities.py | 49,671 | 3.5 | 4 | import numpy as np
import math
"""
Utility classes that mimic the behavior of the Glyph pwu::* utilites.
"""
class GlyphUtility:
tolerance = 1e-7
class Vector2(object):
"""
Utility functions for two dimensional vectors, which are represented
as a list of two real values.
"""
def __init__(se... |
5c51e6c96682225a208ed221f2b23681b1d1add8 | coderplug/adventofcode2018 | /day4/2/script.py | 5,897 | 3.71875 | 4 | from datetime import datetime, timedelta
def input(filename):
with open(filename, "r", encoding="utf-8") as f_in:
lines = f_in.read().splitlines()
return lines
def parse_entries(entries):
parsed_entries = []
for entry in entries:
parts = entry.split(" ")
date_parts... |
8dcc4b89c759898227722bcbd701f19f3dafb88e | GuilhermeRamous/python-exercises | /string_remover.py | 292 | 4 | 4 | """Remove todas as ocorrências de uma determinada substring da string principal"""
def string_remover(string, removed_part):
return string.replace(removed_part, "")
texto = input("Texto: ")
parte_removida = input("Parte que será removida: ")
print(string_remover(texto, parte_removida))
|
99bf204858fa36bbf5acfef9fc3812249c95959c | bielamonika/kurs_python | /09.03/range_zadanie2.py | 217 | 3.578125 | 4 | skladniki = ['ryz','cebula','pieczarki','ser','suszone pomidory','pieprz','sol','olej']
print("Przygotuj nastepujace skladniki: ")
for item in skladniki:
print(item)
print("Podgrzej w garnku.")
print("Zamieszaj.") |
dde2856049f33de450483980fdf26d3e2535e8b6 | nishithamv/Personalized-Voice-Synthesizer | /all_words.py | 1,964 | 3.546875 | 4 | all_w = "the you and it a 's to of that in we is do they er was yeah have but for on this know well so oh got if with " \
"she at there think just can would mm them up now about me very out my mean right which people like really other" \
" something actually take those only into us quite hundred again u... |
2586907485e755f37405fa1f0895c6533fd29828 | Vodrech/WorkApplier | /Settings/save.py | 4,247 | 3.71875 | 4 | import os
"""
The save.py handles the save functionality for the gui to save settings for the TableSpecialSearch.py file
Usage:
> Create Instance of class
> Set the instance object to the current setting name that is going to be changed
> Edit the value
"""
class SaveSettings:
def __ini... |
989a617d646dbb8b97998c67a2aa27b935632904 | drkthakur/learn-python | /python-poc/python-self-poc/DS/recursion/pascal.py | 244 | 3.671875 | 4 | def pascal(n):
line = 1
while(line <= n):
C = 1
i = 1
while(i <= line):
print(C)
C = C * (line - i)/i
i = i + 1
print("\n")
line = line + 1
print(pascal(5))
|
6a860aec19688ee3933dfec3f7780f2f5365adeb | sotrnguy92/udemyPython | /udemy4/pythonDataTypesAndVariables/variablesHomework4.py | 208 | 4.25 | 4 | #This program reads 3 strings and prints the three strings repeated ten times
str1 = input("enter a string: ");
str2 = input("enter a string: ");
str3 = input("enter a string: ");
print((str1+str2+str3)*10) |
5dc661bdc9db20088a59fdf40e4ef0bb4dd32762 | DrEaston/leaderBoard | /old/leaderBoard_working.py | 5,803 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 20:17:17 2020
Curtis Easton
This is a program that takes a .csv file from schoology, and imports it into a Course object. Student info is
stored in a list of Student Objects within a Course, including individual quiz scores.
Within the Course class are some functio... |
735cddc51a5e9c19da4a04f182f59f1895e15ec6 | chaojiechen92/alg | /special_leetcode/array/数组中的第k个最大元素.py | 1,642 | 3.5 | 4 | class Solution:
# O(n^2) 最孬的算法
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
lens = len(nums)
i = 1
while i < lens:
j = i - 1
val = nums[i]
while j >= 0 and nums[j] < v... |
8eb42caeac6918bb2732eab649315b06a74813b4 | SauravShoaeib/College | /CS_127/Python/borough.py | 644 | 4.25 | 4 | #Saurav Hossain
#09/24/18
#Ask the user for the borough, an name for the output file, and then display the fraction of the population that has lived in that borough, over time.
#Taken from lab and modified
import matplotlib.pyplot as plt
import pandas as pd
x = input()
y = input()
#Open the CSV file and store... |
4bc98f96817195ede38c4ae82916b3d1b9e5b372 | raswolf/Python | /module4/store/coupon_calculations.py | 769 | 4.0625 | 4 | """
Program: coupon_calculations.py
Author: Rachael Wolf
Last date modified: 09/21/2020
The purpose of this program is to accept the amount of the purchase,
the cash coupon, and the percent coupon. From these it will
calculate and return the total payment for the order item.
"""
def calculate_order(price, cash_coup... |
c3405aab4e973d1b99a6a72bfd6329f40b2a9102 | ethan21-meet/meetyl1 | /lesson4.py | 1,012 | 3.9375 | 4 | from turtle import Turtle
import turtle
class Ball(Turtle):
def __init__(self,r,color,dx,dy):
Turtle.__init__(self)
self.penup()
self.r = r
self.dx = dx
self.dy = dy
self.color(color)
self.shape("circle")
self.shapesize(r/10)
def move(self,screen_width,screen_height):
current_x = self.xcor()
new_... |
05f9612f39df2dcf521938c0811d7281af710d73 | poojataksande9211/python_data | /python_tutorial/excercise_11_decorators/decorators_intro.py | 368 | 4.15625 | 4 | #intro to decorators
# def square(a):
# return a**2
# s=square(7)
# print(s)
#------------------
def square(a):
return a**2
s=square #here we assing function to variable s....yahape func ko call nahi kar rahe...
print(s(7)) #s kam karega function ki tarah
print(s.__name__) #it will print name of s
print(s) #b... |
10b869fef91a302f336b379f92dd0062c1923cdf | BourgonLaurent/pyParker | /MouseToolsbyScottCaratozzolo/auth.py | 895 | 3.578125 | 4 | import requests
import json
from datetime import datetime, timedelta
def Authentication():
"""Gets an authentication(access) token from Disney and returns it"""
r = requests.get("https://disneyworld.disney.go.com/authentication/get-client-token")
auth = json.loads(r.content)
return auth['access_token... |
4c5dda9485035660017873c4349db25cba6e8bd4 | nosrefeg/Python3 | /mundo3/exercicios/081.py | 617 | 4.09375 | 4 | numeros = []
while True:
numeros.append(int(input('Digite um número: ')))
continua = input('Quer continuar? (S/N) ').strip().upper()
while continua not in 'SN':
print('Apenas S ou N')
continua = input('Quer continuar? (S/N) ').strip().upper()
if continua == 'N':
break
print('¨¨'... |
2424accc6b69a9e090c366d28c5c942396c36330 | manuelalvarezco/Phyton | /funciones_conjuntos.py | 178 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 12:41:48 2020
@author: luismanuelalvarez
"""
def f(x):
return x ** 2 - 3 * x + 1
print(f(3)) |
36938b2c3f3b000452ead843e4553f28550eb772 | SabithaSubair/Luminar_PythonDjangoProjects_May | /samplepgms/add10nums.py | 178 | 3.9375 | 4 | # sum=0
# # for i in range(1,10):
# # sum=sum+i
# # print("result",sum)
#another way
a=int(input("Enter range:"))
sum=0
for i in range(a):
sum=sum+i
print("result",sum) |
a5b447f3062bdd0e3d76ae035190fa2cf65f0c0b | jeancarlo-Topo/Repositorio_General | /Calculadora.py | 5,396 | 3.796875 | 4 | menu = """
Bienvenido ala calculadora,actualmente se encuentra bajo actualizacion por lo que apreciamos su paciencia, muchas gracias
1 - Suma
2 - Resta
3 - Multiplicacion
4 - Division
5 - Division Entera
6 - Potencia
7 - Raiz
8 - Determinacion de raiz cuadrada de un numero
9 - Factoriales
10 - Fibbonacci (Numeros enter... |
2ce44a1b9b49105eac488b9a63c5c1d88883450d | sahasatvik/assignments | /CS2201/tabulation.py | 885 | 4.34375 | 4 | #!/usr/bin/env python3
import numpy as np
'''
Finding the intervals in which a function has roots using tabulation.
'''
def tabulation(f, lo, hi, n):
'''
Yields intervals which contain roots of the function f. A total of n
intervals of equal length within [lo, hi] will be considered.
'''
# Creat... |
46e91f71f436d8a213a0932e69c5bb7cd1ddd733 | ambosing/PlayGround | /Python/language study/function.py | 542 | 3.859375 | 4 | def hello():
print('Hello, world')
def add(a, b):
print(a + b)
def add2(a, b):
return (a + b)
def add_sub(a, b):
return (a + b, a - b)
def add_sub2(a, b):
return ([a + b, a - b])
hello()
add(3, 4)
res = add2(3, 4)
print(res)
x, y = add_sub(10, 5)
print(x, y)
tu = add_sub(10, 5)
print(tu)
lst = a... |
18a349914894ebd98fcb9f13dd40fd35f8902e09 | luka-ve/AoC2020 | /06.py | 1,225 | 3.515625 | 4 | def part1(data):
groups = data.split('\n\n')
groups = [group.split('\n') for group in groups]
# Concatenate every group's individual strings and convert to set
n_different_questions_per_group = [len(set(''.join(group))) for group in groups]
return sum(n_different_questions_per_group)
# Concatena... |
6002393876b826ac00d3fbee852b6577a4dc10c0 | apoorvaagrawal86/PythonUdemyPython | /basicsyntax/string_methods2.py | 218 | 3.921875 | 4 | a = "1abc2abc3abc4abc"
print(a.replace('abc','ABC',2))
#count replaces the specified items in the string
sub = a[1:6]
print(sub)
#sub, first element is inclusive, last element is exclusive
step = a[1:6:3]
print(step)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.